Coverage Report

Created: 2021-06-15 06:44

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaType.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file implements type-related semantic analysis.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "TypeLocBuilder.h"
14
#include "clang/AST/ASTConsumer.h"
15
#include "clang/AST/ASTContext.h"
16
#include "clang/AST/ASTMutationListener.h"
17
#include "clang/AST/ASTStructuralEquivalence.h"
18
#include "clang/AST/CXXInheritance.h"
19
#include "clang/AST/DeclObjC.h"
20
#include "clang/AST/DeclTemplate.h"
21
#include "clang/AST/Expr.h"
22
#include "clang/AST/TypeLoc.h"
23
#include "clang/AST/TypeLocVisitor.h"
24
#include "clang/Basic/PartialDiagnostic.h"
25
#include "clang/Basic/TargetInfo.h"
26
#include "clang/Lex/Preprocessor.h"
27
#include "clang/Sema/DeclSpec.h"
28
#include "clang/Sema/DelayedDiagnostic.h"
29
#include "clang/Sema/Lookup.h"
30
#include "clang/Sema/ParsedTemplate.h"
31
#include "clang/Sema/ScopeInfo.h"
32
#include "clang/Sema/SemaInternal.h"
33
#include "clang/Sema/Template.h"
34
#include "clang/Sema/TemplateInstCallback.h"
35
#include "llvm/ADT/SmallPtrSet.h"
36
#include "llvm/ADT/SmallString.h"
37
#include "llvm/ADT/StringSwitch.h"
38
#include "llvm/IR/DerivedTypes.h"
39
#include "llvm/Support/ErrorHandling.h"
40
#include <bitset>
41
42
using namespace clang;
43
44
enum TypeDiagSelector {
45
  TDS_Function,
46
  TDS_Pointer,
47
  TDS_ObjCObjOrBlock
48
};
49
50
/// isOmittedBlockReturnType - Return true if this declarator is missing a
51
/// return type because this is a omitted return type on a block literal.
52
2.99k
static bool isOmittedBlockReturnType(const Declarator &D) {
53
2.99k
  if (D.getContext() != DeclaratorContext::BlockLiteral ||
54
2.99k
      
D.getDeclSpec().hasTypeSpecifier()2.64k
)
55
349
    return false;
56
57
2.64k
  if (D.getNumTypeObjects() == 0)
58
5
    return true;   // ^{ ... }
59
60
2.64k
  if (D.getNumTypeObjects() == 1 &&
61
2.64k
      
D.getTypeObject(0).Kind == DeclaratorChunk::Function2.64k
)
62
2.64k
    return true;   // ^(int X, float Y) { ... }
63
64
1
  return false;
65
2.64k
}
66
67
/// diagnoseBadTypeAttribute - Diagnoses a type attribute which
68
/// doesn't apply to the given type.
69
static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr,
70
29
                                     QualType type) {
71
29
  TypeDiagSelector WhichType;
72
29
  bool useExpansionLoc = true;
73
29
  switch (attr.getKind()) {
74
1
  case ParsedAttr::AT_ObjCGC:
75
1
    WhichType = TDS_Pointer;
76
1
    break;
77
6
  case ParsedAttr::AT_ObjCOwnership:
78
6
    WhichType = TDS_ObjCObjOrBlock;
79
6
    break;
80
22
  default:
81
    // Assume everything else was a function attribute.
82
22
    WhichType = TDS_Function;
83
22
    useExpansionLoc = false;
84
22
    break;
85
29
  }
86
87
29
  SourceLocation loc = attr.getLoc();
88
29
  StringRef name = attr.getAttrName()->getName();
89
90
  // The GC attributes are usually written with macros;  special-case them.
91
29
  IdentifierInfo *II = attr.isArgIdent(0) ? 
attr.getArgAsIdent(0)->Ident7
92
29
                                          : 
nullptr22
;
93
29
  if (useExpansionLoc && 
loc.isMacroID()7
&&
II5
) {
94
5
    if (II->isStr("strong")) {
95
2
      if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
96
3
    } else if (II->isStr("weak")) {
97
3
      if (S.findMacroSpelling(loc, "__weak")) 
name = "__weak"2
;
98
3
    }
99
5
  }
100
101
29
  S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
102
29
    << type;
103
29
}
104
105
// objc_gc applies to Objective-C pointers or, otherwise, to the
106
// smallest available pointer type (i.e. 'void*' in 'void**').
107
#define OBJC_POINTER_TYPE_ATTRS_CASELIST                                       \
108
289
  case ParsedAttr::AT_ObjCGC:                                                  \
109
7.86k
  case ParsedAttr::AT_ObjCOwnership
110
111
// Calling convention attributes.
112
#define CALLING_CONV_ATTRS_CASELIST                                            \
113
161k
  case ParsedAttr::AT_CDecl:                                                   \
114
161k
  case ParsedAttr::AT_FastCall:                                                \
115
162k
  case ParsedAttr::AT_StdCall:                                                 \
116
162k
  case ParsedAttr::AT_ThisCall:                                                \
117
162k
  case ParsedAttr::AT_RegCall:                                                 \
118
162k
  case ParsedAttr::AT_Pascal:                                                  \
119
166k
  case ParsedAttr::AT_SwiftCall:                                               \
120
167k
  case ParsedAttr::AT_VectorCall:                                              \
121
167k
  case ParsedAttr::AT_AArch64VectorPcs:                                        \
122
167k
  case ParsedAttr::AT_MSABI:                                                   \
123
167k
  case ParsedAttr::AT_SysVABI:                                                 \
124
167k
  case ParsedAttr::AT_Pcs:                                                     \
125
167k
  case ParsedAttr::AT_IntelOclBicc:                                            \
126
167k
  case ParsedAttr::AT_PreserveMost:                                            \
127
167k
  case ParsedAttr::AT_PreserveAll
128
129
// Function type attributes.
130
#define FUNCTION_TYPE_ATTRS_CASELIST                                           \
131
146k
  case ParsedAttr::AT_NSReturnsRetained:                                       \
132
159k
  case ParsedAttr::AT_NoReturn:                                                \
133
159k
  case ParsedAttr::AT_Regparm:                                                 \
134
159k
  case ParsedAttr::AT_CmseNSCall:                                              \
135
159k
  case ParsedAttr::AT_AnyX86NoCallerSavedRegisters:                            \
136
159k
  case ParsedAttr::AT_AnyX86NoCfCheck:                                         \
137
160k
    CALLING_CONV_ATTRS_CASELIST
138
139
// Microsoft-specific type qualifiers.
140
#define MS_TYPE_ATTRS_CASELIST                                                 \
141
39
  case ParsedAttr::AT_Ptr32:                                                   \
142
59
  case ParsedAttr::AT_Ptr64:                                                   \
143
77
  case ParsedAttr::AT_SPtr:                                                    \
144
89
  case ParsedAttr::AT_UPtr
145
146
// Nullability qualifiers.
147
#define NULLABILITY_TYPE_ATTRS_CASELIST                                        \
148
1.01M
  case ParsedAttr::AT_TypeNonNull:                                             \
149
1.94M
  case ParsedAttr::AT_TypeNullable:                                            \
150
1.94M
  case ParsedAttr::AT_TypeNullableResult:                                      \
151
1.98M
  case ParsedAttr::AT_TypeNullUnspecified
152
153
namespace {
154
  /// An object which stores processing state for the entire
155
  /// GetTypeForDeclarator process.
156
  class TypeProcessingState {
157
    Sema &sema;
158
159
    /// The declarator being processed.
160
    Declarator &declarator;
161
162
    /// The index of the declarator chunk we're currently processing.
163
    /// May be the total number of valid chunks, indicating the
164
    /// DeclSpec.
165
    unsigned chunkIndex;
166
167
    /// Whether there are non-trivial modifications to the decl spec.
168
    bool trivial;
169
170
    /// Whether we saved the attributes in the decl spec.
171
    bool hasSavedAttrs;
172
173
    /// The original set of attributes on the DeclSpec.
174
    SmallVector<ParsedAttr *, 2> savedAttrs;
175
176
    /// A list of attributes to diagnose the uselessness of when the
177
    /// processing is complete.
178
    SmallVector<ParsedAttr *, 2> ignoredTypeAttrs;
179
180
    /// Attributes corresponding to AttributedTypeLocs that we have not yet
181
    /// populated.
182
    // FIXME: The two-phase mechanism by which we construct Types and fill
183
    // their TypeLocs makes it hard to correctly assign these. We keep the
184
    // attributes in creation order as an attempt to make them line up
185
    // properly.
186
    using TypeAttrPair = std::pair<const AttributedType*, const Attr*>;
187
    SmallVector<TypeAttrPair, 8> AttrsForTypes;
188
    bool AttrsForTypesSorted = true;
189
190
    /// MacroQualifiedTypes mapping to macro expansion locations that will be
191
    /// stored in a MacroQualifiedTypeLoc.
192
    llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros;
193
194
    /// Flag to indicate we parsed a noderef attribute. This is used for
195
    /// validating that noderef was used on a pointer or array.
196
    bool parsedNoDeref;
197
198
  public:
199
    TypeProcessingState(Sema &sema, Declarator &declarator)
200
        : sema(sema), declarator(declarator),
201
          chunkIndex(declarator.getNumTypeObjects()), trivial(true),
202
137M
          hasSavedAttrs(false), parsedNoDeref(false) {}
203
204
902M
    Sema &getSema() const {
205
902M
      return sema;
206
902M
    }
207
208
891M
    Declarator &getDeclarator() const {
209
891M
      return declarator;
210
891M
    }
211
212
137M
    bool isProcessingDeclSpec() const {
213
137M
      return chunkIndex == declarator.getNumTypeObjects();
214
137M
    }
215
216
1.51M
    unsigned getCurrentChunkIndex() const {
217
1.51M
      return chunkIndex;
218
1.51M
    }
219
220
42.1M
    void setCurrentChunkIndex(unsigned idx) {
221
42.1M
      assert(idx <= declarator.getNumTypeObjects());
222
0
      chunkIndex = idx;
223
42.1M
    }
224
225
137M
    ParsedAttributesView &getCurrentAttributes() const {
226
137M
      if (isProcessingDeclSpec())
227
137M
        return getMutableDeclSpec().getAttributes();
228
30
      return declarator.getTypeObject(chunkIndex).getAttrs();
229
137M
    }
230
231
    /// Save the current set of attributes on the DeclSpec.
232
59.9k
    void saveDeclSpecAttrs() {
233
      // Don't try to save them multiple times.
234
59.9k
      if (hasSavedAttrs) 
return637
;
235
236
59.3k
      DeclSpec &spec = getMutableDeclSpec();
237
59.3k
      for (ParsedAttr &AL : spec.getAttributes())
238
194k
        savedAttrs.push_back(&AL);
239
59.3k
      trivial &= savedAttrs.empty();
240
59.3k
      hasSavedAttrs = true;
241
59.3k
    }
242
243
    /// Record that we had nowhere to put the given type attribute.
244
    /// We will diagnose such attributes later.
245
22
    void addIgnoredTypeAttr(ParsedAttr &attr) {
246
22
      ignoredTypeAttrs.push_back(&attr);
247
22
    }
248
249
    /// Diagnose all the ignored type attributes, given that the
250
    /// declarator worked out to the given type.
251
137M
    void diagnoseIgnoredTypeAttrs(QualType type) const {
252
137M
      for (auto *Attr : ignoredTypeAttrs)
253
22
        diagnoseBadTypeAttribute(getSema(), *Attr, type);
254
137M
    }
255
256
    /// Get an attributed type for the given attribute, and remember the Attr
257
    /// object so that we can attach it to the AttributedTypeLoc.
258
    QualType getAttributedType(Attr *A, QualType ModifiedType,
259
3.18M
                               QualType EquivType) {
260
3.18M
      QualType T =
261
3.18M
          sema.Context.getAttributedType(A->getKind(), ModifiedType, EquivType);
262
3.18M
      AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A});
263
3.18M
      AttrsForTypesSorted = false;
264
3.18M
      return T;
265
3.18M
    }
266
267
    /// Completely replace the \c auto in \p TypeWithAuto by
268
    /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if
269
    /// necessary.
270
2.16k
    QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) {
271
2.16k
      QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement);
272
2.16k
      if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) {
273
        // Attributed type still should be an attributed type after replacement.
274
1
        auto *NewAttrTy = cast<AttributedType>(T.getTypePtr());
275
1
        for (TypeAttrPair &A : AttrsForTypes) {
276
1
          if (A.first == AttrTy)
277
1
            A.first = NewAttrTy;
278
1
        }
279
1
        AttrsForTypesSorted = false;
280
1
      }
281
2.16k
      return T;
282
2.16k
    }
283
284
    /// Extract and remove the Attr* for a given attributed type.
285
3.18M
    const Attr *takeAttrForAttributedType(const AttributedType *AT) {
286
3.18M
      if (!AttrsForTypesSorted) {
287
3.04M
        llvm::stable_sort(AttrsForTypes, llvm::less_first());
288
3.04M
        AttrsForTypesSorted = true;
289
3.04M
      }
290
291
      // FIXME: This is quadratic if we have lots of reuses of the same
292
      // attributed type.
293
3.18M
      for (auto It = std::partition_point(
294
3.18M
               AttrsForTypes.begin(), AttrsForTypes.end(),
295
3.45M
               [=](const TypeAttrPair &A) { return A.first < AT; });
296
3.18M
           It != AttrsForTypes.end() && It->first == AT; 
++It0
) {
297
3.18M
        if (It->second) {
298
3.18M
          const Attr *Result = It->second;
299
3.18M
          It->second = nullptr;
300
3.18M
          return Result;
301
3.18M
        }
302
3.18M
      }
303
304
3.18M
      
llvm_unreachable0
("no Attr* for AttributedType*");
305
3.18M
    }
306
307
    SourceLocation
308
209k
    getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const {
309
209k
      auto FoundLoc = LocsForMacros.find(MQT);
310
209k
      assert(FoundLoc != LocsForMacros.end() &&
311
209k
             "Unable to find macro expansion location for MacroQualifedType");
312
0
      return FoundLoc->second;
313
209k
    }
314
315
    void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT,
316
210k
                                              SourceLocation Loc) {
317
210k
      LocsForMacros[MQT] = Loc;
318
210k
    }
319
320
317M
    void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; }
321
322
41.8M
    bool didParseNoDeref() const { return parsedNoDeref; }
323
324
137M
    ~TypeProcessingState() {
325
137M
      if (trivial) 
return137M
;
326
327
59.3k
      restoreDeclSpecAttrs();
328
59.3k
    }
329
330
  private:
331
138M
    DeclSpec &getMutableDeclSpec() const {
332
138M
      return const_cast<DeclSpec&>(declarator.getDeclSpec());
333
138M
    }
334
335
59.3k
    void restoreDeclSpecAttrs() {
336
59.3k
      assert(hasSavedAttrs);
337
338
0
      getMutableDeclSpec().getAttributes().clearListOnly();
339
59.3k
      for (ParsedAttr *AL : savedAttrs)
340
194k
        getMutableDeclSpec().getAttributes().addAtEnd(AL);
341
59.3k
    }
342
  };
343
} // end anonymous namespace
344
345
static void moveAttrFromListToList(ParsedAttr &attr,
346
                                   ParsedAttributesView &fromList,
347
68.0k
                                   ParsedAttributesView &toList) {
348
68.0k
  fromList.remove(&attr);
349
68.0k
  toList.addAtEnd(&attr);
350
68.0k
}
351
352
/// The location of a type attribute.
353
enum TypeAttrLocation {
354
  /// The attribute is in the decl-specifier-seq.
355
  TAL_DeclSpec,
356
  /// The attribute is part of a DeclaratorChunk.
357
  TAL_DeclChunk,
358
  /// The attribute is immediately after the declaration's name.
359
  TAL_DeclName
360
};
361
362
static void processTypeAttrs(TypeProcessingState &state, QualType &type,
363
                             TypeAttrLocation TAL, ParsedAttributesView &attrs);
364
365
static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
366
                                   QualType &type);
367
368
static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
369
                                             ParsedAttr &attr, QualType &type);
370
371
static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
372
                                 QualType &type);
373
374
static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
375
                                        ParsedAttr &attr, QualType &type);
376
377
static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
378
7.86k
                                      ParsedAttr &attr, QualType &type) {
379
7.86k
  if (attr.getKind() == ParsedAttr::AT_ObjCGC)
380
289
    return handleObjCGCTypeAttr(state, attr, type);
381
7.57k
  assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership);
382
0
  return handleObjCOwnershipTypeAttr(state, attr, type);
383
7.86k
}
384
385
/// Given the index of a declarator chunk, check whether that chunk
386
/// directly specifies the return type of a function and, if so, find
387
/// an appropriate place for it.
388
///
389
/// \param i - a notional index which the search will start
390
///   immediately inside
391
///
392
/// \param onlyBlockPointers Whether we should only look into block
393
/// pointer types (vs. all pointer types).
394
static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
395
                                                unsigned i,
396
5.26k
                                                bool onlyBlockPointers) {
397
5.26k
  assert(i <= declarator.getNumTypeObjects());
398
399
0
  DeclaratorChunk *result = nullptr;
400
401
  // First, look inwards past parens for a function declarator.
402
5.30k
  for (; i != 0; 
--i37
) {
403
3.70k
    DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
404
3.70k
    switch (fnChunk.Kind) {
405
9
    case DeclaratorChunk::Paren:
406
9
      continue;
407
408
    // If we find anything except a function, bail out.
409
1.51k
    case DeclaratorChunk::Pointer:
410
1.51k
    case DeclaratorChunk::BlockPointer:
411
3.48k
    case DeclaratorChunk::Array:
412
3.65k
    case DeclaratorChunk::Reference:
413
3.65k
    case DeclaratorChunk::MemberPointer:
414
3.65k
    case DeclaratorChunk::Pipe:
415
3.65k
      return result;
416
417
    // If we do find a function declarator, scan inwards from that,
418
    // looking for a (block-)pointer declarator.
419
42
    case DeclaratorChunk::Function:
420
78
      for (--i; i != 0; 
--i36
) {
421
64
        DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
422
64
        switch (ptrChunk.Kind) {
423
32
        case DeclaratorChunk::Paren:
424
32
        case DeclaratorChunk::Array:
425
32
        case DeclaratorChunk::Function:
426
32
        case DeclaratorChunk::Reference:
427
32
        case DeclaratorChunk::Pipe:
428
32
          continue;
429
430
2
        case DeclaratorChunk::MemberPointer:
431
10
        case DeclaratorChunk::Pointer:
432
10
          if (onlyBlockPointers)
433
4
            continue;
434
435
10
          
LLVM_FALLTHROUGH6
;6
436
437
28
        case DeclaratorChunk::BlockPointer:
438
28
          result = &ptrChunk;
439
28
          goto continue_outer;
440
64
        }
441
64
        
llvm_unreachable0
("bad declarator chunk kind");
442
64
      }
443
444
      // If we run out of declarators doing that, we're done.
445
14
      return result;
446
3.70k
    }
447
3.70k
    
llvm_unreachable0
("bad declarator chunk kind");
448
449
    // Okay, reconsider from our new point.
450
28
  continue_outer: ;
451
28
  }
452
453
  // Ran out of chunks, bail out.
454
1.59k
  return result;
455
5.26k
}
456
457
/// Given that an objc_gc attribute was written somewhere on a
458
/// declaration *other* than on the declarator itself (for which, use
459
/// distributeObjCPointerTypeAttrFromDeclarator), and given that it
460
/// didn't apply in whatever position it was written in, try to move
461
/// it to a more appropriate position.
462
static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
463
1.59k
                                          ParsedAttr &attr, QualType type) {
464
1.59k
  Declarator &declarator = state.getDeclarator();
465
466
  // Move it to the outermost normal or block pointer declarator.
467
1.59k
  for (unsigned i = state.getCurrentChunkIndex(); i != 0; 
--i0
) {
468
1.58k
    DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
469
1.58k
    switch (chunk.Kind) {
470
1.57k
    case DeclaratorChunk::Pointer:
471
1.57k
    case DeclaratorChunk::BlockPointer: {
472
      // But don't move an ARC ownership attribute to the return type
473
      // of a block.
474
1.57k
      DeclaratorChunk *destChunk = nullptr;
475
1.57k
      if (state.isProcessingDeclSpec() &&
476
1.57k
          attr.getKind() == ParsedAttr::AT_ObjCOwnership)
477
1.50k
        destChunk = maybeMovePastReturnType(declarator, i - 1,
478
1.50k
                                            /*onlyBlockPointers=*/true);
479
1.57k
      if (!destChunk) 
destChunk = &chunk1.57k
;
480
481
1.57k
      moveAttrFromListToList(attr, state.getCurrentAttributes(),
482
1.57k
                             destChunk->getAttrs());
483
1.57k
      return;
484
1.57k
    }
485
486
0
    case DeclaratorChunk::Paren:
487
0
    case DeclaratorChunk::Array:
488
0
      continue;
489
490
    // We may be starting at the return type of a block.
491
8
    case DeclaratorChunk::Function:
492
8
      if (state.isProcessingDeclSpec() &&
493
8
          attr.getKind() == ParsedAttr::AT_ObjCOwnership) {
494
8
        if (DeclaratorChunk *dest = maybeMovePastReturnType(
495
8
                                      declarator, i,
496
8
                                      /*onlyBlockPointers=*/true)) {
497
8
          moveAttrFromListToList(attr, state.getCurrentAttributes(),
498
8
                                 dest->getAttrs());
499
8
          return;
500
8
        }
501
8
      }
502
0
      goto error;
503
504
    // Don't walk through these.
505
0
    case DeclaratorChunk::Reference:
506
0
    case DeclaratorChunk::MemberPointer:
507
0
    case DeclaratorChunk::Pipe:
508
0
      goto error;
509
1.58k
    }
510
1.58k
  }
511
6
 error:
512
513
6
  diagnoseBadTypeAttribute(state.getSema(), attr, type);
514
6
}
515
516
/// Distribute an objc_gc type attribute that was written on the
517
/// declarator.
518
static void distributeObjCPointerTypeAttrFromDeclarator(
519
18
    TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) {
520
18
  Declarator &declarator = state.getDeclarator();
521
522
  // objc_gc goes on the innermost pointer to something that's not a
523
  // pointer.
524
18
  unsigned innermost = -1U;
525
18
  bool considerDeclSpec = true;
526
28
  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; 
++i10
) {
527
15
    DeclaratorChunk &chunk = declarator.getTypeObject(i);
528
15
    switch (chunk.Kind) {
529
0
    case DeclaratorChunk::Pointer:
530
4
    case DeclaratorChunk::BlockPointer:
531
4
      innermost = i;
532
4
      continue;
533
534
0
    case DeclaratorChunk::Reference:
535
0
    case DeclaratorChunk::MemberPointer:
536
4
    case DeclaratorChunk::Paren:
537
6
    case DeclaratorChunk::Array:
538
6
    case DeclaratorChunk::Pipe:
539
6
      continue;
540
541
5
    case DeclaratorChunk::Function:
542
5
      considerDeclSpec = false;
543
5
      goto done;
544
15
    }
545
15
  }
546
18
 done:
547
548
  // That might actually be the decl spec if we weren't blocked by
549
  // anything in the declarator.
550
18
  if (considerDeclSpec) {
551
13
    if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
552
      // Splice the attribute into the decl spec.  Prevents the
553
      // attribute from being applied multiple times and gives
554
      // the source-location-filler something to work with.
555
13
      state.saveDeclSpecAttrs();
556
13
      declarator.getMutableDeclSpec().getAttributes().takeOneFrom(
557
13
          declarator.getAttributes(), &attr);
558
13
      return;
559
13
    }
560
13
  }
561
562
  // Otherwise, if we found an appropriate chunk, splice the attribute
563
  // into it.
564
5
  if (innermost != -1U) {
565
4
    moveAttrFromListToList(attr, declarator.getAttributes(),
566
4
                           declarator.getTypeObject(innermost).getAttrs());
567
4
    return;
568
4
  }
569
570
  // Otherwise, diagnose when we're done building the type.
571
1
  declarator.getAttributes().remove(&attr);
572
1
  state.addIgnoredTypeAttr(attr);
573
1
}
574
575
/// A function type attribute was written somewhere in a declaration
576
/// *other* than on the declarator itself or in the decl spec.  Given
577
/// that it didn't apply in whatever position it was written in, try
578
/// to move it to a more appropriate position.
579
static void distributeFunctionTypeAttr(TypeProcessingState &state,
580
31
                                       ParsedAttr &attr, QualType type) {
581
31
  Declarator &declarator = state.getDeclarator();
582
583
  // Try to push the attribute from the return type of a function to
584
  // the function itself.
585
33
  for (unsigned i = state.getCurrentChunkIndex(); i != 0; 
--i2
) {
586
32
    DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
587
32
    switch (chunk.Kind) {
588
30
    case DeclaratorChunk::Function:
589
30
      moveAttrFromListToList(attr, state.getCurrentAttributes(),
590
30
                             chunk.getAttrs());
591
30
      return;
592
593
2
    case DeclaratorChunk::Paren:
594
2
    case DeclaratorChunk::Pointer:
595
2
    case DeclaratorChunk::BlockPointer:
596
2
    case DeclaratorChunk::Array:
597
2
    case DeclaratorChunk::Reference:
598
2
    case DeclaratorChunk::MemberPointer:
599
2
    case DeclaratorChunk::Pipe:
600
2
      continue;
601
32
    }
602
32
  }
603
604
1
  diagnoseBadTypeAttribute(state.getSema(), attr, type);
605
1
}
606
607
/// Try to distribute a function type attribute to the innermost
608
/// function chunk or type.  Returns true if the attribute was
609
/// distributed, false if no location was found.
610
static bool distributeFunctionTypeAttrToInnermost(
611
    TypeProcessingState &state, ParsedAttr &attr,
612
66.4k
    ParsedAttributesView &attrList, QualType &declSpecType) {
613
66.4k
  Declarator &declarator = state.getDeclarator();
614
615
  // Put it on the innermost function chunk, if there is one.
616
66.7k
  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; 
++i278
) {
617
66.6k
    DeclaratorChunk &chunk = declarator.getTypeObject(i);
618
66.6k
    if (chunk.Kind != DeclaratorChunk::Function) 
continue278
;
619
620
66.3k
    moveAttrFromListToList(attr, attrList, chunk.getAttrs());
621
66.3k
    return true;
622
66.6k
  }
623
624
56
  return handleFunctionTypeAttr(state, attr, declSpecType);
625
66.4k
}
626
627
/// A function type attribute was written in the decl spec.  Try to
628
/// apply it somewhere.
629
static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
630
                                                   ParsedAttr &attr,
631
59.9k
                                                   QualType &declSpecType) {
632
59.9k
  state.saveDeclSpecAttrs();
633
634
  // C++11 attributes before the decl specifiers actually appertain to
635
  // the declarators. Move them straight there. We don't support the
636
  // 'put them wherever you like' semantics we allow for GNU attributes.
637
59.9k
  if (attr.isCXX11Attribute()) {
638
16
    moveAttrFromListToList(attr, state.getCurrentAttributes(),
639
16
                           state.getDeclarator().getAttributes());
640
16
    return;
641
16
  }
642
643
  // Try to distribute to the innermost.
644
59.9k
  if (distributeFunctionTypeAttrToInnermost(
645
59.9k
          state, attr, state.getCurrentAttributes(), declSpecType))
646
59.9k
    return;
647
648
  // If that failed, diagnose the bad attribute when the declarator is
649
  // fully built.
650
9
  state.addIgnoredTypeAttr(attr);
651
9
}
652
653
/// A function type attribute was written on the declarator.  Try to
654
/// apply it somewhere.
655
static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
656
                                                     ParsedAttr &attr,
657
6.48k
                                                     QualType &declSpecType) {
658
6.48k
  Declarator &declarator = state.getDeclarator();
659
660
  // Try to distribute to the innermost.
661
6.48k
  if (distributeFunctionTypeAttrToInnermost(
662
6.48k
          state, attr, declarator.getAttributes(), declSpecType))
663
6.47k
    return;
664
665
  // If that failed, diagnose the bad attribute when the declarator is
666
  // fully built.
667
12
  declarator.getAttributes().remove(&attr);
668
12
  state.addIgnoredTypeAttr(attr);
669
12
}
670
671
/// Given that there are attributes written on the declarator
672
/// itself, try to distribute any type attributes to the appropriate
673
/// declarator chunk.
674
///
675
/// These are attributes like the following:
676
///   int f ATTR;
677
///   int (f ATTR)();
678
/// but not necessarily this:
679
///   int f() ATTR;
680
static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
681
2.01M
                                              QualType &declSpecType) {
682
  // Collect all the type attributes from the declarator itself.
683
2.01M
  assert(!state.getDeclarator().getAttributes().empty() &&
684
2.01M
         "declarator has no attrs!");
685
  // The called functions in this loop actually remove things from the current
686
  // list, so iterating over the existing list isn't possible.  Instead, make a
687
  // non-owning copy and iterate over that.
688
0
  ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()};
689
4.42M
  for (ParsedAttr &attr : AttrsCopy) {
690
    // Do not distribute C++11 attributes. They have strict rules for what
691
    // they appertain to.
692
4.42M
    if (attr.isCXX11Attribute())
693
185
      continue;
694
695
4.42M
    switch (attr.getKind()) {
696
18
    
OBJC_POINTER_TYPE_ATTRS_CASELIST2
:
697
18
      distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType);
698
18
      break;
699
700
6.48k
    
FUNCTION_TYPE_ATTRS_CASELIST505
:
701
6.48k
      distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType);
702
6.48k
      break;
703
704
0
    MS_TYPE_ATTRS_CASELIST:
705
      // Microsoft type attributes cannot go after the declarator-id.
706
0
      continue;
707
708
0
    NULLABILITY_TYPE_ATTRS_CASELIST:
709
      // Nullability specifiers cannot go after the declarator-id.
710
711
    // Objective-C __kindof does not get distributed.
712
0
    case ParsedAttr::AT_ObjCKindOf:
713
0
      continue;
714
715
4.41M
    default:
716
4.41M
      break;
717
4.42M
    }
718
4.42M
  }
719
2.01M
}
720
721
/// Add a synthetic '()' to a block-literal declarator if it is
722
/// required, given the return type.
723
static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
724
2.96k
                                          QualType declSpecType) {
725
2.96k
  Declarator &declarator = state.getDeclarator();
726
727
  // First, check whether the declarator would produce a function,
728
  // i.e. whether the innermost semantic chunk is a function.
729
2.96k
  if (declarator.isFunctionDeclarator()) {
730
    // If so, make that declarator a prototyped declarator.
731
2.94k
    declarator.getFunctionTypeInfo().hasPrototype = true;
732
2.94k
    return;
733
2.94k
  }
734
735
  // If there are any type objects, the type as written won't name a
736
  // function, regardless of the decl spec type.  This is because a
737
  // block signature declarator is always an abstract-declarator, and
738
  // abstract-declarators can't just be parentheses chunks.  Therefore
739
  // we need to build a function chunk unless there are no type
740
  // objects and the decl spec type is a function.
741
23
  if (!declarator.getNumTypeObjects() && 
declSpecType->isFunctionType()20
)
742
3
    return;
743
744
  // Note that there *are* cases with invalid declarators where
745
  // declarators consist solely of parentheses.  In general, these
746
  // occur only in failed efforts to make function declarators, so
747
  // faking up the function chunk is still the right thing to do.
748
749
  // Otherwise, we need to fake up a function declarator.
750
20
  SourceLocation loc = declarator.getBeginLoc();
751
752
  // ...and *prepend* it to the declarator.
753
20
  SourceLocation NoLoc;
754
20
  declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
755
20
      /*HasProto=*/true,
756
20
      /*IsAmbiguous=*/false,
757
20
      /*LParenLoc=*/NoLoc,
758
20
      /*ArgInfo=*/nullptr,
759
20
      /*NumParams=*/0,
760
20
      /*EllipsisLoc=*/NoLoc,
761
20
      /*RParenLoc=*/NoLoc,
762
20
      /*RefQualifierIsLvalueRef=*/true,
763
20
      /*RefQualifierLoc=*/NoLoc,
764
20
      /*MutableLoc=*/NoLoc, EST_None,
765
20
      /*ESpecRange=*/SourceRange(),
766
20
      /*Exceptions=*/nullptr,
767
20
      /*ExceptionRanges=*/nullptr,
768
20
      /*NumExceptions=*/0,
769
20
      /*NoexceptExpr=*/nullptr,
770
20
      /*ExceptionSpecTokens=*/nullptr,
771
20
      /*DeclsInPrototype=*/None, loc, loc, declarator));
772
773
  // For consistency, make sure the state still has us as processing
774
  // the decl spec.
775
20
  assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
776
0
  state.setCurrentChunkIndex(declarator.getNumTypeObjects());
777
20
}
778
779
static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
780
                                            unsigned &TypeQuals,
781
                                            QualType TypeSoFar,
782
                                            unsigned RemoveTQs,
783
2.71k
                                            unsigned DiagID) {
784
  // If this occurs outside a template instantiation, warn the user about
785
  // it; they probably didn't mean to specify a redundant qualifier.
786
2.71k
  typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
787
2.71k
  for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
788
2.71k
                       QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()),
789
2.71k
                       QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
790
10.8k
                       QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
791
10.8k
    if (!(RemoveTQs & Qual.first))
792
90
      continue;
793
794
10.7k
    if (!S.inTemplateInstantiation()) {
795
10.7k
      if (TypeQuals & Qual.first)
796
69
        S.Diag(Qual.second, DiagID)
797
69
          << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
798
69
          << FixItHint::CreateRemoval(Qual.second);
799
10.7k
    }
800
801
10.7k
    TypeQuals &= ~Qual.first;
802
10.7k
  }
803
2.71k
}
804
805
/// Return true if this is omitted block return type. Also check type
806
/// attributes and type qualifiers when returning true.
807
static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
808
2.99k
                                        QualType Result) {
809
2.99k
  if (!isOmittedBlockReturnType(declarator))
810
350
    return false;
811
812
  // Warn if we see type attributes for omitted return type on a block literal.
813
2.64k
  SmallVector<ParsedAttr *, 2> ToBeRemoved;
814
2.64k
  for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) {
815
22
    if (AL.isInvalid() || !AL.isTypeAttr())
816
17
      continue;
817
5
    S.Diag(AL.getLoc(),
818
5
           diag::warn_block_literal_attributes_on_omitted_return_type)
819
5
        << AL;
820
5
    ToBeRemoved.push_back(&AL);
821
5
  }
822
  // Remove bad attributes from the list.
823
2.64k
  for (ParsedAttr *AL : ToBeRemoved)
824
5
    declarator.getMutableDeclSpec().getAttributes().remove(AL);
825
826
  // Warn if we see type qualifiers for omitted return type on a block literal.
827
2.64k
  const DeclSpec &DS = declarator.getDeclSpec();
828
2.64k
  unsigned TypeQuals = DS.getTypeQualifiers();
829
2.64k
  diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
830
2.64k
      diag::warn_block_literal_qualifiers_on_omitted_return_type);
831
2.64k
  declarator.getMutableDeclSpec().ClearTypeQualifiers();
832
833
2.64k
  return true;
834
2.99k
}
835
836
/// Apply Objective-C type arguments to the given type.
837
static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
838
                                  ArrayRef<TypeSourceInfo *> typeArgs,
839
                                  SourceRange typeArgsRange,
840
127k
                                  bool failOnError = false) {
841
  // We can only apply type arguments to an Objective-C class type.
842
127k
  const auto *objcObjectType = type->getAs<ObjCObjectType>();
843
127k
  if (!objcObjectType || 
!objcObjectType->getInterface()127k
) {
844
1
    S.Diag(loc, diag::err_objc_type_args_non_class)
845
1
      << type
846
1
      << typeArgsRange;
847
848
1
    if (failOnError)
849
0
      return QualType();
850
1
    return type;
851
1
  }
852
853
  // The class type must be parameterized.
854
127k
  ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
855
127k
  ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
856
127k
  if (!typeParams) {
857
1
    S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
858
1
      << objcClass->getDeclName()
859
1
      << FixItHint::CreateRemoval(typeArgsRange);
860
861
1
    if (failOnError)
862
0
      return QualType();
863
864
1
    return type;
865
1
  }
866
867
  // The type must not already be specialized.
868
127k
  if (objcObjectType->isSpecialized()) {
869
3
    S.Diag(loc, diag::err_objc_type_args_specialized_class)
870
3
      << type
871
3
      << FixItHint::CreateRemoval(typeArgsRange);
872
873
3
    if (failOnError)
874
0
      return QualType();
875
876
3
    return type;
877
3
  }
878
879
  // Check the type arguments.
880
127k
  SmallVector<QualType, 4> finalTypeArgs;
881
127k
  unsigned numTypeParams = typeParams->size();
882
127k
  bool anyPackExpansions = false;
883
284k
  for (unsigned i = 0, n = typeArgs.size(); i != n; 
++i157k
) {
884
157k
    TypeSourceInfo *typeArgInfo = typeArgs[i];
885
157k
    QualType typeArg = typeArgInfo->getType();
886
887
    // Type arguments cannot have explicit qualifiers or nullability.
888
    // We ignore indirect sources of these, e.g. behind typedefs or
889
    // template arguments.
890
157k
    if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
891
17
      bool diagnosed = false;
892
17
      SourceRange rangeToRemove;
893
17
      if (auto attr = qual.getAs<AttributedTypeLoc>()) {
894
12
        rangeToRemove = attr.getLocalSourceRange();
895
12
        if (attr.getTypePtr()->getImmediateNullability()) {
896
1
          typeArg = attr.getTypePtr()->getModifiedType();
897
1
          S.Diag(attr.getBeginLoc(),
898
1
                 diag::err_objc_type_arg_explicit_nullability)
899
1
              << typeArg << FixItHint::CreateRemoval(rangeToRemove);
900
1
          diagnosed = true;
901
1
        }
902
12
      }
903
904
17
      if (!diagnosed) {
905
16
        S.Diag(qual.getBeginLoc(), diag::err_objc_type_arg_qualified)
906
16
            << typeArg << typeArg.getQualifiers().getAsString()
907
16
            << FixItHint::CreateRemoval(rangeToRemove);
908
16
      }
909
17
    }
910
911
    // Remove qualifiers even if they're non-local.
912
157k
    typeArg = typeArg.getUnqualifiedType();
913
914
157k
    finalTypeArgs.push_back(typeArg);
915
916
157k
    if (typeArg->getAs<PackExpansionType>())
917
1
      anyPackExpansions = true;
918
919
    // Find the corresponding type parameter, if there is one.
920
157k
    ObjCTypeParamDecl *typeParam = nullptr;
921
157k
    if (!anyPackExpansions) {
922
157k
      if (i < numTypeParams) {
923
157k
        typeParam = typeParams->begin()[i];
924
157k
      } else {
925
        // Too many arguments.
926
2
        S.Diag(loc, diag::err_objc_type_args_wrong_arity)
927
2
          << false
928
2
          << objcClass->getDeclName()
929
2
          << (unsigned)typeArgs.size()
930
2
          << numTypeParams;
931
2
        S.Diag(objcClass->getLocation(), diag::note_previous_decl)
932
2
          << objcClass;
933
934
2
        if (failOnError)
935
1
          return QualType();
936
937
1
        return type;
938
2
      }
939
157k
    }
940
941
    // Objective-C object pointer types must be substitutable for the bounds.
942
157k
    if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
943
      // If we don't have a type parameter to match against, assume
944
      // everything is fine. There was a prior pack expansion that
945
      // means we won't be able to match anything.
946
157k
      if (!typeParam) {
947
0
        assert(anyPackExpansions && "Too many arguments?");
948
0
        continue;
949
0
      }
950
951
      // Retrieve the bound.
952
157k
      QualType bound = typeParam->getUnderlyingType();
953
157k
      const auto *boundObjC = bound->getAs<ObjCObjectPointerType>();
954
955
      // Determine whether the type argument is substitutable for the bound.
956
157k
      if (typeArgObjC->isObjCIdType()) {
957
        // When the type argument is 'id', the only acceptable type
958
        // parameter bound is 'id'.
959
62.5k
        if (boundObjC->isObjCIdType())
960
62.5k
          continue;
961
94.7k
      } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
962
        // Otherwise, we follow the assignability rules.
963
94.7k
        continue;
964
94.7k
      }
965
966
      // Diagnose the mismatch.
967
6
      S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
968
6
             diag::err_objc_type_arg_does_not_match_bound)
969
6
          << typeArg << bound << typeParam->getDeclName();
970
6
      S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
971
6
        << typeParam->getDeclName();
972
973
6
      if (failOnError)
974
2
        return QualType();
975
976
4
      return type;
977
6
    }
978
979
    // Block pointer types are permitted for unqualified 'id' bounds.
980
232
    if (typeArg->isBlockPointerType()) {
981
      // If we don't have a type parameter to match against, assume
982
      // everything is fine. There was a prior pack expansion that
983
      // means we won't be able to match anything.
984
224
      if (!typeParam) {
985
0
        assert(anyPackExpansions && "Too many arguments?");
986
0
        continue;
987
0
      }
988
989
      // Retrieve the bound.
990
224
      QualType bound = typeParam->getUnderlyingType();
991
224
      if (bound->isBlockCompatibleObjCPointerType(S.Context))
992
224
        continue;
993
994
      // Diagnose the mismatch.
995
0
      S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
996
0
             diag::err_objc_type_arg_does_not_match_bound)
997
0
          << typeArg << bound << typeParam->getDeclName();
998
0
      S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
999
0
        << typeParam->getDeclName();
1000
1001
0
      if (failOnError)
1002
0
        return QualType();
1003
1004
0
      return type;
1005
0
    }
1006
1007
    // Dependent types will be checked at instantiation time.
1008
8
    if (typeArg->isDependentType()) {
1009
8
      continue;
1010
8
    }
1011
1012
    // Diagnose non-id-compatible type arguments.
1013
0
    S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
1014
0
           diag::err_objc_type_arg_not_id_compatible)
1015
0
        << typeArg << typeArgInfo->getTypeLoc().getSourceRange();
1016
1017
0
    if (failOnError)
1018
0
      return QualType();
1019
1020
0
    return type;
1021
0
  }
1022
1023
  // Make sure we didn't have the wrong number of arguments.
1024
127k
  if (!anyPackExpansions && 
finalTypeArgs.size() != numTypeParams127k
) {
1025
3
    S.Diag(loc, diag::err_objc_type_args_wrong_arity)
1026
3
      << (typeArgs.size() < typeParams->size())
1027
3
      << objcClass->getDeclName()
1028
3
      << (unsigned)finalTypeArgs.size()
1029
3
      << (unsigned)numTypeParams;
1030
3
    S.Diag(objcClass->getLocation(), diag::note_previous_decl)
1031
3
      << objcClass;
1032
1033
3
    if (failOnError)
1034
1
      return QualType();
1035
1036
2
    return type;
1037
3
  }
1038
1039
  // Success. Form the specialized type.
1040
127k
  return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
1041
127k
}
1042
1043
QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1044
                                      SourceLocation ProtocolLAngleLoc,
1045
                                      ArrayRef<ObjCProtocolDecl *> Protocols,
1046
                                      ArrayRef<SourceLocation> ProtocolLocs,
1047
                                      SourceLocation ProtocolRAngleLoc,
1048
0
                                      bool FailOnError) {
1049
0
  QualType Result = QualType(Decl->getTypeForDecl(), 0);
1050
0
  if (!Protocols.empty()) {
1051
0
    bool HasError;
1052
0
    Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1053
0
                                                 HasError);
1054
0
    if (HasError) {
1055
0
      Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers)
1056
0
        << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1057
0
      if (FailOnError) Result = QualType();
1058
0
    }
1059
0
    if (FailOnError && Result.isNull())
1060
0
      return QualType();
1061
0
  }
1062
1063
0
  return Result;
1064
0
}
1065
1066
QualType Sema::BuildObjCObjectType(QualType BaseType,
1067
                                   SourceLocation Loc,
1068
                                   SourceLocation TypeArgsLAngleLoc,
1069
                                   ArrayRef<TypeSourceInfo *> TypeArgs,
1070
                                   SourceLocation TypeArgsRAngleLoc,
1071
                                   SourceLocation ProtocolLAngleLoc,
1072
                                   ArrayRef<ObjCProtocolDecl *> Protocols,
1073
                                   ArrayRef<SourceLocation> ProtocolLocs,
1074
                                   SourceLocation ProtocolRAngleLoc,
1075
149k
                                   bool FailOnError) {
1076
149k
  QualType Result = BaseType;
1077
149k
  if (!TypeArgs.empty()) {
1078
127k
    Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
1079
127k
                               SourceRange(TypeArgsLAngleLoc,
1080
127k
                                           TypeArgsRAngleLoc),
1081
127k
                               FailOnError);
1082
127k
    if (FailOnError && 
Result.isNull()17
)
1083
4
      return QualType();
1084
127k
  }
1085
1086
149k
  if (!Protocols.empty()) {
1087
22.1k
    bool HasError;
1088
22.1k
    Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1089
22.1k
                                                 HasError);
1090
22.1k
    if (HasError) {
1091
1
      Diag(Loc, diag::err_invalid_protocol_qualifiers)
1092
1
        << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1093
1
      if (FailOnError) 
Result = QualType()0
;
1094
1
    }
1095
22.1k
    if (FailOnError && 
Result.isNull()0
)
1096
0
      return QualType();
1097
22.1k
  }
1098
1099
149k
  return Result;
1100
149k
}
1101
1102
TypeResult Sema::actOnObjCProtocolQualifierType(
1103
             SourceLocation lAngleLoc,
1104
             ArrayRef<Decl *> protocols,
1105
             ArrayRef<SourceLocation> protocolLocs,
1106
7
             SourceLocation rAngleLoc) {
1107
  // Form id<protocol-list>.
1108
7
  QualType Result = Context.getObjCObjectType(
1109
7
                      Context.ObjCBuiltinIdTy, { },
1110
7
                      llvm::makeArrayRef(
1111
7
                        (ObjCProtocolDecl * const *)protocols.data(),
1112
7
                        protocols.size()),
1113
7
                      false);
1114
7
  Result = Context.getObjCObjectPointerType(Result);
1115
1116
7
  TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1117
7
  TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1118
1119
7
  auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1120
7
  ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1121
1122
7
  auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1123
7
                        .castAs<ObjCObjectTypeLoc>();
1124
7
  ObjCObjectTL.setHasBaseTypeAsWritten(false);
1125
7
  ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1126
1127
  // No type arguments.
1128
7
  ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1129
7
  ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1130
1131
  // Fill in protocol qualifiers.
1132
7
  ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
1133
7
  ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
1134
14
  for (unsigned i = 0, n = protocols.size(); i != n; 
++i7
)
1135
7
    ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
1136
1137
  // We're done. Return the completed type to the parser.
1138
7
  return CreateParsedType(Result, ResultTInfo);
1139
7
}
1140
1141
TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers(
1142
             Scope *S,
1143
             SourceLocation Loc,
1144
             ParsedType BaseType,
1145
             SourceLocation TypeArgsLAngleLoc,
1146
             ArrayRef<ParsedType> TypeArgs,
1147
             SourceLocation TypeArgsRAngleLoc,
1148
             SourceLocation ProtocolLAngleLoc,
1149
             ArrayRef<Decl *> Protocols,
1150
             ArrayRef<SourceLocation> ProtocolLocs,
1151
149k
             SourceLocation ProtocolRAngleLoc) {
1152
149k
  TypeSourceInfo *BaseTypeInfo = nullptr;
1153
149k
  QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
1154
149k
  if (T.isNull())
1155
0
    return true;
1156
1157
  // Handle missing type-source info.
1158
149k
  if (!BaseTypeInfo)
1159
149k
    BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
1160
1161
  // Extract type arguments.
1162
149k
  SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
1163
306k
  for (unsigned i = 0, n = TypeArgs.size(); i != n; 
++i157k
) {
1164
157k
    TypeSourceInfo *TypeArgInfo = nullptr;
1165
157k
    QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
1166
157k
    if (TypeArg.isNull()) {
1167
0
      ActualTypeArgInfos.clear();
1168
0
      break;
1169
0
    }
1170
1171
157k
    assert(TypeArgInfo && "No type source info?");
1172
0
    ActualTypeArgInfos.push_back(TypeArgInfo);
1173
157k
  }
1174
1175
  // Build the object type.
1176
149k
  QualType Result = BuildObjCObjectType(
1177
149k
      T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1178
149k
      TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1179
149k
      ProtocolLAngleLoc,
1180
149k
      llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(),
1181
149k
                         Protocols.size()),
1182
149k
      ProtocolLocs, ProtocolRAngleLoc,
1183
149k
      /*FailOnError=*/false);
1184
1185
149k
  if (Result == T)
1186
57
    return BaseType;
1187
1188
  // Create source information for this type.
1189
149k
  TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1190
149k
  TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1191
1192
  // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
1193
  // object pointer type. Fill in source information for it.
1194
149k
  if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
1195
    // The '*' is implicit.
1196
15.4k
    ObjCObjectPointerTL.setStarLoc(SourceLocation());
1197
15.4k
    ResultTL = ObjCObjectPointerTL.getPointeeLoc();
1198
15.4k
  }
1199
1200
149k
  if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) {
1201
    // Protocol qualifier information.
1202
1.72k
    if (OTPTL.getNumProtocols() > 0) {
1203
1.72k
      assert(OTPTL.getNumProtocols() == Protocols.size());
1204
0
      OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1205
1.72k
      OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1206
3.45k
      for (unsigned i = 0, n = Protocols.size(); i != n; 
++i1.72k
)
1207
1.72k
        OTPTL.setProtocolLoc(i, ProtocolLocs[i]);
1208
1.72k
    }
1209
1210
    // We're done. Return the completed type to the parser.
1211
0
    return CreateParsedType(Result, ResultTInfo);
1212
1.72k
  }
1213
1214
147k
  auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
1215
1216
  // Type argument information.
1217
147k
  if (ObjCObjectTL.getNumTypeArgs() > 0) {
1218
127k
    assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
1219
0
    ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
1220
127k
    ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
1221
284k
    for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; 
++i157k
)
1222
157k
      ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
1223
127k
  } else {
1224
20.4k
    ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1225
20.4k
    ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1226
20.4k
  }
1227
1228
  // Protocol qualifier information.
1229
147k
  if (ObjCObjectTL.getNumProtocols() > 0) {
1230
20.4k
    assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
1231
0
    ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1232
20.4k
    ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1233
41.8k
    for (unsigned i = 0, n = Protocols.size(); i != n; 
++i21.3k
)
1234
21.3k
      ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
1235
127k
  } else {
1236
127k
    ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1237
127k
    ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1238
127k
  }
1239
1240
  // Base type.
1241
0
  ObjCObjectTL.setHasBaseTypeAsWritten(true);
1242
147k
  if (ObjCObjectTL.getType() == T)
1243
0
    ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1244
147k
  else
1245
147k
    ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1246
1247
  // We're done. Return the completed type to the parser.
1248
147k
  return CreateParsedType(Result, ResultTInfo);
1249
149k
}
1250
1251
static OpenCLAccessAttr::Spelling
1252
6.92k
getImageAccess(const ParsedAttributesView &Attrs) {
1253
6.92k
  for (const ParsedAttr &AL : Attrs)
1254
6.84k
    if (AL.getKind() == ParsedAttr::AT_OpenCLAccess)
1255
6.84k
      return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling());
1256
81
  return OpenCLAccessAttr::Keyword_read_only;
1257
6.92k
}
1258
1259
/// Convert the specified declspec to the appropriate type
1260
/// object.
1261
/// \param state Specifies the declarator containing the declaration specifier
1262
/// to be converted, along with other associated processing state.
1263
/// \returns The type described by the declaration specifiers.  This function
1264
/// never returns null.
1265
137M
static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
1266
  // FIXME: Should move the logic from DeclSpec::Finish to here for validity
1267
  // checking.
1268
1269
137M
  Sema &S = state.getSema();
1270
137M
  Declarator &declarator = state.getDeclarator();
1271
137M
  DeclSpec &DS = declarator.getMutableDeclSpec();
1272
137M
  SourceLocation DeclLoc = declarator.getIdentifierLoc();
1273
137M
  if (DeclLoc.isInvalid())
1274
716k
    DeclLoc = DS.getBeginLoc();
1275
1276
137M
  ASTContext &Context = S.Context;
1277
1278
137M
  QualType Result;
1279
137M
  switch (DS.getTypeSpecType()) {
1280
3.86M
  case DeclSpec::TST_void:
1281
3.86M
    Result = Context.VoidTy;
1282
3.86M
    break;
1283
1.15M
  case DeclSpec::TST_char:
1284
1.15M
    if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
1285
795k
      Result = Context.CharTy;
1286
362k
    else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed)
1287
115k
      Result = Context.SignedCharTy;
1288
247k
    else {
1289
247k
      assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&
1290
247k
             "Unknown TSS value");
1291
0
      Result = Context.UnsignedCharTy;
1292
247k
    }
1293
0
    break;
1294
130k
  case DeclSpec::TST_wchar:
1295
130k
    if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
1296
130k
      Result = Context.WCharTy;
1297
6
    else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed) {
1298
3
      S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
1299
3
        << DS.getSpecifierName(DS.getTypeSpecType(),
1300
3
                               Context.getPrintingPolicy());
1301
3
      Result = Context.getSignedWCharType();
1302
3
    } else {
1303
3
      assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&
1304
3
             "Unknown TSS value");
1305
0
      S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
1306
3
        << DS.getSpecifierName(DS.getTypeSpecType(),
1307
3
                               Context.getPrintingPolicy());
1308
3
      Result = Context.getUnsignedWCharType();
1309
3
    }
1310
0
    break;
1311
58
  case DeclSpec::TST_char8:
1312
58
    assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1313
58
           "Unknown TSS value");
1314
0
    Result = Context.Char8Ty;
1315
58
    break;
1316
9.01k
  case DeclSpec::TST_char16:
1317
9.01k
    assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1318
9.01k
           "Unknown TSS value");
1319
0
    Result = Context.Char16Ty;
1320
9.01k
    break;
1321
9.01k
  case DeclSpec::TST_char32:
1322
9.01k
    assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1323
9.01k
           "Unknown TSS value");
1324
0
    Result = Context.Char32Ty;
1325
9.01k
    break;
1326
9.06k
  case DeclSpec::TST_unspecified:
1327
    // If this is a missing declspec in a block literal return context, then it
1328
    // is inferred from the return statements inside the block.
1329
    // The declspec is always missing in a lambda expr context; it is either
1330
    // specified with a trailing return type or inferred.
1331
9.06k
    if (S.getLangOpts().CPlusPlus14 &&
1332
9.06k
        
declarator.getContext() == DeclaratorContext::LambdaExpr4.95k
) {
1333
      // In C++1y, a lambda's implicit return type is 'auto'.
1334
3.99k
      Result = Context.getAutoDeductType();
1335
3.99k
      break;
1336
5.07k
    } else if (declarator.getContext() == DeclaratorContext::LambdaExpr ||
1337
5.07k
               checkOmittedBlockReturnType(S, declarator,
1338
4.72k
                                           Context.DependentTy)) {
1339
4.72k
      Result = Context.DependentTy;
1340
4.72k
      break;
1341
4.72k
    }
1342
1343
    // Unspecified typespec defaults to int in C90.  However, the C90 grammar
1344
    // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
1345
    // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
1346
    // Note that the one exception to this is function definitions, which are
1347
    // allowed to be completely missing a declspec.  This is handled in the
1348
    // parser already though by it pretending to have seen an 'int' in this
1349
    // case.
1350
350
    if (S.getLangOpts().ImplicitInt) {
1351
      // In C89 mode, we only warn if there is a completely missing declspec
1352
      // when one is not allowed.
1353
4
      if (DS.isEmpty()) {
1354
3
        S.Diag(DeclLoc, diag::ext_missing_declspec)
1355
3
            << DS.getSourceRange()
1356
3
            << FixItHint::CreateInsertion(DS.getBeginLoc(), "int");
1357
3
      }
1358
346
    } else if (!DS.hasTypeSpecifier()) {
1359
      // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
1360
      // "At least one type specifier shall be given in the declaration
1361
      // specifiers in each declaration, and in the specifier-qualifier list in
1362
      // each struct declaration and type name."
1363
346
      if (S.getLangOpts().CPlusPlus && 
!DS.isTypeSpecPipe()214
) {
1364
213
        S.Diag(DeclLoc, diag::err_missing_type_specifier)
1365
213
          << DS.getSourceRange();
1366
1367
        // When this occurs in C++ code, often something is very broken with the
1368
        // value being declared, poison it as invalid so we don't get chains of
1369
        // errors.
1370
213
        declarator.setInvalidType(true);
1371
213
      } else 
if (133
(133
S.getLangOpts().OpenCLVersion >= 200133
||
1372
133
                  
S.getLangOpts().OpenCLCPlusPlus131
) &&
1373
133
                 
DS.isTypeSpecPipe()3
) {
1374
2
        S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1375
2
          << DS.getSourceRange();
1376
2
        declarator.setInvalidType(true);
1377
131
      } else {
1378
131
        S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1379
131
          << DS.getSourceRange();
1380
131
      }
1381
346
    }
1382
1383
350
    LLVM_FALLTHROUGH;
1384
3.41M
  case DeclSpec::TST_int: {
1385
3.41M
    if (DS.getTypeSpecSign() != TypeSpecifierSign::Unsigned) {
1386
2.52M
      switch (DS.getTypeSpecWidth()) {
1387
1.98M
      case TypeSpecifierWidth::Unspecified:
1388
1.98M
        Result = Context.IntTy;
1389
1.98M
        break;
1390
203k
      case TypeSpecifierWidth::Short:
1391
203k
        Result = Context.ShortTy;
1392
203k
        break;
1393
199k
      case TypeSpecifierWidth::Long:
1394
199k
        Result = Context.LongTy;
1395
199k
        break;
1396
135k
      case TypeSpecifierWidth::LongLong:
1397
135k
        Result = Context.LongLongTy;
1398
1399
        // 'long long' is a C99 or C++11 feature.
1400
135k
        if (!S.getLangOpts().C99) {
1401
66.0k
          if (S.getLangOpts().CPlusPlus)
1402
66.0k
            S.Diag(DS.getTypeSpecWidthLoc(),
1403
66.0k
                   S.getLangOpts().CPlusPlus11 ?
1404
64.5k
                   diag::warn_cxx98_compat_longlong : 
diag::ext_cxx11_longlong1.48k
);
1405
39
          else
1406
39
            S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1407
66.0k
        }
1408
135k
        break;
1409
2.52M
      }
1410
2.52M
    } else {
1411
890k
      switch (DS.getTypeSpecWidth()) {
1412
395k
      case TypeSpecifierWidth::Unspecified:
1413
395k
        Result = Context.UnsignedIntTy;
1414
395k
        break;
1415
220k
      case TypeSpecifierWidth::Short:
1416
220k
        Result = Context.UnsignedShortTy;
1417
220k
        break;
1418
134k
      case TypeSpecifierWidth::Long:
1419
134k
        Result = Context.UnsignedLongTy;
1420
134k
        break;
1421
140k
      case TypeSpecifierWidth::LongLong:
1422
140k
        Result = Context.UnsignedLongLongTy;
1423
1424
        // 'long long' is a C99 or C++11 feature.
1425
140k
        if (!S.getLangOpts().C99) {
1426
59.9k
          if (S.getLangOpts().CPlusPlus)
1427
59.9k
            S.Diag(DS.getTypeSpecWidthLoc(),
1428
59.9k
                   S.getLangOpts().CPlusPlus11 ?
1429
58.6k
                   diag::warn_cxx98_compat_longlong : 
diag::ext_cxx11_longlong1.30k
);
1430
11
          else
1431
11
            S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1432
59.9k
        }
1433
140k
        break;
1434
890k
      }
1435
890k
    }
1436
3.41M
    break;
1437
3.41M
  }
1438
3.41M
  case DeclSpec::TST_extint: {
1439
923
    if (!S.Context.getTargetInfo().hasExtIntType())
1440
0
      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1441
0
        << "_ExtInt";
1442
923
    Result =
1443
923
        S.BuildExtIntType(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned,
1444
923
                          DS.getRepAsExpr(), DS.getBeginLoc());
1445
923
    if (Result.isNull()) {
1446
9
      Result = Context.IntTy;
1447
9
      declarator.setInvalidType(true);
1448
9
    }
1449
923
    break;
1450
3.41M
  }
1451
1.02k
  case DeclSpec::TST_accum: {
1452
1.02k
    switch (DS.getTypeSpecWidth()) {
1453
518
    case TypeSpecifierWidth::Short:
1454
518
      Result = Context.ShortAccumTy;
1455
518
      break;
1456
315
    case TypeSpecifierWidth::Unspecified:
1457
315
      Result = Context.AccumTy;
1458
315
      break;
1459
191
    case TypeSpecifierWidth::Long:
1460
191
      Result = Context.LongAccumTy;
1461
191
      break;
1462
0
    case TypeSpecifierWidth::LongLong:
1463
0
      llvm_unreachable("Unable to specify long long as _Accum width");
1464
1.02k
    }
1465
1466
1.02k
    if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1467
327
      Result = Context.getCorrespondingUnsignedType(Result);
1468
1469
1.02k
    if (DS.isTypeSpecSat())
1470
369
      Result = Context.getCorrespondingSaturatedType(Result);
1471
1472
1.02k
    break;
1473
1.02k
  }
1474
545
  case DeclSpec::TST_fract: {
1475
545
    switch (DS.getTypeSpecWidth()) {
1476
168
    case TypeSpecifierWidth::Short:
1477
168
      Result = Context.ShortFractTy;
1478
168
      break;
1479
214
    case TypeSpecifierWidth::Unspecified:
1480
214
      Result = Context.FractTy;
1481
214
      break;
1482
163
    case TypeSpecifierWidth::Long:
1483
163
      Result = Context.LongFractTy;
1484
163
      break;
1485
0
    case TypeSpecifierWidth::LongLong:
1486
0
      llvm_unreachable("Unable to specify long long as _Fract width");
1487
545
    }
1488
1489
545
    if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1490
208
      Result = Context.getCorrespondingUnsignedType(Result);
1491
1492
545
    if (DS.isTypeSpecSat())
1493
176
      Result = Context.getCorrespondingSaturatedType(Result);
1494
1495
545
    break;
1496
545
  }
1497
7.92k
  case DeclSpec::TST_int128:
1498
7.92k
    if (!S.Context.getTargetInfo().hasInt128Type() &&
1499
7.92k
        
!S.getLangOpts().SYCLIsDevice33
&&
1500
7.92k
        
!(15
S.getLangOpts().OpenMP15
&&
S.getLangOpts().OpenMPIsDevice0
))
1501
15
      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1502
15
        << "__int128";
1503
7.92k
    if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1504
4.34k
      Result = Context.UnsignedInt128Ty;
1505
3.58k
    else
1506
3.58k
      Result = Context.Int128Ty;
1507
7.92k
    break;
1508
374
  case DeclSpec::TST_float16:
1509
    // CUDA host and device may have different _Float16 support, therefore
1510
    // do not diagnose _Float16 usage to avoid false alarm.
1511
    // ToDo: more precise diagnostics for CUDA.
1512
374
    if (!S.Context.getTargetInfo().hasFloat16Type() && 
!S.getLangOpts().CUDA5
&&
1513
374
        
!(3
S.getLangOpts().OpenMP3
&&
S.getLangOpts().OpenMPIsDevice0
))
1514
3
      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1515
3
        << "_Float16";
1516
374
    Result = Context.Float16Ty;
1517
374
    break;
1518
18.5k
  case DeclSpec::TST_half:    Result = Context.HalfTy; break;
1519
704
  case DeclSpec::TST_BFloat16:
1520
704
    if (!S.Context.getTargetInfo().hasBFloat16Type())
1521
4
      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1522
4
        << "__bf16";
1523
704
    Result = Context.BFloat16Ty;
1524
704
    break;
1525
330k
  case DeclSpec::TST_float:   Result = Context.FloatTy; break;
1526
369k
  case DeclSpec::TST_double:
1527
369k
    if (S.getLangOpts().OpenCL) {
1528
11.0k
      if (!S.getOpenCLOptions().isSupported("cl_khr_fp64", S.getLangOpts()))
1529
33
        S.Diag(DS.getTypeSpecTypeLoc(),
1530
33
               diag::err_opencl_double_requires_extension)
1531
33
            << (S.getLangOpts().OpenCLVersion >= 300);
1532
11.0k
      else if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp64", S.getLangOpts()))
1533
24
        S.Diag(DS.getTypeSpecTypeLoc(), diag::ext_opencl_double_without_pragma);
1534
11.0k
    }
1535
369k
    if (DS.getTypeSpecWidth() == TypeSpecifierWidth::Long)
1536
70.4k
      Result = Context.LongDoubleTy;
1537
298k
    else
1538
298k
      Result = Context.DoubleTy;
1539
369k
    break;
1540
427
  case DeclSpec::TST_float128:
1541
427
    if (!S.Context.getTargetInfo().hasFloat128Type() &&
1542
427
        
!S.getLangOpts().SYCLIsDevice38
&&
1543
427
        
!(23
S.getLangOpts().OpenMP23
&&
S.getLangOpts().OpenMPIsDevice11
))
1544
12
      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1545
12
        << "__float128";
1546
427
    Result = Context.Float128Ty;
1547
427
    break;
1548
688k
  case DeclSpec::TST_bool:
1549
688k
    Result = Context.BoolTy; // _Bool or bool
1550
688k
    break;
1551
5
  case DeclSpec::TST_decimal32:    // _Decimal32
1552
5
  case DeclSpec::TST_decimal64:    // _Decimal64
1553
7
  case DeclSpec::TST_decimal128:   // _Decimal128
1554
7
    S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1555
7
    Result = Context.IntTy;
1556
7
    declarator.setInvalidType(true);
1557
7
    break;
1558
14.1k
  case DeclSpec::TST_class:
1559
497k
  case DeclSpec::TST_enum:
1560
526k
  case DeclSpec::TST_union:
1561
1.39M
  case DeclSpec::TST_struct:
1562
1.39M
  case DeclSpec::TST_interface: {
1563
1.39M
    TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl());
1564
1.39M
    if (!D) {
1565
      // This can happen in C++ with ambiguous lookups.
1566
6.61k
      Result = Context.IntTy;
1567
6.61k
      declarator.setInvalidType(true);
1568
6.61k
      break;
1569
6.61k
    }
1570
1571
    // If the type is deprecated or unavailable, diagnose it.
1572
1.39M
    S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
1573
1574
1.39M
    assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&
1575
1.39M
           DS.getTypeSpecComplex() == 0 &&
1576
1.39M
           DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1577
1.39M
           "No qualifiers on tag names!");
1578
1579
    // TypeQuals handled by caller.
1580
0
    Result = Context.getTypeDeclType(D);
1581
1582
    // In both C and C++, make an ElaboratedType.
1583
1.39M
    ElaboratedTypeKeyword Keyword
1584
1.39M
      = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
1585
1.39M
    Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result,
1586
1.39M
                                 DS.isTypeSpecOwned() ? 
D443k
:
nullptr949k
);
1587
1.39M
    break;
1588
1.39M
  }
1589
126M
  case DeclSpec::TST_typename: {
1590
126M
    assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&
1591
126M
           DS.getTypeSpecComplex() == 0 &&
1592
126M
           DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1593
126M
           "Can't handle qualifiers on typedef names yet!");
1594
0
    Result = S.GetTypeFromParser(DS.getRepAsType());
1595
126M
    if (Result.isNull()) {
1596
0
      declarator.setInvalidType(true);
1597
0
    }
1598
1599
    // TypeQuals handled by caller.
1600
126M
    break;
1601
1.39M
  }
1602
98
  case DeclSpec::TST_typeofType:
1603
    // FIXME: Preserve type source info.
1604
98
    Result = S.GetTypeFromParser(DS.getRepAsType());
1605
98
    assert(!Result.isNull() && "Didn't get a type for typeof?");
1606
98
    if (!Result->isDependentType())
1607
96
      if (const TagType *TT = Result->getAs<TagType>())
1608
8
        S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1609
    // TypeQuals handled by caller.
1610
98
    Result = Context.getTypeOfType(Result);
1611
98
    break;
1612
2.94k
  case DeclSpec::TST_typeofExpr: {
1613
2.94k
    Expr *E = DS.getRepAsExpr();
1614
2.94k
    assert(E && "Didn't get an expression for typeof?");
1615
    // TypeQuals handled by caller.
1616
0
    Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
1617
2.94k
    if (Result.isNull()) {
1618
0
      Result = Context.IntTy;
1619
0
      declarator.setInvalidType(true);
1620
0
    }
1621
2.94k
    break;
1622
1.39M
  }
1623
39.8k
  case DeclSpec::TST_decltype: {
1624
39.8k
    Expr *E = DS.getRepAsExpr();
1625
39.8k
    assert(E && "Didn't get an expression for decltype?");
1626
    // TypeQuals handled by caller.
1627
0
    Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
1628
39.8k
    if (Result.isNull()) {
1629
0
      Result = Context.IntTy;
1630
0
      declarator.setInvalidType(true);
1631
0
    }
1632
39.8k
    break;
1633
1.39M
  }
1634
505
  case DeclSpec::TST_underlyingType:
1635
505
    Result = S.GetTypeFromParser(DS.getRepAsType());
1636
505
    assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
1637
0
    Result = S.BuildUnaryTransformType(Result,
1638
505
                                       UnaryTransformType::EnumUnderlyingType,
1639
505
                                       DS.getTypeSpecTypeLoc());
1640
505
    if (Result.isNull()) {
1641
4
      Result = Context.IntTy;
1642
4
      declarator.setInvalidType(true);
1643
4
    }
1644
505
    break;
1645
1646
32.5k
  case DeclSpec::TST_auto:
1647
32.9k
  case DeclSpec::TST_decltype_auto: {
1648
32.9k
    auto AutoKW = DS.getTypeSpecType() == DeclSpec::TST_decltype_auto
1649
32.9k
                      ? 
AutoTypeKeyword::DecltypeAuto443
1650
32.9k
                      : 
AutoTypeKeyword::Auto32.5k
;
1651
1652
32.9k
    ConceptDecl *TypeConstraintConcept = nullptr;
1653
32.9k
    llvm::SmallVector<TemplateArgument, 8> TemplateArgs;
1654
32.9k
    if (DS.isConstrainedAuto()) {
1655
130
      if (TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId()) {
1656
128
        TypeConstraintConcept =
1657
128
            cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl());
1658
128
        TemplateArgumentListInfo TemplateArgsInfo;
1659
128
        TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc);
1660
128
        TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc);
1661
128
        ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1662
128
                                           TemplateId->NumArgs);
1663
128
        S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
1664
128
        for (const auto &ArgLoc : TemplateArgsInfo.arguments())
1665
65
          TemplateArgs.push_back(ArgLoc.getArgument());
1666
128
      } else {
1667
2
        declarator.setInvalidType(true);
1668
2
      }
1669
130
    }
1670
32.9k
    Result = S.Context.getAutoType(QualType(), AutoKW,
1671
32.9k
                                   /*IsDependent*/ false, /*IsPack=*/false,
1672
32.9k
                                   TypeConstraintConcept, TemplateArgs);
1673
32.9k
    break;
1674
32.5k
  }
1675
1676
36
  case DeclSpec::TST_auto_type:
1677
36
    Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1678
36
    break;
1679
1680
62
  case DeclSpec::TST_unknown_anytype:
1681
62
    Result = Context.UnknownAnyTy;
1682
62
    break;
1683
1684
2.40k
  case DeclSpec::TST_atomic:
1685
2.40k
    Result = S.GetTypeFromParser(DS.getRepAsType());
1686
2.40k
    assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1687
0
    Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1688
2.40k
    if (Result.isNull()) {
1689
11
      Result = Context.IntTy;
1690
11
      declarator.setInvalidType(true);
1691
11
    }
1692
2.40k
    break;
1693
1694
0
#define GENERIC_IMAGE_TYPE(ImgType, Id)                                        \
1695
6.92k
  case DeclSpec::TST_##ImgType##_t:                                            \
1696
6.92k
    switch (getImageAccess(DS.getAttributes())) {                              \
1697
1.80k
    case OpenCLAccessAttr::Keyword_write_only:                                 \
1698
1.80k
      Result = Context.Id##WOTy;                                               \
1699
1.80k
      break;                                                                   \
1700
2.00k
    case OpenCLAccessAttr::Keyword_read_write:                                 \
1701
2.00k
      Result = Context.Id##RWTy;                                               \
1702
2.00k
      break;                                                                   \
1703
3.12k
    case OpenCLAccessAttr::Keyword_read_only:                                  \
1704
3.12k
      Result = Context.Id##ROTy;                                               \
1705
3.12k
      break;                                                                   \
1706
0
    case OpenCLAccessAttr::SpellingNotCalculated:                              \
1707
0
      llvm_unreachable("Spelling not yet calculated");                         \
1708
6.92k
    }                                                                          \
1709
6.92k
    break;
1710
2.40k
#include "clang/Basic/OpenCLImageTypes.def"
1711
1712
1.88k
  case DeclSpec::TST_error:
1713
1.88k
    Result = Context.IntTy;
1714
1.88k
    declarator.setInvalidType(true);
1715
1.88k
    break;
1716
137M
  }
1717
1718
  // FIXME: we want resulting declarations to be marked invalid, but claiming
1719
  // the type is invalid is too strong - e.g. it causes ActOnTypeName to return
1720
  // a null type.
1721
137M
  if (Result->containsErrors())
1722
181
    declarator.setInvalidType();
1723
1724
137M
  if (S.getLangOpts().OpenCL && 
Result->isOCLImage3dWOType()586k
&&
1725
137M
      
!S.getOpenCLOptions().isSupported("cl_khr_3d_image_writes", S.getLangOpts())255
) {
1726
1
        S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1727
1
        << 0 << Result << "cl_khr_3d_image_writes";
1728
1
        declarator.setInvalidType();
1729
1
  }
1730
1731
137M
  bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1732
137M
                          
DS.getTypeSpecType() == DeclSpec::TST_fract137M
;
1733
1734
  // Only fixed point types can be saturated
1735
137M
  if (DS.isTypeSpecSat() && 
!IsFixedPointType556
)
1736
11
    S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
1737
11
        << DS.getSpecifierName(DS.getTypeSpecType(),
1738
11
                               Context.getPrintingPolicy());
1739
1740
  // Handle complex types.
1741
137M
  if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1742
7.99k
    if (S.getLangOpts().Freestanding)
1743
45
      S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1744
7.99k
    Result = Context.getComplexType(Result);
1745
137M
  } else if (DS.isTypeAltiVecVector()) {
1746
660k
    unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1747
660k
    assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1748
0
    VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1749
660k
    if (DS.isTypeAltiVecPixel())
1750
11.1k
      VecKind = VectorType::AltiVecPixel;
1751
649k
    else if (DS.isTypeAltiVecBool())
1752
113k
      VecKind = VectorType::AltiVecBool;
1753
660k
    Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1754
660k
  }
1755
1756
  // FIXME: Imaginary.
1757
137M
  if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1758
4
    S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1759
1760
  // Before we process any type attributes, synthesize a block literal
1761
  // function declarator if necessary.
1762
137M
  if (declarator.getContext() == DeclaratorContext::BlockLiteral)
1763
2.96k
    maybeSynthesizeBlockSignature(state, Result);
1764
1765
  // Apply any type attributes from the decl spec.  This may cause the
1766
  // list of type attributes to be temporarily saved while the type
1767
  // attributes are pushed around.
1768
  // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1769
137M
  if (!DS.isTypeSpecPipe())
1770
137M
    processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes());
1771
1772
  // Apply const/volatile/restrict qualifiers to T.
1773
137M
  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1774
    // Warn about CV qualifiers on function types.
1775
    // C99 6.7.3p8:
1776
    //   If the specification of a function type includes any type qualifiers,
1777
    //   the behavior is undefined.
1778
    // C++11 [dcl.fct]p7:
1779
    //   The effect of a cv-qualifier-seq in a function declarator is not the
1780
    //   same as adding cv-qualification on top of the function type. In the
1781
    //   latter case, the cv-qualifiers are ignored.
1782
5.45M
    if (Result->isFunctionType()) {
1783
19
      diagnoseAndRemoveTypeQualifiers(
1784
19
          S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1785
19
          S.getLangOpts().CPlusPlus
1786
19
              ? 
diag::warn_typecheck_function_qualifiers_ignored15
1787
19
              : 
diag::warn_typecheck_function_qualifiers_unspecified4
);
1788
      // No diagnostic for 'restrict' or '_Atomic' applied to a
1789
      // function type; we'll diagnose those later, in BuildQualifiedType.
1790
19
    }
1791
1792
    // C++11 [dcl.ref]p1:
1793
    //   Cv-qualified references are ill-formed except when the
1794
    //   cv-qualifiers are introduced through the use of a typedef-name
1795
    //   or decltype-specifier, in which case the cv-qualifiers are ignored.
1796
    //
1797
    // There don't appear to be any other contexts in which a cv-qualified
1798
    // reference type could be formed, so the 'ill-formed' clause here appears
1799
    // to never happen.
1800
5.45M
    if (TypeQuals && 
Result->isReferenceType()5.45M
) {
1801
52
      diagnoseAndRemoveTypeQualifiers(
1802
52
          S, DS, TypeQuals, Result,
1803
52
          DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1804
52
          diag::warn_typecheck_reference_qualifiers);
1805
52
    }
1806
1807
    // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1808
    // than once in the same specifier-list or qualifier-list, either directly
1809
    // or via one or more typedefs."
1810
5.45M
    if (!S.getLangOpts().C99 && 
!S.getLangOpts().CPlusPlus2.42M
1811
5.45M
        && 
TypeQuals & Result.getCVRQualifiers()540
) {
1812
8
      if (TypeQuals & DeclSpec::TQ_const && 
Result.isConstQualified()6
) {
1813
6
        S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1814
6
          << "const";
1815
6
      }
1816
1817
8
      if (TypeQuals & DeclSpec::TQ_volatile && 
Result.isVolatileQualified()2
) {
1818
2
        S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1819
2
          << "volatile";
1820
2
      }
1821
1822
      // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1823
      // produce a warning in this case.
1824
8
    }
1825
1826
5.45M
    QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1827
1828
    // If adding qualifiers fails, just use the unqualified type.
1829
5.45M
    if (Qualified.isNull())
1830
16
      declarator.setInvalidType(true);
1831
5.45M
    else
1832
5.45M
      Result = Qualified;
1833
5.45M
  }
1834
1835
137M
  assert(!Result.isNull() && "This function should not return a null type");
1836
0
  return Result;
1837
137M
}
1838
1839
138
static std::string getPrintableNameForEntity(DeclarationName Entity) {
1840
138
  if (Entity)
1841
106
    return Entity.getAsString();
1842
1843
32
  return "type name";
1844
138
}
1845
1846
QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1847
6.09M
                                  Qualifiers Qs, const DeclSpec *DS) {
1848
6.09M
  if (T.isNull())
1849
0
    return QualType();
1850
1851
  // Ignore any attempt to form a cv-qualified reference.
1852
6.09M
  if (T->isReferenceType()) {
1853
64
    Qs.removeConst();
1854
64
    Qs.removeVolatile();
1855
64
  }
1856
1857
  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1858
  // object or incomplete types shall not be restrict-qualified."
1859
6.09M
  if (Qs.hasRestrict()) {
1860
78.3k
    unsigned DiagID = 0;
1861
78.3k
    QualType ProblemTy;
1862
1863
78.3k
    if (T->isAnyPointerType() || 
T->isReferenceType()37
||
1864
78.3k
        
T->isMemberPointerType()26
) {
1865
78.3k
      QualType EltTy;
1866
78.3k
      if (T->isObjCObjectPointerType())
1867
6
        EltTy = T;
1868
78.3k
      else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1869
2
        EltTy = PTy->getPointeeType();
1870
78.3k
      else
1871
78.3k
        EltTy = T->getPointeeType();
1872
1873
      // If we have a pointer or reference, the pointee must have an object
1874
      // incomplete type.
1875
78.3k
      if (!EltTy->isIncompleteOrObjectType()) {
1876
2
        DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1877
2
        ProblemTy = EltTy;
1878
2
      }
1879
78.3k
    } else 
if (24
!T->isDependentType()24
) {
1880
19
      DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1881
19
      ProblemTy = T;
1882
19
    }
1883
1884
78.3k
    if (DiagID) {
1885
21
      Diag(DS ? 
DS->getRestrictSpecLoc()14
:
Loc7
, DiagID) << ProblemTy;
1886
21
      Qs.removeRestrict();
1887
21
    }
1888
78.3k
  }
1889
1890
6.09M
  return Context.getQualifiedType(T, Qs);
1891
6.09M
}
1892
1893
QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1894
5.61M
                                  unsigned CVRAU, const DeclSpec *DS) {
1895
5.61M
  if (T.isNull())
1896
5
    return QualType();
1897
1898
  // Ignore any attempt to form a cv-qualified reference.
1899
5.61M
  if (T->isReferenceType())
1900
59
    CVRAU &=
1901
59
        ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic);
1902
1903
  // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1904
  // TQ_unaligned;
1905
5.61M
  unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1906
1907
  // C11 6.7.3/5:
1908
  //   If the same qualifier appears more than once in the same
1909
  //   specifier-qualifier-list, either directly or via one or more typedefs,
1910
  //   the behavior is the same as if it appeared only once.
1911
  //
1912
  // It's not specified what happens when the _Atomic qualifier is applied to
1913
  // a type specified with the _Atomic specifier, but we assume that this
1914
  // should be treated as if the _Atomic qualifier appeared multiple times.
1915
5.61M
  if (CVRAU & DeclSpec::TQ_atomic && 
!T->isAtomicType()122
) {
1916
    // C11 6.7.3/5:
1917
    //   If other qualifiers appear along with the _Atomic qualifier in a
1918
    //   specifier-qualifier-list, the resulting type is the so-qualified
1919
    //   atomic type.
1920
    //
1921
    // Don't need to worry about array types here, since _Atomic can't be
1922
    // applied to such types.
1923
120
    SplitQualType Split = T.getSplitUnqualifiedType();
1924
120
    T = BuildAtomicType(QualType(Split.Ty, 0),
1925
120
                        DS ? 
DS->getAtomicSpecLoc()106
:
Loc14
);
1926
120
    if (T.isNull())
1927
16
      return T;
1928
104
    Split.Quals.addCVRQualifiers(CVR);
1929
104
    return BuildQualifiedType(T, Loc, Split.Quals);
1930
120
  }
1931
1932
5.61M
  Qualifiers Q = Qualifiers::fromCVRMask(CVR);
1933
5.61M
  Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned);
1934
5.61M
  return BuildQualifiedType(T, Loc, Q, DS);
1935
5.61M
}
1936
1937
/// Build a paren type including \p T.
1938
311k
QualType Sema::BuildParenType(QualType T) {
1939
311k
  return Context.getParenType(T);
1940
311k
}
1941
1942
/// Given that we're building a pointer or reference to the given
1943
static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1944
                                           SourceLocation loc,
1945
35.8k
                                           bool isReference) {
1946
  // Bail out if retention is unrequired or already specified.
1947
35.8k
  if (!type->isObjCLifetimeType() ||
1948
35.8k
      
type.getObjCLifetime() != Qualifiers::OCL_None1.37k
)
1949
35.8k
    return type;
1950
1951
24
  Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1952
1953
  // If the object type is const-qualified, we can safely use
1954
  // __unsafe_unretained.  This is safe (because there are no read
1955
  // barriers), and it'll be safe to coerce anything but __weak* to
1956
  // the resulting type.
1957
24
  if (type.isConstQualified()) {
1958
2
    implicitLifetime = Qualifiers::OCL_ExplicitNone;
1959
1960
  // Otherwise, check whether the static type does not require
1961
  // retaining.  This currently only triggers for Class (possibly
1962
  // protocol-qualifed, and arrays thereof).
1963
22
  } else if (type->isObjCARCImplicitlyUnretainedType()) {
1964
3
    implicitLifetime = Qualifiers::OCL_ExplicitNone;
1965
1966
  // If we are in an unevaluated context, like sizeof, skip adding a
1967
  // qualification.
1968
19
  } else if (S.isUnevaluatedContext()) {
1969
4
    return type;
1970
1971
  // If that failed, give an error and recover using __strong.  __strong
1972
  // is the option most likely to prevent spurious second-order diagnostics,
1973
  // like when binding a reference to a field.
1974
15
  } else {
1975
    // These types can show up in private ivars in system headers, so
1976
    // we need this to not be an error in those cases.  Instead we
1977
    // want to delay.
1978
15
    if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1979
14
      S.DelayedDiagnostics.add(
1980
14
          sema::DelayedDiagnostic::makeForbiddenType(loc,
1981
14
              diag::err_arc_indirect_no_ownership, type, isReference));
1982
14
    } else {
1983
1
      S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1984
1
    }
1985
15
    implicitLifetime = Qualifiers::OCL_Strong;
1986
15
  }
1987
20
  assert(implicitLifetime && "didn't infer any lifetime!");
1988
1989
0
  Qualifiers qs;
1990
20
  qs.addObjCLifetime(implicitLifetime);
1991
20
  return S.Context.getQualifiedType(type, qs);
1992
24
}
1993
1994
80
static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1995
80
  std::string Quals = FnTy->getMethodQuals().getAsString();
1996
1997
80
  switch (FnTy->getRefQualifier()) {
1998
43
  case RQ_None:
1999
43
    break;
2000
2001
17
  case RQ_LValue:
2002
17
    if (!Quals.empty())
2003
0
      Quals += ' ';
2004
17
    Quals += '&';
2005
17
    break;
2006
2007
20
  case RQ_RValue:
2008
20
    if (!Quals.empty())
2009
2
      Quals += ' ';
2010
20
    Quals += "&&";
2011
20
    break;
2012
80
  }
2013
2014
80
  return Quals;
2015
80
}
2016
2017
namespace {
2018
/// Kinds of declarator that cannot contain a qualified function type.
2019
///
2020
/// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
2021
///     a function type with a cv-qualifier or a ref-qualifier can only appear
2022
///     at the topmost level of a type.
2023
///
2024
/// Parens and member pointers are permitted. We don't diagnose array and
2025
/// function declarators, because they don't allow function types at all.
2026
///
2027
/// The values of this enum are used in diagnostics.
2028
enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
2029
} // end anonymous namespace
2030
2031
/// Check whether the type T is a qualified function type, and if it is,
2032
/// diagnose that it cannot be contained within the given kind of declarator.
2033
static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
2034
10.1M
                                   QualifiedFunctionKind QFK) {
2035
  // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
2036
10.1M
  const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
2037
10.1M
  if (!FPT ||
2038
10.1M
      
(267k
FPT->getMethodQuals().empty()267k
&&
FPT->getRefQualifier() == RQ_None267k
))
2039
10.1M
    return false;
2040
2041
24
  S.Diag(Loc, diag::err_compound_qualified_function_type)
2042
24
    << QFK << isa<FunctionType>(T.IgnoreParens()) << T
2043
24
    << getFunctionQualifiersAsString(FPT);
2044
24
  return true;
2045
10.1M
}
2046
2047
5.30k
bool Sema::CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc) {
2048
5.30k
  const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
2049
5.30k
  if (!FPT ||
2050
5.30k
      
(6
FPT->getMethodQuals().empty()6
&&
FPT->getRefQualifier() == RQ_None3
))
2051
5.29k
    return false;
2052
2053
6
  Diag(Loc, diag::err_qualified_function_typeid)
2054
6
      << T << getFunctionQualifiersAsString(FPT);
2055
6
  return true;
2056
5.30k
}
2057
2058
// Helper to deduce addr space of a pointee type in OpenCL mode.
2059
34.2k
static QualType deduceOpenCLPointeeAddrSpace(Sema &S, QualType PointeeType) {
2060
34.2k
  if (!PointeeType->isUndeducedAutoType() && 
!PointeeType->isDependentType()34.2k
&&
2061
34.2k
      
!PointeeType->isSamplerT()34.1k
&&
2062
34.2k
      
!PointeeType.hasAddressSpace()34.1k
)
2063
6.70k
    PointeeType = S.getASTContext().getAddrSpaceQualType(
2064
6.70k
        PointeeType, S.getLangOpts().OpenCLGenericAddressSpace
2065
6.70k
                         ? 
LangAS::opencl_generic5.97k
2066
6.70k
                         : 
LangAS::opencl_private731
);
2067
34.2k
  return PointeeType;
2068
34.2k
}
2069
2070
/// Build a pointer type.
2071
///
2072
/// \param T The type to which we'll be building a pointer.
2073
///
2074
/// \param Loc The location of the entity whose type involves this
2075
/// pointer type or, if there is no such entity, the location of the
2076
/// type that will have pointer type.
2077
///
2078
/// \param Entity The name of the entity that involves the pointer
2079
/// type, if known.
2080
///
2081
/// \returns A suitable pointer type, if there are no
2082
/// errors. Otherwise, returns a NULL type.
2083
QualType Sema::BuildPointerType(QualType T,
2084
7.99M
                                SourceLocation Loc, DeclarationName Entity) {
2085
7.99M
  if (T->isReferenceType()) {
2086
    // C++ 8.3.2p4: There shall be no ... pointers to references ...
2087
59
    Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
2088
59
      << getPrintableNameForEntity(Entity) << T;
2089
59
    return QualType();
2090
59
  }
2091
2092
7.99M
  if (T->isFunctionType() && 
getLangOpts().OpenCL203k
&&
2093
7.99M
      !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2094
11
                                            getLangOpts())) {
2095
7
    Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
2096
7
    return QualType();
2097
7
  }
2098
2099
7.99M
  if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
2100
12
    return QualType();
2101
2102
7.99M
  assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
2103
2104
  // In ARC, it is forbidden to build pointers to unqualified pointers.
2105
7.99M
  if (getLangOpts().ObjCAutoRefCount)
2106
34.3k
    T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
2107
2108
7.99M
  if (getLangOpts().OpenCL)
2109
34.0k
    T = deduceOpenCLPointeeAddrSpace(*this, T);
2110
2111
  // Build the pointer type.
2112
7.99M
  return Context.getPointerType(T);
2113
7.99M
}
2114
2115
/// Build a reference type.
2116
///
2117
/// \param T The type to which we'll be building a reference.
2118
///
2119
/// \param Loc The location of the entity whose type involves this
2120
/// reference type or, if there is no such entity, the location of the
2121
/// type that will have reference type.
2122
///
2123
/// \param Entity The name of the entity that involves the reference
2124
/// type, if known.
2125
///
2126
/// \returns A suitable reference type, if there are no
2127
/// errors. Otherwise, returns a NULL type.
2128
QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
2129
                                  SourceLocation Loc,
2130
2.06M
                                  DeclarationName Entity) {
2131
2.06M
  assert(Context.getCanonicalType(T) != Context.OverloadTy &&
2132
2.06M
         "Unresolved overloaded function type");
2133
2134
  // C++0x [dcl.ref]p6:
2135
  //   If a typedef (7.1.3), a type template-parameter (14.3.1), or a
2136
  //   decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
2137
  //   type T, an attempt to create the type "lvalue reference to cv TR" creates
2138
  //   the type "lvalue reference to T", while an attempt to create the type
2139
  //   "rvalue reference to cv TR" creates the type TR.
2140
2.06M
  bool LValueRef = SpelledAsLValue || 
T->getAs<LValueReferenceType>()439k
;
2141
2142
  // C++ [dcl.ref]p4: There shall be no references to references.
2143
  //
2144
  // According to C++ DR 106, references to references are only
2145
  // diagnosed when they are written directly (e.g., "int & &"),
2146
  // but not when they happen via a typedef:
2147
  //
2148
  //   typedef int& intref;
2149
  //   typedef intref& intref2;
2150
  //
2151
  // Parser::ParseDeclaratorInternal diagnoses the case where
2152
  // references are written directly; here, we handle the
2153
  // collapsing of references-to-references as described in C++0x.
2154
  // DR 106 and 540 introduce reference-collapsing into C++98/03.
2155
2156
  // C++ [dcl.ref]p1:
2157
  //   A declarator that specifies the type "reference to cv void"
2158
  //   is ill-formed.
2159
2.06M
  if (T->isVoidType()) {
2160
429
    Diag(Loc, diag::err_reference_to_void);
2161
429
    return QualType();
2162
429
  }
2163
2164
2.06M
  if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
2165
12
    return QualType();
2166
2167
2.06M
  if (T->isFunctionType() && 
getLangOpts().OpenCL3.99k
&&
2168
2.06M
      !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2169
10
                                            getLangOpts())) {
2170
5
    Diag(Loc, diag::err_opencl_function_pointer) << /*reference*/ 1;
2171
5
    return QualType();
2172
5
  }
2173
2174
  // In ARC, it is forbidden to build references to unqualified pointers.
2175
2.06M
  if (getLangOpts().ObjCAutoRefCount)
2176
1.54k
    T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
2177
2178
2.06M
  if (getLangOpts().OpenCL)
2179
108
    T = deduceOpenCLPointeeAddrSpace(*this, T);
2180
2181
  // Handle restrict on references.
2182
2.06M
  if (LValueRef)
2183
1.65M
    return Context.getLValueReferenceType(T, SpelledAsLValue);
2184
402k
  return Context.getRValueReferenceType(T);
2185
2.06M
}
2186
2187
/// Build a Read-only Pipe type.
2188
///
2189
/// \param T The type to which we'll be building a Pipe.
2190
///
2191
/// \param Loc We do not use it for now.
2192
///
2193
/// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2194
/// NULL type.
2195
131
QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) {
2196
131
  return Context.getReadPipeType(T);
2197
131
}
2198
2199
/// Build a Write-only Pipe type.
2200
///
2201
/// \param T The type to which we'll be building a Pipe.
2202
///
2203
/// \param Loc We do not use it for now.
2204
///
2205
/// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2206
/// NULL type.
2207
0
QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) {
2208
0
  return Context.getWritePipeType(T);
2209
0
}
2210
2211
/// Build a extended int type.
2212
///
2213
/// \param IsUnsigned Boolean representing the signedness of the type.
2214
///
2215
/// \param BitWidth Size of this int type in bits, or an expression representing
2216
/// that.
2217
///
2218
/// \param Loc Location of the keyword.
2219
QualType Sema::BuildExtIntType(bool IsUnsigned, Expr *BitWidth,
2220
932
                               SourceLocation Loc) {
2221
932
  if (BitWidth->isInstantiationDependent())
2222
4
    return Context.getDependentExtIntType(IsUnsigned, BitWidth);
2223
2224
928
  llvm::APSInt Bits(32);
2225
928
  ExprResult ICE =
2226
928
      VerifyIntegerConstantExpression(BitWidth, &Bits, /*FIXME*/ AllowFold);
2227
2228
928
  if (ICE.isInvalid())
2229
2
    return QualType();
2230
2231
926
  int64_t NumBits = Bits.getSExtValue();
2232
926
  if (!IsUnsigned && 
NumBits < 2853
) {
2233
7
    Diag(Loc, diag::err_ext_int_bad_size) << 0;
2234
7
    return QualType();
2235
7
  }
2236
2237
919
  if (IsUnsigned && 
NumBits < 173
) {
2238
3
    Diag(Loc, diag::err_ext_int_bad_size) << 1;
2239
3
    return QualType();
2240
3
  }
2241
2242
916
  if (NumBits > llvm::IntegerType::MAX_INT_BITS) {
2243
2
    Diag(Loc, diag::err_ext_int_max_size) << IsUnsigned
2244
2
                                          << llvm::IntegerType::MAX_INT_BITS;
2245
2
    return QualType();
2246
2
  }
2247
2248
914
  return Context.getExtIntType(IsUnsigned, NumBits);
2249
916
}
2250
2251
/// Check whether the specified array bound can be evaluated using the relevant
2252
/// language rules. If so, returns the possibly-converted expression and sets
2253
/// SizeVal to the size. If not, but the expression might be a VLA bound,
2254
/// returns ExprResult(). Otherwise, produces a diagnostic and returns
2255
/// ExprError().
2256
static ExprResult checkArraySize(Sema &S, Expr *&ArraySize,
2257
                                 llvm::APSInt &SizeVal, unsigned VLADiag,
2258
255k
                                 bool VLAIsError) {
2259
255k
  if (S.getLangOpts().CPlusPlus14 &&
2260
255k
      
(25.0k
VLAIsError25.0k
||
2261
25.0k
       
!ArraySize->getType()->isIntegralOrUnscopedEnumerationType()24.5k
)) {
2262
    // C++14 [dcl.array]p1:
2263
    //   The constant-expression shall be a converted constant expression of
2264
    //   type std::size_t.
2265
    //
2266
    // Don't apply this rule if we might be forming a VLA: in that case, we
2267
    // allow non-constant expressions and constant-folding. We only need to use
2268
    // the converted constant expression rules (to properly convert the source)
2269
    // when the source expression is of class type.
2270
479
    return S.CheckConvertedConstantExpression(
2271
479
        ArraySize, S.Context.getSizeType(), SizeVal, Sema::CCEK_ArrayBound);
2272
479
  }
2273
2274
  // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2275
  // (like gnu99, but not c99) accept any evaluatable value as an extension.
2276
254k
  class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2277
254k
  public:
2278
254k
    unsigned VLADiag;
2279
254k
    bool VLAIsError;
2280
254k
    bool IsVLA = false;
2281
2282
254k
    VLADiagnoser(unsigned VLADiag, bool VLAIsError)
2283
254k
        : VLADiag(VLADiag), VLAIsError(VLAIsError) {}
2284
2285
254k
    Sema::SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
2286
254k
                                                   QualType T) override {
2287
1
      return S.Diag(Loc, diag::err_array_size_non_int) << T;
2288
1
    }
2289
2290
254k
    Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
2291
254k
                                               SourceLocation Loc) override {
2292
3.48k
      IsVLA = !VLAIsError;
2293
3.48k
      return S.Diag(Loc, VLADiag);
2294
3.48k
    }
2295
2296
254k
    Sema::SemaDiagnosticBuilder diagnoseFold(Sema &S,
2297
254k
                                             SourceLocation Loc) override {
2298
0
      return S.Diag(Loc, diag::ext_vla_folded_to_constant);
2299
0
    }
2300
254k
  } Diagnoser(VLADiag, VLAIsError);
2301
2302
254k
  ExprResult R =
2303
254k
      S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser);
2304
254k
  if (Diagnoser.IsVLA)
2305
3.47k
    return ExprResult();
2306
251k
  return R;
2307
254k
}
2308
2309
/// Build an array type.
2310
///
2311
/// \param T The type of each element in the array.
2312
///
2313
/// \param ASM C99 array size modifier (e.g., '*', 'static').
2314
///
2315
/// \param ArraySize Expression describing the size of the array.
2316
///
2317
/// \param Brackets The range from the opening '[' to the closing ']'.
2318
///
2319
/// \param Entity The name of the entity that involves the array
2320
/// type, if known.
2321
///
2322
/// \returns A suitable array type, if there are no errors. Otherwise,
2323
/// returns a NULL type.
2324
QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2325
                              Expr *ArraySize, unsigned Quals,
2326
321k
                              SourceRange Brackets, DeclarationName Entity) {
2327
2328
321k
  SourceLocation Loc = Brackets.getBegin();
2329
321k
  if (getLangOpts().CPlusPlus) {
2330
    // C++ [dcl.array]p1:
2331
    //   T is called the array element type; this type shall not be a reference
2332
    //   type, the (possibly cv-qualified) type void, a function type or an
2333
    //   abstract class type.
2334
    //
2335
    // C++ [dcl.array]p3:
2336
    //   When several "array of" specifications are adjacent, [...] only the
2337
    //   first of the constant expressions that specify the bounds of the arrays
2338
    //   may be omitted.
2339
    //
2340
    // Note: function types are handled in the common path with C.
2341
151k
    if (T->isReferenceType()) {
2342
9
      Diag(Loc, diag::err_illegal_decl_array_of_references)
2343
9
      << getPrintableNameForEntity(Entity) << T;
2344
9
      return QualType();
2345
9
    }
2346
2347
151k
    if (T->isVoidType() || 
T->isIncompleteArrayType()151k
) {
2348
2
      Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 0 << T;
2349
2
      return QualType();
2350
2
    }
2351
2352
151k
    if (RequireNonAbstractType(Brackets.getBegin(), T,
2353
151k
                               diag::err_array_of_abstract_type))
2354
20
      return QualType();
2355
2356
    // Mentioning a member pointer type for an array type causes us to lock in
2357
    // an inheritance model, even if it's inside an unused typedef.
2358
151k
    if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2359
877
      if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2360
0
        if (!MPTy->getClass()->isDependentType())
2361
0
          (void)isCompleteType(Loc, T);
2362
2363
170k
  } else {
2364
    // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2365
    // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2366
170k
    if (RequireCompleteSizedType(Loc, T,
2367
170k
                                 diag::err_array_incomplete_or_sizeless_type))
2368
21
      return QualType();
2369
170k
  }
2370
2371
321k
  if (T->isSizelessType()) {
2372
19
    Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 1 << T;
2373
19
    return QualType();
2374
19
  }
2375
2376
321k
  if (T->isFunctionType()) {
2377
8
    Diag(Loc, diag::err_illegal_decl_array_of_functions)
2378
8
      << getPrintableNameForEntity(Entity) << T;
2379
8
    return QualType();
2380
8
  }
2381
2382
321k
  if (const RecordType *EltTy = T->getAs<RecordType>()) {
2383
    // If the element type is a struct or union that contains a variadic
2384
    // array, accept it as a GNU extension: C99 6.7.2.1p2.
2385
30.1k
    if (EltTy->getDecl()->hasFlexibleArrayMember())
2386
6
      Diag(Loc, diag::ext_flexible_array_in_array) << T;
2387
291k
  } else if (T->isObjCObjectType()) {
2388
1
    Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2389
1
    return QualType();
2390
1
  }
2391
2392
  // Do placeholder conversions on the array size expression.
2393
321k
  if (ArraySize && 
ArraySize->hasPlaceholderType()271k
) {
2394
2
    ExprResult Result = CheckPlaceholderExpr(ArraySize);
2395
2
    if (Result.isInvalid()) 
return QualType()0
;
2396
2
    ArraySize = Result.get();
2397
2
  }
2398
2399
  // Do lvalue-to-rvalue conversions on the array size expression.
2400
321k
  if (ArraySize && 
!ArraySize->isPRValue()271k
) {
2401
6.75k
    ExprResult Result = DefaultLvalueConversion(ArraySize);
2402
6.75k
    if (Result.isInvalid())
2403
0
      return QualType();
2404
2405
6.75k
    ArraySize = Result.get();
2406
6.75k
  }
2407
2408
  // C99 6.7.5.2p1: The size expression shall have integer type.
2409
  // C++11 allows contextual conversions to such types.
2410
321k
  if (!getLangOpts().CPlusPlus11 &&
2411
321k
      
ArraySize173k
&&
!ArraySize->isTypeDependent()148k
&&
2412
321k
      
!ArraySize->getType()->isIntegralOrUnscopedEnumerationType()148k
) {
2413
4
    Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2414
4
        << ArraySize->getType() << ArraySize->getSourceRange();
2415
4
    return QualType();
2416
4
  }
2417
2418
  // VLAs always produce at least a -Wvla diagnostic, sometimes an error.
2419
321k
  unsigned VLADiag;
2420
321k
  bool VLAIsError;
2421
321k
  if (getLangOpts().OpenCL) {
2422
    // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2423
604
    VLADiag = diag::err_opencl_vla;
2424
604
    VLAIsError = true;
2425
320k
  } else if (getLangOpts().C99) {
2426
169k
    VLADiag = diag::warn_vla_used;
2427
169k
    VLAIsError = false;
2428
169k
  } else 
if (151k
isSFINAEContext()151k
) {
2429
886
    VLADiag = diag::err_vla_in_sfinae;
2430
886
    VLAIsError = true;
2431
150k
  } else {
2432
150k
    VLADiag = diag::ext_vla;
2433
150k
    VLAIsError = false;
2434
150k
  }
2435
2436
321k
  llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2437
321k
  if (!ArraySize) {
2438
49.9k
    if (ASM == ArrayType::Star) {
2439
28
      Diag(Loc, VLADiag);
2440
28
      if (VLAIsError)
2441
0
        return QualType();
2442
2443
28
      T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2444
49.9k
    } else {
2445
49.9k
      T = Context.getIncompleteArrayType(T, ASM, Quals);
2446
49.9k
    }
2447
271k
  } else if (ArraySize->isTypeDependent() || 
ArraySize->isValueDependent()270k
) {
2448
16.0k
    T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2449
255k
  } else {
2450
255k
    ExprResult R =
2451
255k
        checkArraySize(*this, ArraySize, ConstVal, VLADiag, VLAIsError);
2452
255k
    if (R.isInvalid())
2453
11
      return QualType();
2454
2455
255k
    if (!R.isUsable()) {
2456
      // C99: an array with a non-ICE size is a VLA. We accept any expression
2457
      // that we can fold to a non-zero positive value as a non-VLA as an
2458
      // extension.
2459
3.47k
      T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2460
251k
    } else if (!T->isDependentType() && 
!T->isIncompleteType()247k
&&
2461
251k
               
!T->isConstantSizeType()247k
) {
2462
      // C99: an array with an element type that has a non-constant-size is a
2463
      // VLA.
2464
      // FIXME: Add a note to explain why this isn't a VLA.
2465
1.12k
      Diag(Loc, VLADiag);
2466
1.12k
      if (VLAIsError)
2467
0
        return QualType();
2468
1.12k
      T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2469
250k
    } else {
2470
      // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2471
      // have a value greater than zero.
2472
      // In C++, this follows from narrowing conversions being disallowed.
2473
250k
      if (ConstVal.isSigned() && 
ConstVal.isNegative()242k
) {
2474
59
        if (Entity)
2475
51
          Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size)
2476
51
              << getPrintableNameForEntity(Entity)
2477
51
              << ArraySize->getSourceRange();
2478
8
        else
2479
8
          Diag(ArraySize->getBeginLoc(),
2480
8
               diag::err_typecheck_negative_array_size)
2481
8
              << ArraySize->getSourceRange();
2482
59
        return QualType();
2483
59
      }
2484
250k
      if (ConstVal == 0) {
2485
        // GCC accepts zero sized static arrays. We allow them when
2486
        // we're not in a SFINAE context.
2487
2.98k
        Diag(ArraySize->getBeginLoc(),
2488
2.98k
             isSFINAEContext() ? 
diag::err_typecheck_zero_array_size3
2489
2.98k
                               : 
diag::ext_typecheck_zero_array_size2.98k
)
2490
2.98k
            << ArraySize->getSourceRange();
2491
2.98k
      }
2492
2493
      // Is the array too large?
2494
250k
      unsigned ActiveSizeBits =
2495
250k
          (!T->isDependentType() && 
!T->isVariablyModifiedType()246k
&&
2496
250k
           
!T->isIncompleteType()246k
&&
!T->isUndeducedType()246k
)
2497
250k
              ? 
ConstantArrayType::getNumAddressingBits(Context, T, ConstVal)246k
2498
250k
              : 
ConstVal.getActiveBits()4.52k
;
2499
250k
      if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2500
8
        Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2501
8
            << toString(ConstVal, 10) << ArraySize->getSourceRange();
2502
8
        return QualType();
2503
8
      }
2504
2505
250k
      T = Context.getConstantArrayType(T, ConstVal, ArraySize, ASM, Quals);
2506
250k
    }
2507
255k
  }
2508
2509
321k
  if (T->isVariableArrayType() && 
!Context.getTargetInfo().isVLASupported()4.63k
) {
2510
    // CUDA device code and some other targets don't support VLAs.
2511
30
    targetDiag(Loc, (getLangOpts().CUDA && 
getLangOpts().CUDAIsDevice6
)
2512
30
                        ? 
diag::err_cuda_vla6
2513
30
                        : 
diag::err_vla_unsupported24
)
2514
30
        << ((getLangOpts().CUDA && 
getLangOpts().CUDAIsDevice6
)
2515
30
                ? 
CurrentCUDATarget()6
2516
30
                : 
CFT_InvalidTarget24
);
2517
30
  }
2518
2519
  // If this is not C99, diagnose array size modifiers on non-VLAs.
2520
321k
  if (!getLangOpts().C99 && 
!T->isVariableArrayType()151k
&&
2521
321k
      
(147k
ASM != ArrayType::Normal147k
||
Quals != 0147k
)) {
2522
5
    Diag(Loc, getLangOpts().CPlusPlus ? 
diag::err_c99_array_usage_cxx3
2523
5
                                      : 
diag::ext_c99_array_usage2
)
2524
5
        << ASM;
2525
5
  }
2526
2527
  // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2528
  // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2529
  // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2530
321k
  if (getLangOpts().OpenCL) {
2531
599
    const QualType ArrType = Context.getBaseElementType(T);
2532
599
    if (ArrType->isBlockPointerType() || 
ArrType->isPipeType()598
||
2533
599
        
ArrType->isSamplerT()598
||
ArrType->isImageType()592
) {
2534
11
      Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2535
11
      return QualType();
2536
11
    }
2537
599
  }
2538
2539
321k
  return T;
2540
321k
}
2541
2542
QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr,
2543
26.3k
                               SourceLocation AttrLoc) {
2544
  // The base type must be integer (not Boolean or enumeration) or float, and
2545
  // can't already be a vector.
2546
26.3k
  if ((!CurType->isDependentType() &&
2547
26.3k
       
(26.2k
!CurType->isBuiltinType()26.2k
||
CurType->isBooleanType()26.2k
||
2548
26.2k
        
(26.2k
!CurType->isIntegerType()26.2k
&&
!CurType->isRealFloatingType()9.12k
))) ||
2549
26.3k
      
CurType->isArrayType()26.3k
) {
2550
38
    Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType;
2551
38
    return QualType();
2552
38
  }
2553
2554
26.3k
  if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
2555
30
    return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2556
30
                                               VectorType::GenericVector);
2557
2558
26.2k
  Optional<llvm::APSInt> VecSize = SizeExpr->getIntegerConstantExpr(Context);
2559
26.2k
  if (!VecSize) {
2560
0
    Diag(AttrLoc, diag::err_attribute_argument_type)
2561
0
        << "vector_size" << AANT_ArgumentIntegerConstant
2562
0
        << SizeExpr->getSourceRange();
2563
0
    return QualType();
2564
0
  }
2565
2566
26.2k
  if (CurType->isDependentType())
2567
15
    return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2568
15
                                               VectorType::GenericVector);
2569
2570
  // vecSize is specified in bytes - convert to bits.
2571
26.2k
  if (!VecSize->isIntN(61)) {
2572
    // Bit size will overflow uint64.
2573
10
    Diag(AttrLoc, diag::err_attribute_size_too_large)
2574
10
        << SizeExpr->getSourceRange() << "vector";
2575
10
    return QualType();
2576
10
  }
2577
26.2k
  uint64_t VectorSizeBits = VecSize->getZExtValue() * 8;
2578
26.2k
  unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
2579
2580
26.2k
  if (VectorSizeBits == 0) {
2581
10
    Diag(AttrLoc, diag::err_attribute_zero_size)
2582
10
        << SizeExpr->getSourceRange() << "vector";
2583
10
    return QualType();
2584
10
  }
2585
2586
26.2k
  if (VectorSizeBits % TypeSize) {
2587
10
    Diag(AttrLoc, diag::err_attribute_invalid_size)
2588
10
        << SizeExpr->getSourceRange();
2589
10
    return QualType();
2590
10
  }
2591
2592
26.2k
  if (VectorSizeBits / TypeSize > std::numeric_limits<uint32_t>::max()) {
2593
20
    Diag(AttrLoc, diag::err_attribute_size_too_large)
2594
20
        << SizeExpr->getSourceRange() << "vector";
2595
20
    return QualType();
2596
20
  }
2597
2598
26.2k
  return Context.getVectorType(CurType, VectorSizeBits / TypeSize,
2599
26.2k
                               VectorType::GenericVector);
2600
26.2k
}
2601
2602
/// Build an ext-vector type.
2603
///
2604
/// Run the required checks for the extended vector type.
2605
QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
2606
3.80k
                                  SourceLocation AttrLoc) {
2607
  // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2608
  // in conjunction with complex types (pointers, arrays, functions, etc.).
2609
  //
2610
  // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2611
  // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2612
  // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2613
  // of bool aren't allowed.
2614
3.80k
  if ((!T->isDependentType() && 
!T->isIntegerType()3.79k
&&
2615
3.80k
       
!T->isRealFloatingType()1.16k
) ||
2616
3.80k
      
T->isBooleanType()3.79k
) {
2617
12
    Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2618
12
    return QualType();
2619
12
  }
2620
2621
3.79k
  if (!ArraySize->isTypeDependent() && 
!ArraySize->isValueDependent()3.79k
) {
2622
3.77k
    Optional<llvm::APSInt> vecSize = ArraySize->getIntegerConstantExpr(Context);
2623
3.77k
    if (!vecSize) {
2624
0
      Diag(AttrLoc, diag::err_attribute_argument_type)
2625
0
        << "ext_vector_type" << AANT_ArgumentIntegerConstant
2626
0
        << ArraySize->getSourceRange();
2627
0
      return QualType();
2628
0
    }
2629
2630
3.77k
    if (!vecSize->isIntN(32)) {
2631
5
      Diag(AttrLoc, diag::err_attribute_size_too_large)
2632
5
          << ArraySize->getSourceRange() << "vector";
2633
5
      return QualType();
2634
5
    }
2635
    // Unlike gcc's vector_size attribute, the size is specified as the
2636
    // number of elements, not the number of bytes.
2637
3.76k
    unsigned vectorSize = static_cast<unsigned>(vecSize->getZExtValue());
2638
2639
3.76k
    if (vectorSize == 0) {
2640
8
      Diag(AttrLoc, diag::err_attribute_zero_size)
2641
8
          << ArraySize->getSourceRange() << "vector";
2642
8
      return QualType();
2643
8
    }
2644
2645
3.75k
    return Context.getExtVectorType(T, vectorSize);
2646
3.76k
  }
2647
2648
27
  return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2649
3.79k
}
2650
2651
QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols,
2652
365
                               SourceLocation AttrLoc) {
2653
365
  assert(Context.getLangOpts().MatrixTypes &&
2654
365
         "Should never build a matrix type when it is disabled");
2655
2656
  // Check element type, if it is not dependent.
2657
365
  if (!ElementTy->isDependentType() &&
2658
365
      
!MatrixType::isValidElementType(ElementTy)329
) {
2659
6
    Diag(AttrLoc, diag::err_attribute_invalid_matrix_type) << ElementTy;
2660
6
    return QualType();
2661
6
  }
2662
2663
359
  if (NumRows->isTypeDependent() || 
NumCols->isTypeDependent()358
||
2664
359
      
NumRows->isValueDependent()358
||
NumCols->isValueDependent()312
)
2665
71
    return Context.getDependentSizedMatrixType(ElementTy, NumRows, NumCols,
2666
71
                                               AttrLoc);
2667
2668
288
  Optional<llvm::APSInt> ValueRows = NumRows->getIntegerConstantExpr(Context);
2669
288
  Optional<llvm::APSInt> ValueColumns =
2670
288
      NumCols->getIntegerConstantExpr(Context);
2671
2672
288
  auto const RowRange = NumRows->getSourceRange();
2673
288
  auto const ColRange = NumCols->getSourceRange();
2674
2675
  // Both are row and column expressions are invalid.
2676
288
  if (!ValueRows && 
!ValueColumns2
) {
2677
1
    Diag(AttrLoc, diag::err_attribute_argument_type)
2678
1
        << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange
2679
1
        << ColRange;
2680
1
    return QualType();
2681
1
  }
2682
2683
  // Only the row expression is invalid.
2684
287
  if (!ValueRows) {
2685
1
    Diag(AttrLoc, diag::err_attribute_argument_type)
2686
1
        << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange;
2687
1
    return QualType();
2688
1
  }
2689
2690
  // Only the column expression is invalid.
2691
286
  if (!ValueColumns) {
2692
1
    Diag(AttrLoc, diag::err_attribute_argument_type)
2693
1
        << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange;
2694
1
    return QualType();
2695
1
  }
2696
2697
  // Check the matrix dimensions.
2698
285
  unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue());
2699
285
  unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue());
2700
285
  if (MatrixRows == 0 && 
MatrixColumns == 03
) {
2701
0
    Diag(AttrLoc, diag::err_attribute_zero_size)
2702
0
        << "matrix" << RowRange << ColRange;
2703
0
    return QualType();
2704
0
  }
2705
285
  if (MatrixRows == 0) {
2706
3
    Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << RowRange;
2707
3
    return QualType();
2708
3
  }
2709
282
  if (MatrixColumns == 0) {
2710
1
    Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << ColRange;
2711
1
    return QualType();
2712
1
  }
2713
281
  if (!ConstantMatrixType::isDimensionValid(MatrixRows)) {
2714
3
    Diag(AttrLoc, diag::err_attribute_size_too_large)
2715
3
        << RowRange << "matrix row";
2716
3
    return QualType();
2717
3
  }
2718
278
  if (!ConstantMatrixType::isDimensionValid(MatrixColumns)) {
2719
1
    Diag(AttrLoc, diag::err_attribute_size_too_large)
2720
1
        << ColRange << "matrix column";
2721
1
    return QualType();
2722
1
  }
2723
277
  return Context.getConstantMatrixType(ElementTy, MatrixRows, MatrixColumns);
2724
278
}
2725
2726
1.59M
bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2727
1.59M
  if (T->isArrayType() || 
T->isFunctionType()1.59M
) {
2728
18
    Diag(Loc, diag::err_func_returning_array_function)
2729
18
      << T->isFunctionType() << T;
2730
18
    return true;
2731
18
  }
2732
2733
  // Functions cannot return half FP.
2734
1.59M
  if (T->isHalfType() && 
!getLangOpts().HalfArgsAndReturns0
) {
2735
0
    Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2736
0
      FixItHint::CreateInsertion(Loc, "*");
2737
0
    return true;
2738
0
  }
2739
2740
  // Methods cannot return interface types. All ObjC objects are
2741
  // passed by reference.
2742
1.59M
  if (T->isObjCObjectType()) {
2743
3
    Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2744
3
        << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2745
3
    return true;
2746
3
  }
2747
2748
1.59M
  if (T.hasNonTrivialToPrimitiveDestructCUnion() ||
2749
1.59M
      
T.hasNonTrivialToPrimitiveCopyCUnion()1.59M
)
2750
2
    checkNonTrivialCUnion(T, Loc, NTCUC_FunctionReturn,
2751
2
                          NTCUK_Destruct|NTCUK_Copy);
2752
2753
  // C++2a [dcl.fct]p12:
2754
  //   A volatile-qualified return type is deprecated
2755
1.59M
  if (T.isVolatileQualified() && 
getLangOpts().CPlusPlus2029
)
2756
3
    Diag(Loc, diag::warn_deprecated_volatile_return) << T;
2757
2758
1.59M
  return false;
2759
1.59M
}
2760
2761
/// Check the extended parameter information.  Most of the necessary
2762
/// checking should occur when applying the parameter attribute; the
2763
/// only other checks required are positional restrictions.
2764
static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes,
2765
                    const FunctionProtoType::ExtProtoInfo &EPI,
2766
8.43k
                    llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2767
8.43k
  assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2768
2769
0
  bool hasCheckedSwiftCall = false;
2770
8.43k
  auto checkForSwiftCC = [&](unsigned paramIndex) {
2771
    // Only do this once.
2772
166
    if (hasCheckedSwiftCall) 
return55
;
2773
111
    hasCheckedSwiftCall = true;
2774
111
    if (EPI.ExtInfo.getCC() == CC_Swift) 
return102
;
2775
9
    S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2776
9
      << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI());
2777
9
  };
2778
2779
8.43k
  for (size_t paramIndex = 0, numParams = paramTypes.size();
2780
34.0k
          paramIndex != numParams; 
++paramIndex25.6k
) {
2781
25.6k
    switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2782
    // Nothing interesting to check for orindary-ABI parameters.
2783
25.4k
    case ParameterABI::Ordinary:
2784
25.4k
      continue;
2785
2786
    // swift_indirect_result parameters must be a prefix of the function
2787
    // arguments.
2788
74
    case ParameterABI::SwiftIndirectResult:
2789
74
      checkForSwiftCC(paramIndex);
2790
74
      if (paramIndex != 0 &&
2791
74
          EPI.ExtParameterInfos[paramIndex - 1].getABI()
2792
30
            != ParameterABI::SwiftIndirectResult) {
2793
3
        S.Diag(getParamLoc(paramIndex),
2794
3
               diag::err_swift_indirect_result_not_first);
2795
3
      }
2796
74
      continue;
2797
2798
58
    case ParameterABI::SwiftContext:
2799
58
      checkForSwiftCC(paramIndex);
2800
58
      continue;
2801
2802
11
    case ParameterABI::SwiftAsyncContext:
2803
      // FIXME: might want to require swiftasynccc when it exists
2804
11
      continue;
2805
2806
    // swift_error parameters must be preceded by a swift_context parameter.
2807
34
    case ParameterABI::SwiftErrorResult:
2808
34
      checkForSwiftCC(paramIndex);
2809
34
      if (paramIndex == 0 ||
2810
34
          EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2811
31
              ParameterABI::SwiftContext) {
2812
6
        S.Diag(getParamLoc(paramIndex),
2813
6
               diag::err_swift_error_result_not_after_swift_context);
2814
6
      }
2815
34
      continue;
2816
25.6k
    }
2817
25.6k
    
llvm_unreachable0
("bad ABI kind");
2818
25.6k
  }
2819
8.43k
}
2820
2821
QualType Sema::BuildFunctionType(QualType T,
2822
                                 MutableArrayRef<QualType> ParamTypes,
2823
                                 SourceLocation Loc, DeclarationName Entity,
2824
950k
                                 const FunctionProtoType::ExtProtoInfo &EPI) {
2825
950k
  bool Invalid = false;
2826
2827
950k
  Invalid |= CheckFunctionReturnType(T, Loc);
2828
2829
2.29M
  for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; 
++Idx1.34M
) {
2830
    // FIXME: Loc is too inprecise here, should use proper locations for args.
2831
1.34M
    QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2832
1.34M
    if (ParamType->isVoidType()) {
2833
0
      Diag(Loc, diag::err_param_with_void_type);
2834
0
      Invalid = true;
2835
1.34M
    } else if (ParamType->isHalfType() && 
!getLangOpts().HalfArgsAndReturns0
) {
2836
      // Disallow half FP arguments.
2837
0
      Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2838
0
        FixItHint::CreateInsertion(Loc, "*");
2839
0
      Invalid = true;
2840
0
    }
2841
2842
    // C++2a [dcl.fct]p4:
2843
    //   A parameter with volatile-qualified type is deprecated
2844
1.34M
    if (ParamType.isVolatileQualified() && 
getLangOpts().CPlusPlus206
)
2845
1
      Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType;
2846
2847
1.34M
    ParamTypes[Idx] = ParamType;
2848
1.34M
  }
2849
2850
950k
  if (EPI.ExtParameterInfos) {
2851
86
    checkExtParameterInfos(*this, ParamTypes, EPI,
2852
86
                           [=](unsigned i) 
{ return Loc; }0
);
2853
86
  }
2854
2855
950k
  if (EPI.ExtInfo.getProducesResult()) {
2856
    // This is just a warning, so we can't fail to build if we see it.
2857
18
    checkNSReturnsRetainedReturnType(Loc, T);
2858
18
  }
2859
2860
950k
  if (Invalid)
2861
17
    return QualType();
2862
2863
950k
  return Context.getFunctionType(T, ParamTypes, EPI);
2864
950k
}
2865
2866
/// Build a member pointer type \c T Class::*.
2867
///
2868
/// \param T the type to which the member pointer refers.
2869
/// \param Class the class type into which the member pointer points.
2870
/// \param Loc the location where this type begins
2871
/// \param Entity the name of the entity that will have this member pointer type
2872
///
2873
/// \returns a member pointer type, if successful, or a NULL type if there was
2874
/// an error.
2875
QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
2876
                                      SourceLocation Loc,
2877
32.3k
                                      DeclarationName Entity) {
2878
  // Verify that we're not building a pointer to pointer to function with
2879
  // exception specification.
2880
32.3k
  if (CheckDistantExceptionSpec(T)) {
2881
3
    Diag(Loc, diag::err_distant_exception_spec);
2882
3
    return QualType();
2883
3
  }
2884
2885
  // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2886
  //   with reference type, or "cv void."
2887
32.3k
  if (T->isReferenceType()) {
2888
4
    Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2889
4
      << getPrintableNameForEntity(Entity) << T;
2890
4
    return QualType();
2891
4
  }
2892
2893
32.3k
  if (T->isVoidType()) {
2894
5
    Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2895
5
      << getPrintableNameForEntity(Entity);
2896
5
    return QualType();
2897
5
  }
2898
2899
32.3k
  if (!Class->isDependentType() && 
!Class->isRecordType()3.54k
) {
2900
3
    Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
2901
3
    return QualType();
2902
3
  }
2903
2904
32.3k
  if (T->isFunctionType() && 
getLangOpts().OpenCL27.7k
&&
2905
32.3k
      !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2906
4
                                            getLangOpts())) {
2907
2
    Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
2908
2
    return QualType();
2909
2
  }
2910
2911
  // Adjust the default free function calling convention to the default method
2912
  // calling convention.
2913
32.3k
  bool IsCtorOrDtor =
2914
32.3k
      (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
2915
32.3k
      (Entity.getNameKind() == DeclarationName::CXXDestructorName);
2916
32.3k
  if (T->isFunctionType())
2917
27.7k
    adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
2918
2919
32.3k
  return Context.getMemberPointerType(T, Class.getTypePtr());
2920
32.3k
}
2921
2922
/// Build a block pointer type.
2923
///
2924
/// \param T The type to which we'll be building a block pointer.
2925
///
2926
/// \param Loc The source location, used for diagnostics.
2927
///
2928
/// \param Entity The name of the entity that involves the block pointer
2929
/// type, if known.
2930
///
2931
/// \returns A suitable block pointer type, if there are no
2932
/// errors. Otherwise, returns a NULL type.
2933
QualType Sema::BuildBlockPointerType(QualType T,
2934
                                     SourceLocation Loc,
2935
60.3k
                                     DeclarationName Entity) {
2936
60.3k
  if (!T->isFunctionType()) {
2937
10
    Diag(Loc, diag::err_nonfunction_block_type);
2938
10
    return QualType();
2939
10
  }
2940
2941
60.3k
  if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2942
0
    return QualType();
2943
2944
60.3k
  if (getLangOpts().OpenCL)
2945
79
    T = deduceOpenCLPointeeAddrSpace(*this, T);
2946
2947
60.3k
  return Context.getBlockPointerType(T);
2948
60.3k
}
2949
2950
141M
QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
2951
141M
  QualType QT = Ty.get();
2952
141M
  if (QT.isNull()) {
2953
1.47M
    if (TInfo) 
*TInfo = nullptr236
;
2954
1.47M
    return QualType();
2955
1.47M
  }
2956
2957
139M
  TypeSourceInfo *DI = nullptr;
2958
139M
  if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2959
14.8M
    QT = LIT->getType();
2960
14.8M
    DI = LIT->getTypeSourceInfo();
2961
14.8M
  }
2962
2963
139M
  if (TInfo) 
*TInfo = DI13.8M
;
2964
139M
  return QT;
2965
141M
}
2966
2967
static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2968
                                            Qualifiers::ObjCLifetime ownership,
2969
                                            unsigned chunkIndex);
2970
2971
/// Given that this is the declaration of a parameter under ARC,
2972
/// attempt to infer attributes and such for pointer-to-whatever
2973
/// types.
2974
static void inferARCWriteback(TypeProcessingState &state,
2975
111k
                              QualType &declSpecType) {
2976
111k
  Sema &S = state.getSema();
2977
111k
  Declarator &declarator = state.getDeclarator();
2978
2979
  // TODO: should we care about decl qualifiers?
2980
2981
  // Check whether the declarator has the expected form.  We walk
2982
  // from the inside out in order to make the block logic work.
2983
111k
  unsigned outermostPointerIndex = 0;
2984
111k
  bool isBlockPointer = false;
2985
111k
  unsigned numPointers = 0;
2986
147k
  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; 
++i36.0k
) {
2987
37.2k
    unsigned chunkIndex = i;
2988
37.2k
    DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2989
37.2k
    switch (chunk.Kind) {
2990
139
    case DeclaratorChunk::Paren:
2991
      // Ignore parens.
2992
139
      break;
2993
2994
680
    case DeclaratorChunk::Reference:
2995
35.9k
    case DeclaratorChunk::Pointer:
2996
      // Count the number of pointers.  Treat references
2997
      // interchangeably as pointers; if they're mis-ordered, normal
2998
      // type building will discover that.
2999
35.9k
      outermostPointerIndex = chunkIndex;
3000
35.9k
      numPointers++;
3001
35.9k
      break;
3002
3003
578
    case DeclaratorChunk::BlockPointer:
3004
      // If we have a pointer to block pointer, that's an acceptable
3005
      // indirect reference; anything else is not an application of
3006
      // the rules.
3007
578
      if (numPointers != 1) return;
3008
0
      numPointers++;
3009
0
      outermostPointerIndex = chunkIndex;
3010
0
      isBlockPointer = true;
3011
3012
      // We don't care about pointer structure in return values here.
3013
0
      goto done;
3014
3015
495
    case DeclaratorChunk::Array: // suppress if written (id[])?
3016
634
    case DeclaratorChunk::Function:
3017
634
    case DeclaratorChunk::MemberPointer:
3018
634
    case DeclaratorChunk::Pipe:
3019
634
      return;
3020
37.2k
    }
3021
37.2k
  }
3022
110k
 done:
3023
3024
  // If we have *one* pointer, then we want to throw the qualifier on
3025
  // the declaration-specifiers, which means that it needs to be a
3026
  // retainable object type.
3027
110k
  if (numPointers == 1) {
3028
    // If it's not a retainable object type, the rule doesn't apply.
3029
33.4k
    if (!declSpecType->isObjCRetainableType()) 
return33.2k
;
3030
3031
    // If it already has lifetime, don't do anything.
3032
215
    if (declSpecType.getObjCLifetime()) 
return129
;
3033
3034
    // Otherwise, modify the type in-place.
3035
86
    Qualifiers qs;
3036
3037
86
    if (declSpecType->isObjCARCImplicitlyUnretainedType())
3038
4
      qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
3039
82
    else
3040
82
      qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
3041
86
    declSpecType = S.Context.getQualifiedType(declSpecType, qs);
3042
3043
  // If we have *two* pointers, then we want to throw the qualifier on
3044
  // the outermost pointer.
3045
77.2k
  } else if (numPointers == 2) {
3046
    // If we don't have a block pointer, we need to check whether the
3047
    // declaration-specifiers gave us something that will turn into a
3048
    // retainable object pointer after we slap the first pointer on it.
3049
1.13k
    if (!isBlockPointer && !declSpecType->isObjCObjectType())
3050
500
      return;
3051
3052
    // Look for an explicit lifetime attribute there.
3053
639
    DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
3054
639
    if (chunk.Kind != DeclaratorChunk::Pointer &&
3055
639
        
chunk.Kind != DeclaratorChunk::BlockPointer1
)
3056
1
      return;
3057
638
    for (const ParsedAttr &AL : chunk.getAttrs())
3058
209
      if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
3059
83
        return;
3060
3061
555
    transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
3062
555
                                          outermostPointerIndex);
3063
3064
  // Any other number of pointers/references does not trigger the rule.
3065
76.1k
  } else return;
3066
3067
  // TODO: mark whether we did this inference?
3068
110k
}
3069
3070
void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
3071
                                     SourceLocation FallbackLoc,
3072
                                     SourceLocation ConstQualLoc,
3073
                                     SourceLocation VolatileQualLoc,
3074
                                     SourceLocation RestrictQualLoc,
3075
                                     SourceLocation AtomicQualLoc,
3076
354
                                     SourceLocation UnalignedQualLoc) {
3077
354
  if (!Quals)
3078
16
    return;
3079
3080
338
  struct Qual {
3081
338
    const char *Name;
3082
338
    unsigned Mask;
3083
338
    SourceLocation Loc;
3084
338
  } const QualKinds[5] = {
3085
338
    { "const", DeclSpec::TQ_const, ConstQualLoc },
3086
338
    { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
3087
338
    { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
3088
338
    { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
3089
338
    { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
3090
338
  };
3091
3092
338
  SmallString<32> QualStr;
3093
338
  unsigned NumQuals = 0;
3094
338
  SourceLocation Loc;
3095
338
  FixItHint FixIts[5];
3096
3097
  // Build a string naming the redundant qualifiers.
3098
1.69k
  for (auto &E : QualKinds) {
3099
1.69k
    if (Quals & E.Mask) {
3100
370
      if (!QualStr.empty()) 
QualStr += ' '32
;
3101
370
      QualStr += E.Name;
3102
3103
      // If we have a location for the qualifier, offer a fixit.
3104
370
      SourceLocation QualLoc = E.Loc;
3105
370
      if (QualLoc.isValid()) {
3106
349
        FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
3107
349
        if (Loc.isInvalid() ||
3108
349
            
getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc)31
)
3109
321
          Loc = QualLoc;
3110
349
      }
3111
3112
370
      ++NumQuals;
3113
370
    }
3114
1.69k
  }
3115
3116
338
  Diag(Loc.isInvalid() ? 
FallbackLoc20
:
Loc318
, DiagID)
3117
338
    << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
3118
338
}
3119
3120
// Diagnose pointless type qualifiers on the return type of a function.
3121
static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
3122
                                                  Declarator &D,
3123
370
                                                  unsigned FunctionChunkIndex) {
3124
370
  const DeclaratorChunk::FunctionTypeInfo &FTI =
3125
370
      D.getTypeObject(FunctionChunkIndex).Fun;
3126
370
  if (FTI.hasTrailingReturnType()) {
3127
10
    S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3128
10
                                RetTy.getLocalCVRQualifiers(),
3129
10
                                FTI.getTrailingReturnTypeLoc());
3130
10
    return;
3131
10
  }
3132
3133
360
  for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
3134
360
                End = D.getNumTypeObjects();
3135
363
       OuterChunkIndex != End; 
++OuterChunkIndex3
) {
3136
37
    DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
3137
37
    switch (OuterChunk.Kind) {
3138
3
    case DeclaratorChunk::Paren:
3139
3
      continue;
3140
3141
24
    case DeclaratorChunk::Pointer: {
3142
24
      DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
3143
24
      S.diagnoseIgnoredQualifiers(
3144
24
          diag::warn_qual_return_type,
3145
24
          PTI.TypeQuals,
3146
24
          SourceLocation(),
3147
24
          PTI.ConstQualLoc,
3148
24
          PTI.VolatileQualLoc,
3149
24
          PTI.RestrictQualLoc,
3150
24
          PTI.AtomicQualLoc,
3151
24
          PTI.UnalignedQualLoc);
3152
24
      return;
3153
0
    }
3154
3155
0
    case DeclaratorChunk::Function:
3156
0
    case DeclaratorChunk::BlockPointer:
3157
1
    case DeclaratorChunk::Reference:
3158
1
    case DeclaratorChunk::Array:
3159
10
    case DeclaratorChunk::MemberPointer:
3160
10
    case DeclaratorChunk::Pipe:
3161
      // FIXME: We can't currently provide an accurate source location and a
3162
      // fix-it hint for these.
3163
10
      unsigned AtomicQual = RetTy->isAtomicType() ? 
DeclSpec::TQ_atomic0
: 0;
3164
10
      S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3165
10
                                  RetTy.getCVRQualifiers() | AtomicQual,
3166
10
                                  D.getIdentifierLoc());
3167
10
      return;
3168
37
    }
3169
3170
37
    
llvm_unreachable0
("unknown declarator chunk kind");
3171
37
  }
3172
3173
  // If the qualifiers come from a conversion function type, don't diagnose
3174
  // them -- they're not necessarily redundant, since such a conversion
3175
  // operator can be explicitly called as "x.operator const int()".
3176
326
  if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3177
19
    return;
3178
3179
  // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
3180
  // which are present there.
3181
307
  S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3182
307
                              D.getDeclSpec().getTypeQualifiers(),
3183
307
                              D.getIdentifierLoc(),
3184
307
                              D.getDeclSpec().getConstSpecLoc(),
3185
307
                              D.getDeclSpec().getVolatileSpecLoc(),
3186
307
                              D.getDeclSpec().getRestrictSpecLoc(),
3187
307
                              D.getDeclSpec().getAtomicSpecLoc(),
3188
307
                              D.getDeclSpec().getUnalignedSpecLoc());
3189
307
}
3190
3191
static std::pair<QualType, TypeSourceInfo *>
3192
InventTemplateParameter(TypeProcessingState &state, QualType T,
3193
                        TypeSourceInfo *TrailingTSI, AutoType *Auto,
3194
2.16k
                        InventedTemplateParameterInfo &Info) {
3195
2.16k
  Sema &S = state.getSema();
3196
2.16k
  Declarator &D = state.getDeclarator();
3197
3198
2.16k
  const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth;
3199
2.16k
  const unsigned AutoParameterPosition = Info.TemplateParams.size();
3200
2.16k
  const bool IsParameterPack = D.hasEllipsis();
3201
3202
  // If auto is mentioned in a lambda parameter or abbreviated function
3203
  // template context, convert it to a template parameter type.
3204
3205
  // Create the TemplateTypeParmDecl here to retrieve the corresponding
3206
  // template parameter type. Template parameters are temporarily added
3207
  // to the TU until the associated TemplateDecl is created.
3208
2.16k
  TemplateTypeParmDecl *InventedTemplateParam =
3209
2.16k
      TemplateTypeParmDecl::Create(
3210
2.16k
          S.Context, S.Context.getTranslationUnitDecl(),
3211
2.16k
          /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(),
3212
2.16k
          /*NameLoc=*/D.getIdentifierLoc(),
3213
2.16k
          TemplateParameterDepth, AutoParameterPosition,
3214
2.16k
          S.InventAbbreviatedTemplateParameterTypeName(
3215
2.16k
              D.getIdentifier(), AutoParameterPosition), false,
3216
2.16k
          IsParameterPack, /*HasTypeConstraint=*/Auto->isConstrained());
3217
2.16k
  InventedTemplateParam->setImplicit();
3218
2.16k
  Info.TemplateParams.push_back(InventedTemplateParam);
3219
3220
  // Attach type constraints to the new parameter.
3221
2.16k
  if (Auto->isConstrained()) {
3222
75
    if (TrailingTSI) {
3223
      // The 'auto' appears in a trailing return type we've already built;
3224
      // extract its type constraints to attach to the template parameter.
3225
0
      AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc();
3226
0
      TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc());
3227
0
      bool Invalid = false;
3228
0
      for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx) {
3229
0
        if (D.getEllipsisLoc().isInvalid() && !Invalid &&
3230
0
            S.DiagnoseUnexpandedParameterPack(AutoLoc.getArgLoc(Idx),
3231
0
                                              Sema::UPPC_TypeConstraint))
3232
0
          Invalid = true;
3233
0
        TAL.addArgument(AutoLoc.getArgLoc(Idx));
3234
0
      }
3235
3236
0
      if (!Invalid) {
3237
0
        S.AttachTypeConstraint(
3238
0
            AutoLoc.getNestedNameSpecifierLoc(), AutoLoc.getConceptNameInfo(),
3239
0
            AutoLoc.getNamedConcept(),
3240
0
            AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr,
3241
0
            InventedTemplateParam, D.getEllipsisLoc());
3242
0
      }
3243
75
    } else {
3244
      // The 'auto' appears in the decl-specifiers; we've not finished forming
3245
      // TypeSourceInfo for it yet.
3246
75
      TemplateIdAnnotation *TemplateId = D.getDeclSpec().getRepAsTemplateId();
3247
75
      TemplateArgumentListInfo TemplateArgsInfo;
3248
75
      bool Invalid = false;
3249
75
      if (TemplateId->LAngleLoc.isValid()) {
3250
39
        ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
3251
39
                                           TemplateId->NumArgs);
3252
39
        S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
3253
3254
39
        if (D.getEllipsisLoc().isInvalid()) {
3255
31
          for (TemplateArgumentLoc Arg : TemplateArgsInfo.arguments()) {
3256
31
            if (S.DiagnoseUnexpandedParameterPack(Arg,
3257
31
                                                  Sema::UPPC_TypeConstraint)) {
3258
2
              Invalid = true;
3259
2
              break;
3260
2
            }
3261
31
          }
3262
31
        }
3263
39
      }
3264
75
      if (!Invalid) {
3265
73
        S.AttachTypeConstraint(
3266
73
            D.getDeclSpec().getTypeSpecScope().getWithLocInContext(S.Context),
3267
73
            DeclarationNameInfo(DeclarationName(TemplateId->Name),
3268
73
                                TemplateId->TemplateNameLoc),
3269
73
            cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl()),
3270
73
            TemplateId->LAngleLoc.isValid() ? 
&TemplateArgsInfo37
:
nullptr36
,
3271
73
            InventedTemplateParam, D.getEllipsisLoc());
3272
73
      }
3273
75
    }
3274
75
  }
3275
3276
  // Replace the 'auto' in the function parameter with this invented
3277
  // template type parameter.
3278
  // FIXME: Retain some type sugar to indicate that this was written
3279
  //  as 'auto'?
3280
2.16k
  QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0);
3281
2.16k
  QualType NewT = state.ReplaceAutoType(T, Replacement);
3282
2.16k
  TypeSourceInfo *NewTSI =
3283
2.16k
      TrailingTSI ? 
S.ReplaceAutoTypeSourceInfo(TrailingTSI, Replacement)8
3284
2.16k
                  : 
nullptr2.16k
;
3285
2.16k
  return {NewT, NewTSI};
3286
2.16k
}
3287
3288
static TypeSourceInfo *
3289
GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3290
                               QualType T, TypeSourceInfo *ReturnTypeInfo);
3291
3292
static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
3293
137M
                                             TypeSourceInfo *&ReturnTypeInfo) {
3294
137M
  Sema &SemaRef = state.getSema();
3295
137M
  Declarator &D = state.getDeclarator();
3296
137M
  QualType T;
3297
137M
  ReturnTypeInfo = nullptr;
3298
3299
  // The TagDecl owned by the DeclSpec.
3300
137M
  TagDecl *OwnedTagDecl = nullptr;
3301
3302
137M
  switch (D.getName().getKind()) {
3303
0
  case UnqualifiedIdKind::IK_ImplicitSelfParam:
3304
324k
  case UnqualifiedIdKind::IK_OperatorFunctionId:
3305
137M
  case UnqualifiedIdKind::IK_Identifier:
3306
137M
  case UnqualifiedIdKind::IK_LiteralOperatorId:
3307
137M
  case UnqualifiedIdKind::IK_TemplateId:
3308
137M
    T = ConvertDeclSpecToType(state);
3309
3310
137M
    if (!D.isInvalidType() && 
D.getDeclSpec().isTypeSpecOwned()137M
) {
3311
443k
      OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3312
      // Owned declaration is embedded in declarator.
3313
443k
      OwnedTagDecl->setEmbeddedInDeclarator(true);
3314
443k
    }
3315
137M
    break;
3316
3317
274k
  case UnqualifiedIdKind::IK_ConstructorName:
3318
274k
  case UnqualifiedIdKind::IK_ConstructorTemplateId:
3319
315k
  case UnqualifiedIdKind::IK_DestructorName:
3320
    // Constructors and destructors don't have return types. Use
3321
    // "void" instead.
3322
315k
    T = SemaRef.Context.VoidTy;
3323
315k
    processTypeAttrs(state, T, TAL_DeclSpec,
3324
315k
                     D.getMutableDeclSpec().getAttributes());
3325
315k
    break;
3326
3327
430
  case UnqualifiedIdKind::IK_DeductionGuideName:
3328
    // Deduction guides have a trailing return type and no type in their
3329
    // decl-specifier sequence. Use a placeholder return type for now.
3330
430
    T = SemaRef.Context.DependentTy;
3331
430
    break;
3332
3333
13.0k
  case UnqualifiedIdKind::IK_ConversionFunctionId:
3334
    // The result type of a conversion function is the type that it
3335
    // converts to.
3336
13.0k
    T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
3337
13.0k
                                  &ReturnTypeInfo);
3338
13.0k
    break;
3339
137M
  }
3340
3341
137M
  if (!D.getAttributes().empty())
3342
2.01M
    distributeTypeAttrsFromDeclarator(state, T);
3343
3344
  // Find the deduced type in this type. Look in the trailing return type if we
3345
  // have one, otherwise in the DeclSpec type.
3346
  // FIXME: The standard wording doesn't currently describe this.
3347
137M
  DeducedType *Deduced = T->getContainedDeducedType();
3348
137M
  bool DeducedIsTrailingReturnType = false;
3349
137M
  if (Deduced && 
isa<AutoType>(Deduced)37.9k
&&
D.hasTrailingReturnType()37.0k
) {
3350
16.1k
    QualType T = SemaRef.GetTypeFromParser(D.getTrailingReturnType());
3351
16.1k
    Deduced = T.isNull() ? 
nullptr48
:
T->getContainedDeducedType()16.1k
;
3352
16.1k
    DeducedIsTrailingReturnType = true;
3353
16.1k
  }
3354
3355
  // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
3356
137M
  if (Deduced) {
3357
21.9k
    AutoType *Auto = dyn_cast<AutoType>(Deduced);
3358
21.9k
    int Error = -1;
3359
3360
    // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
3361
    // class template argument deduction)?
3362
21.9k
    bool IsCXXAutoType =
3363
21.9k
        (Auto && 
Auto->getKeyword() != AutoTypeKeyword::GNUAutoType21.1k
);
3364
21.9k
    bool IsDeducedReturnType = false;
3365
3366
21.9k
    switch (D.getContext()) {
3367
3.34k
    case DeclaratorContext::LambdaExpr:
3368
      // Declared return type of a lambda-declarator is implicit and is always
3369
      // 'auto'.
3370
3.34k
      break;
3371
0
    case DeclaratorContext::ObjCParameter:
3372
0
    case DeclaratorContext::ObjCResult:
3373
0
      Error = 0;
3374
0
      break;
3375
2
    case DeclaratorContext::RequiresExpr:
3376
2
      Error = 22;
3377
2
      break;
3378
120
    case DeclaratorContext::Prototype:
3379
2.19k
    case DeclaratorContext::LambdaExprParameter: {
3380
2.19k
      InventedTemplateParameterInfo *Info = nullptr;
3381
2.19k
      if (D.getContext() == DeclaratorContext::Prototype) {
3382
        // With concepts we allow 'auto' in function parameters.
3383
120
        if (!SemaRef.getLangOpts().CPlusPlus20 || 
!Auto107
||
3384
120
            
Auto->getKeyword() != AutoTypeKeyword::Auto106
) {
3385
18
          Error = 0;
3386
18
          break;
3387
102
        } else if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) {
3388
4
          Error = 21;
3389
4
          break;
3390
4
        }
3391
3392
98
        Info = &SemaRef.InventedParameterInfos.back();
3393
2.07k
      } else {
3394
        // In C++14, generic lambdas allow 'auto' in their parameters.
3395
2.07k
        if (!SemaRef.getLangOpts().CPlusPlus14 || 
!Auto2.07k
||
3396
2.07k
            
Auto->getKeyword() != AutoTypeKeyword::Auto2.07k
) {
3397
4
          Error = 16;
3398
4
          break;
3399
4
        }
3400
2.07k
        Info = SemaRef.getCurLambda();
3401
2.07k
        assert(Info && "No LambdaScopeInfo on the stack!");
3402
2.07k
      }
3403
3404
      // We'll deal with inventing template parameters for 'auto' in trailing
3405
      // return types when we pick up the trailing return type when processing
3406
      // the function chunk.
3407
2.16k
      if (!DeducedIsTrailingReturnType)
3408
2.16k
        T = InventTemplateParameter(state, T, nullptr, Auto, *Info).first;
3409
2.16k
      break;
3410
2.19k
    }
3411
695
    case DeclaratorContext::Member: {
3412
695
      if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
3413
695
          
D.isFunctionDeclarator()492
)
3414
674
        break;
3415
21
      bool Cxx = SemaRef.getLangOpts().CPlusPlus;
3416
21
      if (isa<ObjCContainerDecl>(SemaRef.CurContext)) {
3417
4
        Error = 6; // Interface member.
3418
17
      } else {
3419
17
        switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
3420
0
        case TTK_Enum: llvm_unreachable("unhandled tag kind");
3421
13
        case TTK_Struct: Error = Cxx ? 
112
:
21
; /* Struct member */ break;
3422
0
        case TTK_Union:  Error = Cxx ? 3 : 4; /* Union member */ break;
3423
4
        case TTK_Class:  Error = 5; /* Class member */ break;
3424
0
        case TTK_Interface: Error = 6; /* Interface member */ break;
3425
17
        }
3426
17
      }
3427
21
      if (D.getDeclSpec().isFriendSpecified())
3428
6
        Error = 20; // Friend type
3429
21
      break;
3430
21
    }
3431
8
    case DeclaratorContext::CXXCatch:
3432
9
    case DeclaratorContext::ObjCCatch:
3433
9
      Error = 7; // Exception declaration
3434
9
      break;
3435
202
    case DeclaratorContext::TemplateParam:
3436
202
      if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3437
202
          
!SemaRef.getLangOpts().CPlusPlus2015
)
3438
2
        Error = 19; // Template parameter (until C++20)
3439
200
      else if (!SemaRef.getLangOpts().CPlusPlus17)
3440
5
        Error = 8; // Template parameter (until C++17)
3441
202
      break;
3442
0
    case DeclaratorContext::BlockLiteral:
3443
0
      Error = 9; // Block literal
3444
0
      break;
3445
406
    case DeclaratorContext::TemplateArg:
3446
      // Within a template argument list, a deduced template specialization
3447
      // type will be reinterpreted as a template template argument.
3448
406
      if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3449
406
          
!D.getNumTypeObjects()394
&&
3450
406
          
D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier393
)
3451
392
        break;
3452
406
      
LLVM_FALLTHROUGH14
;14
3453
15
    case DeclaratorContext::TemplateTypeArg:
3454
15
      Error = 10; // Template type argument
3455
15
      break;
3456
13
    case DeclaratorContext::AliasDecl:
3457
13
    case DeclaratorContext::AliasTemplate:
3458
13
      Error = 12; // Type alias
3459
13
      break;
3460
145
    case DeclaratorContext::TrailingReturn:
3461
192
    case DeclaratorContext::TrailingReturnVar:
3462
192
      if (!SemaRef.getLangOpts().CPlusPlus14 || 
!IsCXXAutoType184
)
3463
9
        Error = 13; // Function return type
3464
192
      IsDeducedReturnType = true;
3465
192
      break;
3466
140
    case DeclaratorContext::ConversionId:
3467
140
      if (!SemaRef.getLangOpts().CPlusPlus14 || 
!IsCXXAutoType138
)
3468
6
        Error = 14; // conversion-type-id
3469
140
      IsDeducedReturnType = true;
3470
140
      break;
3471
78
    case DeclaratorContext::FunctionalCast:
3472
78
      if (isa<DeducedTemplateSpecializationType>(Deduced))
3473
78
        break;
3474
78
      
LLVM_FALLTHROUGH0
;0
3475
30
    case DeclaratorContext::TypeName:
3476
30
      Error = 15; // Generic
3477
30
      break;
3478
3.45k
    case DeclaratorContext::File:
3479
13.8k
    case DeclaratorContext::Block:
3480
14.4k
    case DeclaratorContext::ForInit:
3481
14.4k
    case DeclaratorContext::SelectionInit:
3482
14.5k
    case DeclaratorContext::Condition:
3483
      // FIXME: P0091R3 (erroneously) does not permit class template argument
3484
      // deduction in conditions, for-init-statements, and other declarations
3485
      // that are not simple-declarations.
3486
14.5k
      break;
3487
61
    case DeclaratorContext::CXXNew:
3488
      // FIXME: P0091R3 does not permit class template argument deduction here,
3489
      // but we follow GCC and allow it anyway.
3490
61
      if (!IsCXXAutoType && 
!isa<DeducedTemplateSpecializationType>(Deduced)14
)
3491
1
        Error = 17; // 'new' type
3492
61
      break;
3493
1
    case DeclaratorContext::KNRTypeList:
3494
1
      Error = 18; // K&R function parameter
3495
1
      break;
3496
21.9k
    }
3497
3498
21.9k
    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3499
10
      Error = 11;
3500
3501
    // In Objective-C it is an error to use 'auto' on a function declarator
3502
    // (and everywhere for '__auto_type').
3503
21.9k
    if (D.isFunctionDeclarator() &&
3504
21.9k
        
(5.13k
!SemaRef.getLangOpts().CPlusPlus115.13k
||
!IsCXXAutoType5.13k
))
3505
7
      Error = 13;
3506
3507
21.9k
    SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
3508
21.9k
    if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3509
62
      AutoRange = D.getName().getSourceRange();
3510
3511
21.9k
    if (Error != -1) {
3512
156
      unsigned Kind;
3513
156
      if (Auto) {
3514
116
        switch (Auto->getKeyword()) {
3515
93
        case AutoTypeKeyword::Auto: Kind = 0; break;
3516
14
        case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3517
9
        case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3518
116
        }
3519
116
      } else {
3520
40
        assert(isa<DeducedTemplateSpecializationType>(Deduced) &&
3521
40
               "unknown auto type");
3522
0
        Kind = 3;
3523
40
      }
3524
3525
156
      auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3526
156
      TemplateName TN = DTST ? 
DTST->getTemplateName()40
:
TemplateName()116
;
3527
3528
156
      SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3529
156
        << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3530
156
        << QualType(Deduced, 0) << AutoRange;
3531
156
      if (auto *TD = TN.getAsTemplateDecl())
3532
40
        SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
3533
3534
156
      T = SemaRef.Context.IntTy;
3535
156
      D.setInvalidType(true);
3536
21.7k
    } else if (Auto && 
D.getContext() != DeclaratorContext::LambdaExpr20.9k
) {
3537
      // If there was a trailing return type, we already got
3538
      // warn_cxx98_compat_trailing_return_type in the parser.
3539
17.6k
      SemaRef.Diag(AutoRange.getBegin(),
3540
17.6k
                   D.getContext() == DeclaratorContext::LambdaExprParameter
3541
17.6k
                       ? 
diag::warn_cxx11_compat_generic_lambda2.07k
3542
17.6k
                   : 
IsDeducedReturnType15.5k
3543
15.5k
                       ? 
diag::warn_cxx11_compat_deduced_return_type317
3544
15.5k
                       : 
diag::warn_cxx98_compat_auto_type_specifier15.2k
)
3545
17.6k
          << AutoRange;
3546
17.6k
    }
3547
21.9k
  }
3548
3549
137M
  if (SemaRef.getLangOpts().CPlusPlus &&
3550
137M
      
OwnedTagDecl45.0M
&&
OwnedTagDecl->isCompleteDefinition()82.5k
) {
3551
    // Check the contexts where C++ forbids the declaration of a new class
3552
    // or enumeration in a type-specifier-seq.
3553
63.9k
    unsigned DiagID = 0;
3554
63.9k
    switch (D.getContext()) {
3555
0
    case DeclaratorContext::TrailingReturn:
3556
0
    case DeclaratorContext::TrailingReturnVar:
3557
      // Class and enumeration definitions are syntactically not allowed in
3558
      // trailing return types.
3559
0
      llvm_unreachable("parser should not have allowed this");
3560
0
      break;
3561
52.7k
    case DeclaratorContext::File:
3562
59.9k
    case DeclaratorContext::Member:
3563
63.8k
    case DeclaratorContext::Block:
3564
63.8k
    case DeclaratorContext::ForInit:
3565
63.8k
    case DeclaratorContext::SelectionInit:
3566
63.8k
    case DeclaratorContext::BlockLiteral:
3567
63.8k
    case DeclaratorContext::LambdaExpr:
3568
      // C++11 [dcl.type]p3:
3569
      //   A type-specifier-seq shall not define a class or enumeration unless
3570
      //   it appears in the type-id of an alias-declaration (7.1.3) that is not
3571
      //   the declaration of a template-declaration.
3572
63.8k
    case DeclaratorContext::AliasDecl:
3573
63.8k
      break;
3574
5
    case DeclaratorContext::AliasTemplate:
3575
5
      DiagID = diag::err_type_defined_in_alias_template;
3576
5
      break;
3577
43
    case DeclaratorContext::TypeName:
3578
43
    case DeclaratorContext::FunctionalCast:
3579
43
    case DeclaratorContext::ConversionId:
3580
43
    case DeclaratorContext::TemplateParam:
3581
43
    case DeclaratorContext::CXXNew:
3582
43
    case DeclaratorContext::CXXCatch:
3583
43
    case DeclaratorContext::ObjCCatch:
3584
43
    case DeclaratorContext::TemplateArg:
3585
43
    case DeclaratorContext::TemplateTypeArg:
3586
43
      DiagID = diag::err_type_defined_in_type_specifier;
3587
43
      break;
3588
5
    case DeclaratorContext::Prototype:
3589
5
    case DeclaratorContext::LambdaExprParameter:
3590
5
    case DeclaratorContext::ObjCParameter:
3591
5
    case DeclaratorContext::ObjCResult:
3592
5
    case DeclaratorContext::KNRTypeList:
3593
5
    case DeclaratorContext::RequiresExpr:
3594
      // C++ [dcl.fct]p6:
3595
      //   Types shall not be defined in return or parameter types.
3596
5
      DiagID = diag::err_type_defined_in_param_type;
3597
5
      break;
3598
15
    case DeclaratorContext::Condition:
3599
      // C++ 6.4p2:
3600
      // The type-specifier-seq shall not contain typedef and shall not declare
3601
      // a new class or enumeration.
3602
15
      DiagID = diag::err_type_defined_in_condition;
3603
15
      break;
3604
63.9k
    }
3605
3606
63.9k
    if (DiagID != 0) {
3607
68
      SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3608
68
          << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
3609
68
      D.setInvalidType(true);
3610
68
    }
3611
63.9k
  }
3612
3613
137M
  assert(!T.isNull() && "This function should not return a null type");
3614
0
  return T;
3615
137M
}
3616
3617
/// Produce an appropriate diagnostic for an ambiguity between a function
3618
/// declarator and a C++ direct-initializer.
3619
static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
3620
64.2k
                                       DeclaratorChunk &DeclType, QualType RT) {
3621
64.2k
  const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3622
64.2k
  assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3623
3624
  // If the return type is void there is no ambiguity.
3625
64.2k
  if (RT->isVoidType())
3626
10.1k
    return;
3627
3628
  // An initializer for a non-class type can have at most one argument.
3629
54.0k
  if (!RT->isRecordType() && 
FTI.NumParams > 152.7k
)
3630
420
    return;
3631
3632
  // An initializer for a reference must have exactly one argument.
3633
53.6k
  if (RT->isReferenceType() && 
FTI.NumParams != 1452
)
3634
393
    return;
3635
3636
  // Only warn if this declarator is declaring a function at block scope, and
3637
  // doesn't have a storage class (such as 'extern') specified.
3638
53.2k
  if (!D.isFunctionDeclarator() ||
3639
53.2k
      
D.getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration53.1k
||
3640
53.2k
      
!S.CurContext->isFunctionOrMethod()53.1k
||
3641
53.2k
      
D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_unspecified138
)
3642
53.1k
    return;
3643
3644
  // Inside a condition, a direct initializer is not permitted. We allow one to
3645
  // be parsed in order to give better diagnostics in condition parsing.
3646
132
  if (D.getContext() == DeclaratorContext::Condition)
3647
4
    return;
3648
3649
128
  SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3650
3651
128
  S.Diag(DeclType.Loc,
3652
128
         FTI.NumParams ? 
diag::warn_parens_disambiguated_as_function_declaration24
3653
128
                       : 
diag::warn_empty_parens_are_function_decl104
)
3654
128
      << ParenRange;
3655
3656
  // If the declaration looks like:
3657
  //   T var1,
3658
  //   f();
3659
  // and name lookup finds a function named 'f', then the ',' was
3660
  // probably intended to be a ';'.
3661
128
  if (!D.isFirstDeclarator() && 
D.getIdentifier()19
) {
3662
19
    FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3663
19
    FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
3664
19
    if (Comma.getFileID() != Name.getFileID() ||
3665
19
        Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3666
19
      LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3667
19
                          Sema::LookupOrdinaryName);
3668
19
      if (S.LookupName(Result, S.getCurScope()))
3669
13
        S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3670
13
          << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
3671
13
          << D.getIdentifier();
3672
19
      Result.suppressDiagnostics();
3673
19
    }
3674
19
  }
3675
3676
128
  if (FTI.NumParams > 0) {
3677
    // For a declaration with parameters, eg. "T var(T());", suggest adding
3678
    // parens around the first parameter to turn the declaration into a
3679
    // variable declaration.
3680
24
    SourceRange Range = FTI.Params[0].Param->getSourceRange();
3681
24
    SourceLocation B = Range.getBegin();
3682
24
    SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3683
    // FIXME: Maybe we should suggest adding braces instead of parens
3684
    // in C++11 for classes that don't have an initializer_list constructor.
3685
24
    S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3686
24
      << FixItHint::CreateInsertion(B, "(")
3687
24
      << FixItHint::CreateInsertion(E, ")");
3688
104
  } else {
3689
    // For a declaration without parameters, eg. "T var();", suggest replacing
3690
    // the parens with an initializer to turn the declaration into a variable
3691
    // declaration.
3692
104
    const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3693
3694
    // Empty parens mean value-initialization, and no parens mean
3695
    // default initialization. These are equivalent if the default
3696
    // constructor is user-provided or if zero-initialization is a
3697
    // no-op.
3698
104
    if (RD && 
RD->hasDefinition()31
&&
3699
104
        
(27
RD->isEmpty()27
||
RD->hasUserProvidedDefaultConstructor()18
))
3700
13
      S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3701
13
        << FixItHint::CreateRemoval(ParenRange);
3702
91
    else {
3703
91
      std::string Init =
3704
91
          S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3705
91
      if (Init.empty() && 
S.LangOpts.CPlusPlus1112
)
3706
9
        Init = "{}";
3707
91
      if (!Init.empty())
3708
88
        S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3709
88
          << FixItHint::CreateReplacement(ParenRange, Init);
3710
91
    }
3711
104
  }
3712
128
}
3713
3714
/// Produce an appropriate diagnostic for a declarator with top-level
3715
/// parentheses.
3716
442
static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) {
3717
442
  DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1);
3718
442
  assert(Paren.Kind == DeclaratorChunk::Paren &&
3719
442
         "do not have redundant top-level parentheses");
3720
3721
  // This is a syntactic check; we're not interested in cases that arise
3722
  // during template instantiation.
3723
442
  if (S.inTemplateInstantiation())
3724
0
    return;
3725
3726
  // Check whether this could be intended to be a construction of a temporary
3727
  // object in C++ via a function-style cast.
3728
442
  bool CouldBeTemporaryObject =
3729
442
      S.getLangOpts().CPlusPlus && 
D.isExpressionContext()417
&&
3730
442
      
!D.isInvalidType()142
&&
D.getIdentifier()126
&&
3731
442
      
D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier120
&&
3732
442
      
(109
T->isRecordType()109
||
T->isDependentType()64
) &&
3733
442
      
D.getDeclSpec().getTypeQualifiers() == 046
&&
D.isFirstDeclarator()46
;
3734
3735
442
  bool StartsWithDeclaratorId = true;
3736
730
  for (auto &C : D.type_objects()) {
3737
730
    switch (C.Kind) {
3738
501
    case DeclaratorChunk::Paren:
3739
501
      if (&C == &Paren)
3740
442
        continue;
3741
501
      
LLVM_FALLTHROUGH59
;59
3742
94
    case DeclaratorChunk::Pointer:
3743
94
      StartsWithDeclaratorId = false;
3744
94
      continue;
3745
3746
18
    case DeclaratorChunk::Array:
3747
18
      if (!C.Arr.NumElts)
3748
0
        CouldBeTemporaryObject = false;
3749
18
      continue;
3750
3751
9
    case DeclaratorChunk::Reference:
3752
      // FIXME: Suppress the warning here if there is no initializer; we're
3753
      // going to give an error anyway.
3754
      // We assume that something like 'T (&x) = y;' is highly likely to not
3755
      // be intended to be a temporary object.
3756
9
      CouldBeTemporaryObject = false;
3757
9
      StartsWithDeclaratorId = false;
3758
9
      continue;
3759
3760
53
    case DeclaratorChunk::Function:
3761
      // In a new-type-id, function chunks require parentheses.
3762
53
      if (D.getContext() == DeclaratorContext::CXXNew)
3763
0
        return;
3764
      // FIXME: "A(f())" deserves a vexing-parse warning, not just a
3765
      // redundant-parens warning, but we don't know whether the function
3766
      // chunk was syntactically valid as an expression here.
3767
53
      CouldBeTemporaryObject = false;
3768
53
      continue;
3769
3770
0
    case DeclaratorChunk::BlockPointer:
3771
114
    case DeclaratorChunk::MemberPointer:
3772
114
    case DeclaratorChunk::Pipe:
3773
      // These cannot appear in expressions.
3774
114
      CouldBeTemporaryObject = false;
3775
114
      StartsWithDeclaratorId = false;
3776
114
      continue;
3777
730
    }
3778
730
  }
3779
3780
  // FIXME: If there is an initializer, assume that this is not intended to be
3781
  // a construction of a temporary object.
3782
3783
  // Check whether the name has already been declared; if not, this is not a
3784
  // function-style cast.
3785
442
  if (CouldBeTemporaryObject) {
3786
33
    LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3787
33
                        Sema::LookupOrdinaryName);
3788
33
    if (!S.LookupName(Result, S.getCurScope()))
3789
18
      CouldBeTemporaryObject = false;
3790
33
    Result.suppressDiagnostics();
3791
33
  }
3792
3793
442
  SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
3794
3795
442
  if (!CouldBeTemporaryObject) {
3796
    // If we have A (::B), the parentheses affect the meaning of the program.
3797
    // Suppress the warning in that case. Don't bother looking at the DeclSpec
3798
    // here: even (e.g.) "int ::x" is visually ambiguous even though it's
3799
    // formally unambiguous.
3800
427
    if (StartsWithDeclaratorId && 
D.getCXXScopeSpec().isValid()253
) {
3801
63
      for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS;
3802
51
           
NNS = NNS->getPrefix()39
) {
3803
51
        if (NNS->getKind() == NestedNameSpecifier::Global)
3804
12
          return;
3805
51
      }
3806
24
    }
3807
3808
415
    S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
3809
415
        << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
3810
415
        << FixItHint::CreateRemoval(Paren.EndLoc);
3811
415
    return;
3812
427
  }
3813
3814
15
  S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
3815
15
      << ParenRange << D.getIdentifier();
3816
15
  auto *RD = T->getAsCXXRecordDecl();
3817
15
  if (!RD || 
!RD->hasDefinition()14
||
RD->hasNonTrivialDestructor()14
)
3818
7
    S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
3819
7
        << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
3820
7
        << D.getIdentifier();
3821
  // FIXME: A cast to void is probably a better suggestion in cases where it's
3822
  // valid (when there is no initializer and we're not in a condition).
3823
15
  S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses)
3824
15
      << FixItHint::CreateInsertion(D.getBeginLoc(), "(")
3825
15
      << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getEndLoc()), ")");
3826
15
  S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
3827
15
      << FixItHint::CreateRemoval(Paren.Loc)
3828
15
      << FixItHint::CreateRemoval(Paren.EndLoc);
3829
15
}
3830
3831
/// Helper for figuring out the default CC for a function declarator type.  If
3832
/// this is the outermost chunk, then we can determine the CC from the
3833
/// declarator context.  If not, then this could be either a member function
3834
/// type or normal function type.
3835
static CallingConv getCCForDeclaratorChunk(
3836
    Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
3837
31.5M
    const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
3838
31.5M
  assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3839
3840
  // Check for an explicit CC attribute.
3841
98.5k
  for (const ParsedAttr &AL : AttrList) {
3842
98.5k
    switch (AL.getKind()) {
3843
25.8k
    
CALLING_CONV_ATTRS_CASELIST353
: {
3844
      // Ignore attributes that don't validate or can't apply to the
3845
      // function type.  We'll diagnose the failure to apply them in
3846
      // handleFunctionTypeAttr.
3847
25.8k
      CallingConv CC;
3848
25.8k
      if (
!S.CheckCallingConvAttr(AL, CC)2.51k
&&
3849
2.51k
          
(2.48k
!FTI.isVariadic2.48k
||
supportsVariadicCall(CC)69
)) {
3850
2.46k
        return CC;
3851
2.46k
      }
3852
55
      break;
3853
25.8k
    }
3854
3855
96.0k
    default:
3856
96.0k
      break;
3857
98.5k
    }
3858
98.5k
  }
3859
3860
31.4M
  bool IsCXXInstanceMethod = false;
3861
3862
31.4M
  if (S.getLangOpts().CPlusPlus) {
3863
    // Look inwards through parentheses to see if this chunk will form a
3864
    // member pointer type or if we're the declarator.  Any type attributes
3865
    // between here and there will override the CC we choose here.
3866
10.3M
    unsigned I = ChunkIndex;
3867
10.3M
    bool FoundNonParen = false;
3868
10.5M
    while (I && 
!FoundNonParen236k
) {
3869
234k
      --I;
3870
234k
      if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
3871
111k
        FoundNonParen = true;
3872
234k
    }
3873
3874
10.3M
    if (FoundNonParen) {
3875
      // If we're not the declarator, we're a regular function type unless we're
3876
      // in a member pointer.
3877
111k
      IsCXXInstanceMethod =
3878
111k
          D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
3879
10.2M
    } else if (D.getContext() == DeclaratorContext::LambdaExpr) {
3880
      // This can only be a call operator for a lambda, which is an instance
3881
      // method.
3882
6.04k
      IsCXXInstanceMethod = true;
3883
10.2M
    } else {
3884
      // We're the innermost decl chunk, so must be a function declarator.
3885
10.2M
      assert(D.isFunctionDeclarator());
3886
3887
      // If we're inside a record, we're declaring a method, but it could be
3888
      // explicitly or implicitly static.
3889
0
      IsCXXInstanceMethod =
3890
10.2M
          D.isFirstDeclarationOfMember() &&
3891
10.2M
          
D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef1.00M
&&
3892
10.2M
          
!D.isStaticMember()997k
;
3893
10.2M
    }
3894
10.3M
  }
3895
3896
0
  CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
3897
31.4M
                                                         IsCXXInstanceMethod);
3898
3899
  // Attribute AT_OpenCLKernel affects the calling convention for SPIR
3900
  // and AMDGPU targets, hence it cannot be treated as a calling
3901
  // convention attribute. This is the simplest place to infer
3902
  // calling convention for OpenCL kernels.
3903
31.4M
  if (S.getLangOpts().OpenCL) {
3904
375k
    for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
3905
375k
      if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) {
3906
993
        CC = CC_OpenCLKernel;
3907
993
        break;
3908
993
      }
3909
375k
    }
3910
229k
  }
3911
3912
31.4M
  return CC;
3913
31.5M
}
3914
3915
namespace {
3916
  /// A simple notion of pointer kinds, which matches up with the various
3917
  /// pointer declarators.
3918
  enum class SimplePointerKind {
3919
    Pointer,
3920
    BlockPointer,
3921
    MemberPointer,
3922
    Array,
3923
  };
3924
} // end anonymous namespace
3925
3926
2.50M
IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
3927
2.50M
  switch (nullability) {
3928
2.05M
  case NullabilityKind::NonNull:
3929
2.05M
    if (!Ident__Nonnull)
3930
982
      Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3931
2.05M
    return Ident__Nonnull;
3932
3933
438k
  case NullabilityKind::Nullable:
3934
438k
    if (!Ident__Nullable)
3935
433
      Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3936
438k
    return Ident__Nullable;
3937
3938
0
  case NullabilityKind::NullableResult:
3939
0
    if (!Ident__Nullable_result)
3940
0
      Ident__Nullable_result = PP.getIdentifierInfo("_Nullable_result");
3941
0
    return Ident__Nullable_result;
3942
3943
14.8k
  case NullabilityKind::Unspecified:
3944
14.8k
    if (!Ident__Null_unspecified)
3945
228
      Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3946
14.8k
    return Ident__Null_unspecified;
3947
2.50M
  }
3948
2.50M
  
llvm_unreachable0
("Unknown nullability kind.");
3949
2.50M
}
3950
3951
/// Retrieve the identifier "NSError".
3952
1.09M
IdentifierInfo *Sema::getNSErrorIdent() {
3953
1.09M
  if (!Ident_NSError)
3954
2.59k
    Ident_NSError = PP.getIdentifierInfo("NSError");
3955
3956
1.09M
  return Ident_NSError;
3957
1.09M
}
3958
3959
/// Check whether there is a nullability attribute of any kind in the given
3960
/// attribute list.
3961
11.6M
static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
3962
11.6M
  for (const ParsedAttr &AL : attrs) {
3963
861k
    if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
3964
861k
        
AL.getKind() == ParsedAttr::AT_TypeNullable794k
||
3965
861k
        
AL.getKind() == ParsedAttr::AT_TypeNullableResult357k
||
3966
861k
        
AL.getKind() == ParsedAttr::AT_TypeNullUnspecified357k
)
3967
526k
      return true;
3968
861k
  }
3969
3970
11.0M
  return false;
3971
11.6M
}
3972
3973
namespace {
3974
  /// Describes the kind of a pointer a declarator describes.
3975
  enum class PointerDeclaratorKind {
3976
    // Not a pointer.
3977
    NonPointer,
3978
    // Single-level pointer.
3979
    SingleLevelPointer,
3980
    // Multi-level pointer (of any pointer kind).
3981
    MultiLevelPointer,
3982
    // CFFooRef*
3983
    MaybePointerToCFRef,
3984
    // CFErrorRef*
3985
    CFErrorRefPointer,
3986
    // NSError**
3987
    NSErrorPointerPointer,
3988
  };
3989
3990
  /// Describes a declarator chunk wrapping a pointer that marks inference as
3991
  /// unexpected.
3992
  // These values must be kept in sync with diagnostics.
3993
  enum class PointerWrappingDeclaratorKind {
3994
    /// Pointer is top-level.
3995
    None = -1,
3996
    /// Pointer is an array element.
3997
    Array = 0,
3998
    /// Pointer is the referent type of a C++ reference.
3999
    Reference = 1
4000
  };
4001
} // end anonymous namespace
4002
4003
/// Classify the given declarator, whose type-specified is \c type, based on
4004
/// what kind of pointer it refers to.
4005
///
4006
/// This is used to determine the default nullability.
4007
static PointerDeclaratorKind
4008
classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator,
4009
124M
                          PointerWrappingDeclaratorKind &wrappingKind) {
4010
124M
  unsigned numNormalPointers = 0;
4011
4012
  // For any dependent type, we consider it a non-pointer.
4013
124M
  if (type->isDependentType())
4014
2.37M
    return PointerDeclaratorKind::NonPointer;
4015
4016
  // Look through the declarator chunks to identify pointers.
4017
161M
  
for (unsigned i = 0, n = declarator.getNumTypeObjects(); 122M
i != n;
++i38.9M
) {
4018
38.9M
    DeclaratorChunk &chunk = declarator.getTypeObject(i);
4019
38.9M
    switch (chunk.Kind) {
4020
235k
    case DeclaratorChunk::Array:
4021
235k
      if (numNormalPointers == 0)
4022
235k
        wrappingKind = PointerWrappingDeclaratorKind::Array;
4023
235k
      break;
4024
4025
30.6M
    case DeclaratorChunk::Function:
4026
30.6M
    case DeclaratorChunk::Pipe:
4027
30.6M
      break;
4028
4029
47.7k
    case DeclaratorChunk::BlockPointer:
4030
49.4k
    case DeclaratorChunk::MemberPointer:
4031
49.4k
      return numNormalPointers > 0 ? 
PointerDeclaratorKind::MultiLevelPointer58
4032
49.4k
                                   : 
PointerDeclaratorKind::SingleLevelPointer49.4k
;
4033
4034
116k
    case DeclaratorChunk::Paren:
4035
116k
      break;
4036
4037
218k
    case DeclaratorChunk::Reference:
4038
218k
      if (numNormalPointers == 0)
4039
218k
        wrappingKind = PointerWrappingDeclaratorKind::Reference;
4040
218k
      break;
4041
4042
7.69M
    case DeclaratorChunk::Pointer:
4043
7.69M
      ++numNormalPointers;
4044
7.69M
      if (numNormalPointers > 2)
4045
295
        return PointerDeclaratorKind::MultiLevelPointer;
4046
7.69M
      break;
4047
38.9M
    }
4048
38.9M
  }
4049
4050
  // Then, dig into the type specifier itself.
4051
122M
  unsigned numTypeSpecifierPointers = 0;
4052
124M
  do {
4053
    // Decompose normal pointers.
4054
124M
    if (auto ptrType = type->getAs<PointerType>()) {
4055
2.30M
      ++numNormalPointers;
4056
4057
2.30M
      if (numNormalPointers > 2)
4058
4.78k
        return PointerDeclaratorKind::MultiLevelPointer;
4059
4060
2.30M
      type = ptrType->getPointeeType();
4061
2.30M
      ++numTypeSpecifierPointers;
4062
2.30M
      continue;
4063
2.30M
    }
4064
4065
    // Decompose block pointers.
4066
122M
    if (type->getAs<BlockPointerType>()) {
4067
22.2k
      return numNormalPointers > 0 ? 
PointerDeclaratorKind::MultiLevelPointer13
4068
22.2k
                                   : 
PointerDeclaratorKind::SingleLevelPointer22.2k
;
4069
22.2k
    }
4070
4071
    // Decompose member pointers.
4072
122M
    if (type->getAs<MemberPointerType>()) {
4073
872
      return numNormalPointers > 0 ? 
PointerDeclaratorKind::MultiLevelPointer9
4074
872
                                   : 
PointerDeclaratorKind::SingleLevelPointer863
;
4075
872
    }
4076
4077
    // Look at Objective-C object pointers.
4078
122M
    if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
4079
490k
      ++numNormalPointers;
4080
490k
      ++numTypeSpecifierPointers;
4081
4082
      // If this is NSError**, report that.
4083
490k
      if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
4084
206k
        if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
4085
206k
            
numNormalPointers == 22
&&
numTypeSpecifierPointers < 22
) {
4086
1
          return PointerDeclaratorKind::NSErrorPointerPointer;
4087
1
        }
4088
206k
      }
4089
4090
490k
      break;
4091
490k
    }
4092
4093
    // Look at Objective-C class types.
4094
121M
    if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
4095
880k
      if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
4096
45.1k
        if (numNormalPointers == 2 && 
numTypeSpecifierPointers < 230.0k
)
4097
30.0k
          return PointerDeclaratorKind::NSErrorPointerPointer;
4098
45.1k
      }
4099
4100
850k
      break;
4101
880k
    }
4102
4103
    // If at this point we haven't seen a pointer, we won't see one.
4104
120M
    if (numNormalPointers == 0)
4105
112M
      return PointerDeclaratorKind::NonPointer;
4106
4107
8.80M
    if (auto recordType = type->getAs<RecordType>()) {
4108
2.52M
      RecordDecl *recordDecl = recordType->getDecl();
4109
4110
      // If this is CFErrorRef*, report it as such.
4111
2.52M
      if (numNormalPointers == 2 && 
numTypeSpecifierPointers < 2135k
&&
4112
2.52M
          
S.isCFError(recordDecl)128k
) {
4113
18.2k
        return PointerDeclaratorKind::CFErrorRefPointer;
4114
18.2k
      }
4115
2.50M
      break;
4116
2.52M
    }
4117
4118
6.28M
    break;
4119
8.80M
  } while (
true2.30M
);
4120
4121
10.1M
  switch (numNormalPointers) {
4122
42
  case 0:
4123
42
    return PointerDeclaratorKind::NonPointer;
4124
4125
9.88M
  case 1:
4126
9.88M
    return PointerDeclaratorKind::SingleLevelPointer;
4127
4128
247k
  case 2:
4129
247k
    return PointerDeclaratorKind::MaybePointerToCFRef;
4130
4131
11
  default:
4132
11
    return PointerDeclaratorKind::MultiLevelPointer;
4133
10.1M
  }
4134
10.1M
}
4135
4136
128k
bool Sema::isCFError(RecordDecl *RD) {
4137
  // If we already know about CFError, test it directly.
4138
128k
  if (CFError)
4139
119k
    return CFError == RD;
4140
4141
  // Check whether this is CFError, which we identify based on its bridge to
4142
  // NSError. CFErrorRef used to be declared with "objc_bridge" but is now
4143
  // declared with "objc_bridge_mutable", so look for either one of the two
4144
  // attributes.
4145
9.15k
  if (RD->getTagKind() == TTK_Struct) {
4146
9.10k
    IdentifierInfo *bridgedType = nullptr;
4147
9.10k
    if (auto bridgeAttr = RD->getAttr<ObjCBridgeAttr>())
4148
1.42k
      bridgedType = bridgeAttr->getBridgedType();
4149
7.67k
    else if (auto bridgeAttr = RD->getAttr<ObjCBridgeMutableAttr>())
4150
366
      bridgedType = bridgeAttr->getBridgedType();
4151
4152
9.10k
    if (bridgedType == getNSErrorIdent()) {
4153
254
      CFError = RD;
4154
254
      return true;
4155
254
    }
4156
9.10k
  }
4157
4158
8.89k
  return false;
4159
9.15k
}
4160
4161
static FileID getNullabilityCompletenessCheckFileID(Sema &S,
4162
14.6M
                                                    SourceLocation loc) {
4163
  // If we're anywhere in a function, method, or closure context, don't perform
4164
  // completeness checks.
4165
19.1M
  for (DeclContext *ctx = S.CurContext; ctx; 
ctx = ctx->getParent()4.47M
) {
4166
19.1M
    if (ctx->isFunctionOrMethod())
4167
30.1k
      return FileID();
4168
4169
19.0M
    if (ctx->isFileContext())
4170
14.5M
      break;
4171
19.0M
  }
4172
4173
  // We only care about the expansion location.
4174
14.5M
  loc = S.SourceMgr.getExpansionLoc(loc);
4175
14.5M
  FileID file = S.SourceMgr.getFileID(loc);
4176
14.5M
  if (file.isInvalid())
4177
519
    return FileID();
4178
4179
  // Retrieve file information.
4180
14.5M
  bool invalid = false;
4181
14.5M
  const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
4182
14.5M
  if (invalid || !sloc.isFile())
4183
0
    return FileID();
4184
4185
  // We don't want to perform completeness checks on the main file or in
4186
  // system headers.
4187
14.5M
  const SrcMgr::FileInfo &fileInfo = sloc.getFile();
4188
14.5M
  if (fileInfo.getIncludeLoc().isInvalid())
4189
208k
    return FileID();
4190
14.3M
  if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
4191
14.3M
      
S.Diags.getSuppressSystemWarnings()14.3M
) {
4192
14.3M
    return FileID();
4193
14.3M
  }
4194
4195
37.1k
  return file;
4196
14.3M
}
4197
4198
/// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
4199
/// taking into account whitespace before and after.
4200
template <typename DiagBuilderT>
4201
static void fixItNullability(Sema &S, DiagBuilderT &Diag,
4202
                             SourceLocation PointerLoc,
4203
897
                             NullabilityKind Nullability) {
4204
897
  assert(PointerLoc.isValid());
4205
897
  if (PointerLoc.isMacroID())
4206
2
    return;
4207
4208
895
  SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
4209
895
  if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
4210
0
    return;
4211
4212
895
  const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
4213
895
  if (!NextChar)
4214
0
    return;
4215
4216
895
  SmallString<32> InsertionTextBuf{" "};
4217
895
  InsertionTextBuf += getNullabilitySpelling(Nullability);
4218
895
  InsertionTextBuf += " ";
4219
895
  StringRef InsertionText = InsertionTextBuf.str();
4220
4221
895
  if (isWhitespace(*NextChar)) {
4222
151
    InsertionText = InsertionText.drop_back();
4223
744
  } else if (NextChar[-1] == '[') {
4224
152
    if (NextChar[0] == ']')
4225
120
      InsertionText = InsertionText.drop_back().drop_front();
4226
32
    else
4227
32
      InsertionText = InsertionText.drop_front();
4228
592
  } else if (!isIdentifierBody(NextChar[0], /*allow dollar*/true) &&
4229
592
             
!isIdentifierBody(NextChar[-1], /*allow dollar*/true)428
) {
4230
188
    InsertionText = InsertionText.drop_back().drop_front();
4231
188
  }
4232
4233
895
  Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
4234
895
}
4235
4236
static void emitNullabilityConsistencyWarning(Sema &S,
4237
                                              SimplePointerKind PointerKind,
4238
                                              SourceLocation PointerLoc,
4239
429
                                              SourceLocation PointerEndLoc) {
4240
429
  assert(PointerLoc.isValid());
4241
4242
429
  if (PointerKind == SimplePointerKind::Array) {
4243
82
    S.Diag(PointerLoc, diag::warn_nullability_missing_array);
4244
347
  } else {
4245
347
    S.Diag(PointerLoc, diag::warn_nullability_missing)
4246
347
      << static_cast<unsigned>(PointerKind);
4247
347
  }
4248
4249
429
  auto FixItLoc = PointerEndLoc.isValid() ? 
PointerEndLoc194
:
PointerLoc235
;
4250
429
  if (FixItLoc.isMacroID())
4251
6
    return;
4252
4253
846
  
auto addFixIt = [&](NullabilityKind Nullability) 423
{
4254
846
    auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
4255
846
    Diag << static_cast<unsigned>(Nullability);
4256
846
    Diag << static_cast<unsigned>(PointerKind);
4257
846
    fixItNullability(S, Diag, FixItLoc, Nullability);
4258
846
  };
4259
423
  addFixIt(NullabilityKind::Nullable);
4260
423
  addFixIt(NullabilityKind::NonNull);
4261
423
}
4262
4263
/// Complains about missing nullability if the file containing \p pointerLoc
4264
/// has other uses of nullability (either the keywords or the \c assume_nonnull
4265
/// pragma).
4266
///
4267
/// If the file has \e not seen other uses of nullability, this particular
4268
/// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
4269
static void
4270
checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
4271
                            SourceLocation pointerLoc,
4272
7.69M
                            SourceLocation pointerEndLoc = SourceLocation()) {
4273
  // Determine which file we're performing consistency checking for.
4274
7.69M
  FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
4275
7.69M
  if (file.isInvalid())
4276
7.65M
    return;
4277
4278
  // If we haven't seen any type nullability in this file, we won't warn now
4279
  // about anything.
4280
36.1k
  FileNullability &fileNullability = S.NullabilityMap[file];
4281
36.1k
  if (!fileNullability.SawTypeNullability) {
4282
    // If this is the first pointer declarator in the file, and the appropriate
4283
    // warning is on, record it in case we need to diagnose it retroactively.
4284
35.7k
    diag::kind diagKind;
4285
35.7k
    if (pointerKind == SimplePointerKind::Array)
4286
419
      diagKind = diag::warn_nullability_missing_array;
4287
35.3k
    else
4288
35.3k
      diagKind = diag::warn_nullability_missing;
4289
4290
35.7k
    if (fileNullability.PointerLoc.isInvalid() &&
4291
35.7k
        
!S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)18.5k
) {
4292
2.81k
      fileNullability.PointerLoc = pointerLoc;
4293
2.81k
      fileNullability.PointerEndLoc = pointerEndLoc;
4294
2.81k
      fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
4295
2.81k
    }
4296
4297
35.7k
    return;
4298
35.7k
  }
4299
4300
  // Complain about missing nullability.
4301
411
  emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
4302
411
}
4303
4304
/// Marks that a nullability feature has been used in the file containing
4305
/// \p loc.
4306
///
4307
/// If this file already had pointer types in it that were missing nullability,
4308
/// the first such instance is retroactively diagnosed.
4309
///
4310
/// \sa checkNullabilityConsistency
4311
6.93M
static void recordNullabilitySeen(Sema &S, SourceLocation loc) {
4312
6.93M
  FileID file = getNullabilityCompletenessCheckFileID(S, loc);
4313
6.93M
  if (file.isInvalid())
4314
6.93M
    return;
4315
4316
951
  FileNullability &fileNullability = S.NullabilityMap[file];
4317
951
  if (fileNullability.SawTypeNullability)
4318
905
    return;
4319
46
  fileNullability.SawTypeNullability = true;
4320
4321
  // If we haven't seen any type nullability before, now we have. Retroactively
4322
  // diagnose the first unannotated pointer, if there was one.
4323
46
  if (fileNullability.PointerLoc.isInvalid())
4324
28
    return;
4325
4326
18
  auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
4327
18
  emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc,
4328
18
                                    fileNullability.PointerEndLoc);
4329
18
}
4330
4331
/// Returns true if any of the declarator chunks before \p endIndex include a
4332
/// level of indirection: array, pointer, reference, or pointer-to-member.
4333
///
4334
/// Because declarator chunks are stored in outer-to-inner order, testing
4335
/// every chunk before \p endIndex is testing all chunks that embed the current
4336
/// chunk as part of their type.
4337
///
4338
/// It is legal to pass the result of Declarator::getNumTypeObjects() as the
4339
/// end index, in which case all chunks are tested.
4340
1.58M
static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
4341
1.58M
  unsigned i = endIndex;
4342
1.59M
  while (i != 0) {
4343
    // Walk outwards along the declarator chunks.
4344
98.4k
    --i;
4345
98.4k
    const DeclaratorChunk &DC = D.getTypeObject(i);
4346
98.4k
    switch (DC.Kind) {
4347
4.91k
    case DeclaratorChunk::Paren:
4348
4.91k
      break;
4349
5.02k
    case DeclaratorChunk::Array:
4350
87.5k
    case DeclaratorChunk::Pointer:
4351
89.9k
    case DeclaratorChunk::Reference:
4352
90.0k
    case DeclaratorChunk::MemberPointer:
4353
90.0k
      return true;
4354
2.21k
    case DeclaratorChunk::Function:
4355
3.51k
    case DeclaratorChunk::BlockPointer:
4356
3.51k
    case DeclaratorChunk::Pipe:
4357
      // These are invalid anyway, so just ignore.
4358
3.51k
      break;
4359
98.4k
    }
4360
98.4k
  }
4361
1.49M
  return false;
4362
1.58M
}
4363
4364
85
static bool IsNoDerefableChunk(DeclaratorChunk Chunk) {
4365
85
  return (Chunk.Kind == DeclaratorChunk::Pointer ||
4366
85
          
Chunk.Kind == DeclaratorChunk::Array14
);
4367
85
}
4368
4369
template<typename AttrT>
4370
3.17M
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
3.17M
  AL.setUsedAsTypeAttr();
4372
3.17M
  return ::new (Ctx) AttrT(Ctx, AL);
4373
3.17M
}
SemaType.cpp:clang::ObjCInertUnsafeUnretainedAttr* createSimpleAttr<clang::ObjCInertUnsafeUnretainedAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4370
2.21k
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
2.21k
  AL.setUsedAsTypeAttr();
4372
2.21k
  return ::new (Ctx) AttrT(Ctx, AL);
4373
2.21k
}
SemaType.cpp:clang::ArmMveStrictPolymorphismAttr* createSimpleAttr<clang::ArmMveStrictPolymorphismAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4370
1.57k
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
1.57k
  AL.setUsedAsTypeAttr();
4372
1.57k
  return ::new (Ctx) AttrT(Ctx, AL);
4373
1.57k
}
SemaType.cpp:clang::LifetimeBoundAttr* createSimpleAttr<clang::LifetimeBoundAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4370
7
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
7
  AL.setUsedAsTypeAttr();
4372
7
  return ::new (Ctx) AttrT(Ctx, AL);
4373
7
}
SemaType.cpp:clang::NoDerefAttr* createSimpleAttr<clang::NoDerefAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4370
98
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
98
  AL.setUsedAsTypeAttr();
4372
98
  return ::new (Ctx) AttrT(Ctx, AL);
4373
98
}
SemaType.cpp:clang::Ptr32Attr* createSimpleAttr<clang::Ptr32Attr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4370
39
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
39
  AL.setUsedAsTypeAttr();
4372
39
  return ::new (Ctx) AttrT(Ctx, AL);
4373
39
}
SemaType.cpp:clang::Ptr64Attr* createSimpleAttr<clang::Ptr64Attr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4370
20
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
20
  AL.setUsedAsTypeAttr();
4372
20
  return ::new (Ctx) AttrT(Ctx, AL);
4373
20
}
SemaType.cpp:clang::SPtrAttr* createSimpleAttr<clang::SPtrAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4370
18
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
18
  AL.setUsedAsTypeAttr();
4372
18
  return ::new (Ctx) AttrT(Ctx, AL);
4373
18
}
SemaType.cpp:clang::UPtrAttr* createSimpleAttr<clang::UPtrAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4370
12
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
12
  AL.setUsedAsTypeAttr();
4372
12
  return ::new (Ctx) AttrT(Ctx, AL);
4373
12
}
SemaType.cpp:clang::TypeNonNullAttr* createSimpleAttr<clang::TypeNonNullAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4370
2.15M
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
2.15M
  AL.setUsedAsTypeAttr();
4372
2.15M
  return ::new (Ctx) AttrT(Ctx, AL);
4373
2.15M
}
SemaType.cpp:clang::TypeNullableAttr* createSimpleAttr<clang::TypeNullableAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4370
959k
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
959k
  AL.setUsedAsTypeAttr();
4372
959k
  return ::new (Ctx) AttrT(Ctx, AL);
4373
959k
}
SemaType.cpp:clang::TypeNullableResultAttr* createSimpleAttr<clang::TypeNullableResultAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4370
18
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
18
  AL.setUsedAsTypeAttr();
4372
18
  return ::new (Ctx) AttrT(Ctx, AL);
4373
18
}
SemaType.cpp:clang::TypeNullUnspecifiedAttr* createSimpleAttr<clang::TypeNullUnspecifiedAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4370
43.3k
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
43.3k
  AL.setUsedAsTypeAttr();
4372
43.3k
  return ::new (Ctx) AttrT(Ctx, AL);
4373
43.3k
}
SemaType.cpp:clang::ObjCKindOfAttr* createSimpleAttr<clang::ObjCKindOfAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4370
1.28k
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
1.28k
  AL.setUsedAsTypeAttr();
4372
1.28k
  return ::new (Ctx) AttrT(Ctx, AL);
4373
1.28k
}
SemaType.cpp:clang::NSReturnsRetainedAttr* createSimpleAttr<clang::NSReturnsRetainedAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4370
12.1k
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
12.1k
  AL.setUsedAsTypeAttr();
4372
12.1k
  return ::new (Ctx) AttrT(Ctx, AL);
4373
12.1k
}
SemaType.cpp:clang::CDeclAttr* createSimpleAttr<clang::CDeclAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4370
401
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
401
  AL.setUsedAsTypeAttr();
4372
401
  return ::new (Ctx) AttrT(Ctx, AL);
4373
401
}
SemaType.cpp:clang::FastCallAttr* createSimpleAttr<clang::FastCallAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4370
232
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
232
  AL.setUsedAsTypeAttr();
4372
232
  return ::new (Ctx) AttrT(Ctx, AL);
4373
232
}
SemaType.cpp:clang::StdCallAttr* createSimpleAttr<clang::StdCallAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4370
277
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
277
  AL.setUsedAsTypeAttr();
4372
277
  return ::new (Ctx) AttrT(Ctx, AL);
4373
277
}
SemaType.cpp:clang::ThisCallAttr* createSimpleAttr<clang::ThisCallAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4370
78
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
78
  AL.setUsedAsTypeAttr();
4372
78
  return ::new (Ctx) AttrT(Ctx, AL);
4373
78
}
SemaType.cpp:clang::RegCallAttr* createSimpleAttr<clang::RegCallAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4370
124
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
124
  AL.setUsedAsTypeAttr();
4372
124
  return ::new (Ctx) AttrT(Ctx, AL);
4373
124
}
SemaType.cpp:clang::PascalAttr* createSimpleAttr<clang::PascalAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4370
22
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
22
  AL.setUsedAsTypeAttr();
4372
22
  return ::new (Ctx) AttrT(Ctx, AL);
4373
22
}
SemaType.cpp:clang::SwiftCallAttr* createSimpleAttr<clang::SwiftCallAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4370
1.20k
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
1.20k
  AL.setUsedAsTypeAttr();
4372
1.20k
  return ::new (Ctx) AttrT(Ctx, AL);
4373
1.20k
}
SemaType.cpp:clang::VectorCallAttr* createSimpleAttr<clang::VectorCallAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4370
196
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
196
  AL.setUsedAsTypeAttr();
4372
196
  return ::new (Ctx) AttrT(Ctx, AL);
4373
196
}
SemaType.cpp:clang::AArch64VectorPcsAttr* createSimpleAttr<clang::AArch64VectorPcsAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4370
12
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
12
  AL.setUsedAsTypeAttr();
4372
12
  return ::new (Ctx) AttrT(Ctx, AL);
4373
12
}
SemaType.cpp:clang::IntelOclBiccAttr* createSimpleAttr<clang::IntelOclBiccAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4370
8
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
8
  AL.setUsedAsTypeAttr();
4372
8
  return ::new (Ctx) AttrT(Ctx, AL);
4373
8
}
SemaType.cpp:clang::MSABIAttr* createSimpleAttr<clang::MSABIAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4370
47
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
47
  AL.setUsedAsTypeAttr();
4372
47
  return ::new (Ctx) AttrT(Ctx, AL);
4373
47
}
SemaType.cpp:clang::SysVABIAttr* createSimpleAttr<clang::SysVABIAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4370
36
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
36
  AL.setUsedAsTypeAttr();
4372
36
  return ::new (Ctx) AttrT(Ctx, AL);
4373
36
}
SemaType.cpp:clang::PreserveMostAttr* createSimpleAttr<clang::PreserveMostAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4370
36
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
36
  AL.setUsedAsTypeAttr();
4372
36
  return ::new (Ctx) AttrT(Ctx, AL);
4373
36
}
SemaType.cpp:clang::PreserveAllAttr* createSimpleAttr<clang::PreserveAllAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4370
26
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4371
26
  AL.setUsedAsTypeAttr();
4372
26
  return ::new (Ctx) AttrT(Ctx, AL);
4373
26
}
4374
4375
static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr,
4376
3.15M
                                   NullabilityKind NK) {
4377
3.15M
  switch (NK) {
4378
2.15M
  case NullabilityKind::NonNull:
4379
2.15M
    return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr);
4380
4381
959k
  case NullabilityKind::Nullable:
4382
959k
    return createSimpleAttr<TypeNullableAttr>(Ctx, Attr);
4383
4384
18
  case NullabilityKind::NullableResult:
4385
18
    return createSimpleAttr<TypeNullableResultAttr>(Ctx, Attr);
4386
4387
43.3k
  case NullabilityKind::Unspecified:
4388
43.3k
    return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr);
4389
3.15M
  }
4390
3.15M
  
llvm_unreachable0
("unknown NullabilityKind");
4391
3.15M
}
4392
4393
// Diagnose whether this is a case with the multiple addr spaces.
4394
// Returns true if this is an invalid case.
4395
// ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
4396
// by qualifiers for two or more different address spaces."
4397
static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld,
4398
                                                LangAS ASNew,
4399
28.5k
                                                SourceLocation AttrLoc) {
4400
28.5k
  if (ASOld != LangAS::Default) {
4401
48
    if (ASOld != ASNew) {
4402
32
      S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
4403
32
      return true;
4404
32
    }
4405
    // Emit a warning if they are identical; it's likely unintended.
4406
16
    S.Diag(AttrLoc,
4407
16
           diag::warn_attribute_address_multiple_identical_qualifiers);
4408
16
  }
4409
28.5k
  return false;
4410
28.5k
}
4411
4412
static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
4413
                                                QualType declSpecType,
4414
137M
                                                TypeSourceInfo *TInfo) {
4415
  // The TypeSourceInfo that this function returns will not be a null type.
4416
  // If there is an error, this function will fill in a dummy type as fallback.
4417
137M
  QualType T = declSpecType;
4418
137M
  Declarator &D = state.getDeclarator();
4419
137M
  Sema &S = state.getSema();
4420
137M
  ASTContext &Context = S.Context;
4421
137M
  const LangOptions &LangOpts = S.getLangOpts();
4422
4423
  // The name we're declaring, if any.
4424
137M
  DeclarationName Name;
4425
137M
  if (D.getIdentifier())
4426
62.6M
    Name = D.getIdentifier();
4427
4428
  // Does this declaration declare a typedef-name?
4429
137M
  bool IsTypedefName =
4430
137M
      D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
4431
137M
      
D.getContext() == DeclaratorContext::AliasDecl135M
||
4432
137M
      
D.getContext() == DeclaratorContext::AliasTemplate135M
;
4433
4434
  // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
4435
137M
  bool IsQualifiedFunction = T->isFunctionProtoType() &&
4436
137M
      
(1.87k
!T->castAs<FunctionProtoType>()->getMethodQuals().empty()1.87k
||
4437
1.87k
       
T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None1.83k
);
4438
4439
  // If T is 'decltype(auto)', the only declarators we can have are parens
4440
  // and at most one function declarator if this is a function declaration.
4441
  // If T is a deduced class template specialization type, we can have no
4442
  // declarator chunks at all.
4443
137M
  if (auto *DT = T->getAs<DeducedType>()) {
4444
35.5k
    const AutoType *AT = T->getAs<AutoType>();
4445
35.5k
    bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
4446
35.5k
    if ((AT && 
AT->isDecltypeAuto()34.7k
) ||
IsClassTemplateDeduction35.1k
) {
4447
1.50k
      for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; 
++I280
) {
4448
329
        unsigned Index = E - I - 1;
4449
329
        DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
4450
329
        unsigned DiagId = IsClassTemplateDeduction
4451
329
                              ? 
diag::err_deduced_class_template_compound_type14
4452
329
                              : 
diag::err_decltype_auto_compound_type315
;
4453
329
        unsigned DiagKind = 0;
4454
329
        switch (DeclChunk.Kind) {
4455
38
        case DeclaratorChunk::Paren:
4456
          // FIXME: Rejecting this is a little silly.
4457
38
          if (IsClassTemplateDeduction) {
4458
2
            DiagKind = 4;
4459
2
            break;
4460
2
          }
4461
36
          continue;
4462
255
        case DeclaratorChunk::Function: {
4463
255
          if (IsClassTemplateDeduction) {
4464
2
            DiagKind = 3;
4465
2
            break;
4466
2
          }
4467
253
          unsigned FnIndex;
4468
253
          if (D.isFunctionDeclarationContext() &&
4469
253
              D.isFunctionDeclarator(FnIndex) && 
FnIndex == Index247
)
4470
244
            continue;
4471
9
          DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
4472
9
          break;
4473
253
        }
4474
16
        case DeclaratorChunk::Pointer:
4475
16
        case DeclaratorChunk::BlockPointer:
4476
18
        case DeclaratorChunk::MemberPointer:
4477
18
          DiagKind = 0;
4478
18
          break;
4479
10
        case DeclaratorChunk::Reference:
4480
10
          DiagKind = 1;
4481
10
          break;
4482
8
        case DeclaratorChunk::Array:
4483
8
          DiagKind = 2;
4484
8
          break;
4485
0
        case DeclaratorChunk::Pipe:
4486
0
          break;
4487
329
        }
4488
4489
49
        S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
4490
49
        D.setInvalidType(true);
4491
49
        break;
4492
329
      }
4493
1.22k
    }
4494
35.5k
  }
4495
4496
  // Determine whether we should infer _Nonnull on pointer types.
4497
137M
  Optional<NullabilityKind> inferNullability;
4498
137M
  bool inferNullabilityCS = false;
4499
137M
  bool inferNullabilityInnerOnly = false;
4500
137M
  bool inferNullabilityInnerOnlyComplete = false;
4501
4502
  // Are we in an assume-nonnull region?
4503
137M
  bool inAssumeNonNullRegion = false;
4504
137M
  SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4505
137M
  if (assumeNonNullLoc.isValid()) {
4506
4.94M
    inAssumeNonNullRegion = true;
4507
4.94M
    recordNullabilitySeen(S, assumeNonNullLoc);
4508
4.94M
  }
4509
4510
  // Whether to complain about missing nullability specifiers or not.
4511
137M
  enum {
4512
    /// Never complain.
4513
137M
    CAMN_No,
4514
    /// Complain on the inner pointers (but not the outermost
4515
    /// pointer).
4516
137M
    CAMN_InnerPointers,
4517
    /// Complain about any pointers that don't have nullability
4518
    /// specified or inferred.
4519
137M
    CAMN_Yes
4520
137M
  } complainAboutMissingNullability = CAMN_No;
4521
137M
  unsigned NumPointersRemaining = 0;
4522
137M
  auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4523
4524
137M
  if (IsTypedefName) {
4525
    // For typedefs, we do not infer any nullability (the default),
4526
    // and we only complain about missing nullability specifiers on
4527
    // inner pointers.
4528
2.31M
    complainAboutMissingNullability = CAMN_InnerPointers;
4529
4530
2.31M
    if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
4531
2.31M
        
!T->getNullability(S.Context)58.3k
) {
4532
      // Note that we allow but don't require nullability on dependent types.
4533
56.5k
      ++NumPointersRemaining;
4534
56.5k
    }
4535
4536
2.85M
    for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; 
++i543k
) {
4537
543k
      DeclaratorChunk &chunk = D.getTypeObject(i);
4538
543k
      switch (chunk.Kind) {
4539
17.8k
      case DeclaratorChunk::Array:
4540
114k
      case DeclaratorChunk::Function:
4541
114k
      case DeclaratorChunk::Pipe:
4542
114k
        break;
4543
4544
10.4k
      case DeclaratorChunk::BlockPointer:
4545
10.6k
      case DeclaratorChunk::MemberPointer:
4546
10.6k
        ++NumPointersRemaining;
4547
10.6k
        break;
4548
4549
95.0k
      case DeclaratorChunk::Paren:
4550
120k
      case DeclaratorChunk::Reference:
4551
120k
        continue;
4552
4553
298k
      case DeclaratorChunk::Pointer:
4554
298k
        ++NumPointersRemaining;
4555
298k
        continue;
4556
543k
      }
4557
543k
    }
4558
135M
  } else {
4559
135M
    bool isFunctionOrMethod = false;
4560
135M
    switch (auto context = state.getDeclarator().getContext()) {
4561
955k
    case DeclaratorContext::ObjCParameter:
4562
1.60M
    case DeclaratorContext::ObjCResult:
4563
89.1M
    case DeclaratorContext::Prototype:
4564
89.1M
    case DeclaratorContext::TrailingReturn:
4565
89.1M
    case DeclaratorContext::TrailingReturnVar:
4566
89.1M
      isFunctionOrMethod = true;
4567
89.1M
      LLVM_FALLTHROUGH;
4568
4569
93.6M
    case DeclaratorContext::Member:
4570
93.6M
      if (state.getDeclarator().isObjCIvar() && 
!isFunctionOrMethod132k
) {
4571
132k
        complainAboutMissingNullability = CAMN_No;
4572
132k
        break;
4573
132k
      }
4574
4575
      // Weak properties are inferred to be nullable.
4576
93.4M
      if (state.getDeclarator().isObjCWeakProperty() && 
inAssumeNonNullRegion1.14k
) {
4577
1.01k
        inferNullability = NullabilityKind::Nullable;
4578
1.01k
        break;
4579
1.01k
      }
4580
4581
93.4M
      
LLVM_FALLTHROUGH93.4M
;93.4M
4582
4583
124M
    case DeclaratorContext::File:
4584
124M
    case DeclaratorContext::KNRTypeList: {
4585
124M
      complainAboutMissingNullability = CAMN_Yes;
4586
4587
      // Nullability inference depends on the type and declarator.
4588
124M
      auto wrappingKind = PointerWrappingDeclaratorKind::None;
4589
124M
      switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4590
114M
      case PointerDeclaratorKind::NonPointer:
4591
114M
      case PointerDeclaratorKind::MultiLevelPointer:
4592
        // Cannot infer nullability.
4593
114M
        break;
4594
4595
9.95M
      case PointerDeclaratorKind::SingleLevelPointer:
4596
        // Infer _Nonnull if we are in an assumes-nonnull region.
4597
9.95M
        if (inAssumeNonNullRegion) {
4598
2.81M
          complainAboutInferringWithinChunk = wrappingKind;
4599
2.81M
          inferNullability = NullabilityKind::NonNull;
4600
2.81M
          inferNullabilityCS = (context == DeclaratorContext::ObjCParameter ||
4601
2.81M
                                
context == DeclaratorContext::ObjCResult2.15M
);
4602
2.81M
        }
4603
9.95M
        break;
4604
4605
18.2k
      case PointerDeclaratorKind::CFErrorRefPointer:
4606
48.3k
      case PointerDeclaratorKind::NSErrorPointerPointer:
4607
        // Within a function or method signature, infer _Nullable at both
4608
        // levels.
4609
48.3k
        if (isFunctionOrMethod && 
inAssumeNonNullRegion48.3k
)
4610
43.2k
          inferNullability = NullabilityKind::Nullable;
4611
48.3k
        break;
4612
4613
247k
      case PointerDeclaratorKind::MaybePointerToCFRef:
4614
247k
        if (isFunctionOrMethod) {
4615
          // On pointer-to-pointer parameters marked cf_returns_retained or
4616
          // cf_returns_not_retained, if the outer pointer is explicit then
4617
          // infer the inner pointer as _Nullable.
4618
224k
          auto hasCFReturnsAttr =
4619
578k
              [](const ParsedAttributesView &AttrList) -> bool {
4620
578k
            return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
4621
578k
                   
AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained)550k
;
4622
578k
          };
4623
224k
          if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4624
202k
            if (hasCFReturnsAttr(D.getAttributes()) ||
4625
202k
                
hasCFReturnsAttr(InnermostChunk->getAttrs())200k
||
4626
202k
                
hasCFReturnsAttr(D.getDeclSpec().getAttributes())174k
) {
4627
27.4k
              inferNullability = NullabilityKind::Nullable;
4628
27.4k
              inferNullabilityInnerOnly = true;
4629
27.4k
            }
4630
202k
          }
4631
224k
        }
4632
247k
        break;
4633
124M
      }
4634
124M
      break;
4635
124M
    }
4636
4637
124M
    case DeclaratorContext::ConversionId:
4638
13.3k
      complainAboutMissingNullability = CAMN_Yes;
4639
13.3k
      break;
4640
4641
0
    case DeclaratorContext::AliasDecl:
4642
0
    case DeclaratorContext::AliasTemplate:
4643
1.07M
    case DeclaratorContext::Block:
4644
1.08M
    case DeclaratorContext::BlockLiteral:
4645
1.08M
    case DeclaratorContext::Condition:
4646
1.08M
    case DeclaratorContext::CXXCatch:
4647
1.10M
    case DeclaratorContext::CXXNew:
4648
1.22M
    case DeclaratorContext::ForInit:
4649
1.22M
    case DeclaratorContext::SelectionInit:
4650
1.23M
    case DeclaratorContext::LambdaExpr:
4651
1.23M
    case DeclaratorContext::LambdaExprParameter:
4652
1.23M
    case DeclaratorContext::ObjCCatch:
4653
1.45M
    case DeclaratorContext::TemplateParam:
4654
5.13M
    case DeclaratorContext::TemplateArg:
4655
5.23M
    case DeclaratorContext::TemplateTypeArg:
4656
10.3M
    case DeclaratorContext::TypeName:
4657
10.6M
    case DeclaratorContext::FunctionalCast:
4658
10.6M
    case DeclaratorContext::RequiresExpr:
4659
      // Don't infer in these contexts.
4660
10.6M
      break;
4661
135M
    }
4662
135M
  }
4663
4664
  // Local function that returns true if its argument looks like a va_list.
4665
137M
  auto isVaList = [&S](QualType T) -> bool {
4666
2.57M
    auto *typedefTy = T->getAs<TypedefType>();
4667
2.57M
    if (!typedefTy)
4668
76.3k
      return false;
4669
2.49M
    TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4670
2.78M
    do {
4671
2.78M
      if (typedefTy->getDecl() == vaListTypedef)
4672
4.02k
        return true;
4673
2.77M
      if (auto *name = typedefTy->getDecl()->getIdentifier())
4674
2.77M
        if (name->isStr("va_list"))
4675
20.3k
          return true;
4676
2.75M
      typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4677
2.75M
    } while (typedefTy);
4678
2.47M
    return false;
4679
2.49M
  };
4680
4681
  // Local function that checks the nullability for a given pointer declarator.
4682
  // Returns true if _Nonnull was inferred.
4683
137M
  auto inferPointerNullability =
4684
137M
      [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4685
137M
          SourceLocation pointerEndLoc,
4686
137M
          ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * {
4687
    // We've seen a pointer.
4688
11.3M
    if (NumPointersRemaining > 0)
4689
365k
      --NumPointersRemaining;
4690
4691
    // If a nullability attribute is present, there's nothing to do.
4692
11.3M
    if (hasNullabilityAttr(attrs))
4693
514k
      return nullptr;
4694
4695
    // If we're supposed to infer nullability, do so now.
4696
10.8M
    if (inferNullability && 
!inferNullabilityInnerOnlyComplete2.15M
) {
4697
2.15M
      ParsedAttr::Syntax syntax = inferNullabilityCS
4698
2.15M
                                      ? 
ParsedAttr::AS_ContextSensitiveKeyword710k
4699
2.15M
                                      : 
ParsedAttr::AS_Keyword1.44M
;
4700
2.15M
      ParsedAttr *nullabilityAttr = Pool.create(
4701
2.15M
          S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
4702
2.15M
          nullptr, SourceLocation(), nullptr, 0, syntax);
4703
4704
2.15M
      attrs.addAtEnd(nullabilityAttr);
4705
4706
2.15M
      if (inferNullabilityCS) {
4707
710k
        state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4708
710k
          ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4709
710k
      }
4710
4711
2.15M
      if (pointerLoc.isValid() &&
4712
2.15M
          complainAboutInferringWithinChunk !=
4713
2.15M
            PointerWrappingDeclaratorKind::None) {
4714
51
        auto Diag =
4715
51
            S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
4716
51
        Diag << static_cast<int>(complainAboutInferringWithinChunk);
4717
51
        fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull);
4718
51
      }
4719
4720
2.15M
      if (inferNullabilityInnerOnly)
4721
23.2k
        inferNullabilityInnerOnlyComplete = true;
4722
2.15M
      return nullabilityAttr;
4723
2.15M
    }
4724
4725
    // If we're supposed to complain about missing nullability, do so
4726
    // now if it's truly missing.
4727
8.70M
    switch (complainAboutMissingNullability) {
4728
710k
    case CAMN_No:
4729
710k
      break;
4730
4731
365k
    case CAMN_InnerPointers:
4732
365k
      if (NumPointersRemaining == 0)
4733
342k
        break;
4734
365k
      
LLVM_FALLTHROUGH22.7k
;22.7k
4735
4736
7.65M
    case CAMN_Yes:
4737
7.65M
      checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4738
8.70M
    }
4739
8.70M
    return nullptr;
4740
8.70M
  };
4741
4742
  // If the type itself could have nullability but does not, infer pointer
4743
  // nullability and perform consistency checking.
4744
137M
  if (S.CodeSynthesisContexts.empty()) {
4745
137M
    if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
4746
137M
        
!T->getNullability(S.Context)2.99M
) {
4747
2.51M
      if (isVaList(T)) {
4748
        // Record that we've seen a pointer, but do nothing else.
4749
523
        if (NumPointersRemaining > 0)
4750
122
          --NumPointersRemaining;
4751
2.51M
      } else {
4752
2.51M
        SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4753
2.51M
        if (T->isBlockPointerType())
4754
21.3k
          pointerKind = SimplePointerKind::BlockPointer;
4755
2.49M
        else if (T->isMemberPointerType())
4756
1.08k
          pointerKind = SimplePointerKind::MemberPointer;
4757
4758
2.51M
        if (auto *attr = inferPointerNullability(
4759
2.51M
                pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4760
2.51M
                D.getDeclSpec().getEndLoc(),
4761
2.51M
                D.getMutableDeclSpec().getAttributes(),
4762
2.51M
                D.getMutableDeclSpec().getAttributePool())) {
4763
1.17M
          T = state.getAttributedType(
4764
1.17M
              createNullabilityAttr(Context, *attr, *inferNullability), T, T);
4765
1.17M
        }
4766
2.51M
      }
4767
2.51M
    }
4768
4769
137M
    if (complainAboutMissingNullability == CAMN_Yes &&
4770
137M
        
T->isArrayType()124M
&&
!T->getNullability(S.Context)58.2k
&&
!isVaList(T)57.1k
&&
4771
137M
        
D.isPrototypeContext()33.2k
&&
4772
137M
        
!hasOuterPointerLikeChunk(D, D.getNumTypeObjects())20.9k
) {
4773
19.0k
      checkNullabilityConsistency(S, SimplePointerKind::Array,
4774
19.0k
                                  D.getDeclSpec().getTypeSpecTypeLoc());
4775
19.0k
    }
4776
137M
  }
4777
4778
137M
  bool ExpectNoDerefChunk =
4779
137M
      state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref);
4780
4781
  // Walk the DeclTypeInfo, building the recursive type as we go.
4782
  // DeclTypeInfos are ordered from the identifier out, which is
4783
  // opposite of what we want :).
4784
179M
  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; 
++i42.1M
) {
4785
42.1M
    unsigned chunkIndex = e - i - 1;
4786
42.1M
    state.setCurrentChunkIndex(chunkIndex);
4787
42.1M
    DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4788
42.1M
    IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4789
42.1M
    switch (DeclType.Kind) {
4790
306k
    case DeclaratorChunk::Paren:
4791
306k
      if (i == 0)
4792
442
        warnAboutRedundantParens(S, D, T);
4793
306k
      T = S.BuildParenType(T);
4794
306k
      break;
4795
60.3k
    case DeclaratorChunk::BlockPointer:
4796
      // If blocks are disabled, emit an error.
4797
60.3k
      if (!LangOpts.Blocks)
4798
6
        S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4799
4800
      // Handle pointer nullability.
4801
60.3k
      inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
4802
60.3k
                              DeclType.EndLoc, DeclType.getAttrs(),
4803
60.3k
                              state.getDeclarator().getAttributePool());
4804
4805
60.3k
      T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4806
60.3k
      if (DeclType.Cls.TypeQuals || 
LangOpts.OpenCL60.2k
) {
4807
        // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4808
        // qualified with const.
4809
89
        if (LangOpts.OpenCL)
4810
79
          DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4811
89
        T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4812
89
      }
4813
60.3k
      break;
4814
8.76M
    case DeclaratorChunk::Pointer:
4815
      // Verify that we're not building a pointer to pointer to function with
4816
      // exception specification.
4817
8.76M
      if (LangOpts.CPlusPlus && 
S.CheckDistantExceptionSpec(T)3.08M
) {
4818
7
        S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4819
7
        D.setInvalidType(true);
4820
        // Build the type anyway.
4821
7
      }
4822
4823
      // Handle pointer nullability
4824
8.76M
      inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4825
8.76M
                              DeclType.EndLoc, DeclType.getAttrs(),
4826
8.76M
                              state.getDeclarator().getAttributePool());
4827
4828
8.76M
      if (LangOpts.ObjC && 
T->getAs<ObjCObjectType>()3.00M
) {
4829
1.13M
        T = Context.getObjCObjectPointerType(T);
4830
1.13M
        if (DeclType.Ptr.TypeQuals)
4831
65.0k
          T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4832
1.13M
        break;
4833
1.13M
      }
4834
4835
      // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4836
      // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4837
      // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4838
7.62M
      if (LangOpts.OpenCL) {
4839
34.0k
        if (T->isImageType() || 
T->isSamplerT()34.0k
||
T->isPipeType()33.9k
||
4840
34.0k
            
T->isBlockPointerType()33.9k
) {
4841
12
          S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4842
12
          D.setInvalidType(true);
4843
12
        }
4844
34.0k
      }
4845
4846
7.62M
      T = S.BuildPointerType(T, DeclType.Loc, Name);
4847
7.62M
      if (DeclType.Ptr.TypeQuals)
4848
96.2k
        T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4849
7.62M
      break;
4850
1.14M
    case DeclaratorChunk::Reference: {
4851
      // Verify that we're not building a reference to pointer to function with
4852
      // exception specification.
4853
1.14M
      if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4854
0
        S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4855
0
        D.setInvalidType(true);
4856
        // Build the type anyway.
4857
0
      }
4858
1.14M
      T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
4859
4860
1.14M
      if (DeclType.Ref.HasRestrict)
4861
7
        T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
4862
1.14M
      break;
4863
8.76M
    }
4864
307k
    case DeclaratorChunk::Array: {
4865
      // Verify that we're not building an array of pointers to function with
4866
      // exception specification.
4867
307k
      if (LangOpts.CPlusPlus && 
S.CheckDistantExceptionSpec(T)137k
) {
4868
0
        S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4869
0
        D.setInvalidType(true);
4870
        // Build the type anyway.
4871
0
      }
4872
307k
      DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4873
307k
      Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
4874
307k
      ArrayType::ArraySizeModifier ASM;
4875
307k
      if (ATI.isStar)
4876
29
        ASM = ArrayType::Star;
4877
307k
      else if (ATI.hasStatic)
4878
48
        ASM = ArrayType::Static;
4879
307k
      else
4880
307k
        ASM = ArrayType::Normal;
4881
307k
      if (ASM == ArrayType::Star && 
!D.isPrototypeContext()29
) {
4882
        // FIXME: This check isn't quite right: it allows star in prototypes
4883
        // for function definitions, and disallows some edge cases detailed
4884
        // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4885
1
        S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
4886
1
        ASM = ArrayType::Normal;
4887
1
        D.setInvalidType(true);
4888
1
      }
4889
4890
      // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4891
      // shall appear only in a declaration of a function parameter with an
4892
      // array type, ...
4893
307k
      if (ASM == ArrayType::Static || 
ATI.TypeQuals307k
) {
4894
158
        if (!(D.isPrototypeContext() ||
4895
158
              
D.getContext() == DeclaratorContext::KNRTypeList7
)) {
4896
6
          S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
4897
6
              (ASM == ArrayType::Static ? 
"'static'"3
:
"type qualifier"3
);
4898
          // Remove the 'static' and the type qualifiers.
4899
6
          if (ASM == ArrayType::Static)
4900
3
            ASM = ArrayType::Normal;
4901
6
          ATI.TypeQuals = 0;
4902
6
          D.setInvalidType(true);
4903
6
        }
4904
4905
        // C99 6.7.5.2p1: ... and then only in the outermost array type
4906
        // derivation.
4907
158
        if (hasOuterPointerLikeChunk(D, chunkIndex)) {
4908
3
          S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
4909
3
            (ASM == ArrayType::Static ? 
"'static'"2
:
"type qualifier"1
);
4910
3
          if (ASM == ArrayType::Static)
4911
2
            ASM = ArrayType::Normal;
4912
3
          ATI.TypeQuals = 0;
4913
3
          D.setInvalidType(true);
4914
3
        }
4915
158
      }
4916
307k
      const AutoType *AT = T->getContainedAutoType();
4917
      // Allow arrays of auto if we are a generic lambda parameter.
4918
      // i.e. [](auto (&array)[5]) { return array[0]; }; OK
4919
307k
      if (AT && 
D.getContext() != DeclaratorContext::LambdaExprParameter8
) {
4920
        // We've already diagnosed this for decltype(auto).
4921
8
        if (!AT->isDecltypeAuto())
4922
2
          S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
4923
2
              << getPrintableNameForEntity(Name) << T;
4924
8
        T = QualType();
4925
8
        break;
4926
8
      }
4927
4928
      // Array parameters can be marked nullable as well, although it's not
4929
      // necessary if they're marked 'static'.
4930
307k
      if (complainAboutMissingNullability == CAMN_Yes &&
4931
307k
          
!hasNullabilityAttr(DeclType.getAttrs())239k
&&
4932
307k
          
ASM != ArrayType::Static226k
&&
4933
307k
          
D.isPrototypeContext()226k
&&
4934
307k
          
!hasOuterPointerLikeChunk(D, chunkIndex)28.6k
) {
4935
25.8k
        checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
4936
25.8k
      }
4937
4938
307k
      T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
4939
307k
                           SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
4940
307k
      break;
4941
307k
    }
4942
31.5M
    case DeclaratorChunk::Function: {
4943
      // If the function declarator has a prototype (i.e. it is not () and
4944
      // does not have a K&R-style identifier list), then the arguments are part
4945
      // of the type, otherwise the argument list is ().
4946
31.5M
      DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4947
31.5M
      IsQualifiedFunction =
4948
31.5M
          FTI.hasMethodTypeQualifiers() || 
FTI.hasRefQualifier()31.1M
;
4949
4950
      // Check for auto functions and trailing return type and adjust the
4951
      // return type accordingly.
4952
31.5M
      if (!D.isInvalidType()) {
4953
        // trailing-return-type is only required if we're declaring a function,
4954
        // and not, for instance, a pointer to a function.
4955
31.5M
        if (D.getDeclSpec().hasAutoTypeSpec() &&
4956
31.5M
            
!FTI.hasTrailingReturnType()17.1k
&&
chunkIndex == 01.74k
) {
4957
1.66k
          if (!S.getLangOpts().CPlusPlus14) {
4958
3
            S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4959
3
                   D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
4960
3
                       ? 
diag::err_auto_missing_trailing_return2
4961
3
                       : 
diag::err_deduced_return_type1
);
4962
3
            T = Context.IntTy;
4963
3
            D.setInvalidType(true);
4964
1.65k
          } else {
4965
1.65k
            S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4966
1.65k
                   diag::warn_cxx11_compat_deduced_return_type);
4967
1.65k
          }
4968
31.5M
        } else if (FTI.hasTrailingReturnType()) {
4969
          // T must be exactly 'auto' at this point. See CWG issue 681.
4970
16.7k
          if (isa<ParenType>(T)) {
4971
3
            S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens)
4972
3
                << T << D.getSourceRange();
4973
3
            D.setInvalidType(true);
4974
16.7k
          } else if (D.getName().getKind() ==
4975
16.7k
                     UnqualifiedIdKind::IK_DeductionGuideName) {
4976
422
            if (T != Context.DependentTy) {
4977
4
              S.Diag(D.getDeclSpec().getBeginLoc(),
4978
4
                     diag::err_deduction_guide_with_complex_decl)
4979
4
                  << D.getSourceRange();
4980
4
              D.setInvalidType(true);
4981
4
            }
4982
16.2k
          } else if (D.getContext() != DeclaratorContext::LambdaExpr &&
4983
16.2k
                     
(15.3k
T.hasQualifiers()15.3k
||
!isa<AutoType>(T)15.3k
||
4984