Coverage Report

Created: 2023-11-11 10:31

/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/Decl.h"
20
#include "clang/AST/DeclObjC.h"
21
#include "clang/AST/DeclTemplate.h"
22
#include "clang/AST/Expr.h"
23
#include "clang/AST/Type.h"
24
#include "clang/AST/TypeLoc.h"
25
#include "clang/AST/TypeLocVisitor.h"
26
#include "clang/Basic/PartialDiagnostic.h"
27
#include "clang/Basic/SourceLocation.h"
28
#include "clang/Basic/Specifiers.h"
29
#include "clang/Basic/TargetInfo.h"
30
#include "clang/Lex/Preprocessor.h"
31
#include "clang/Sema/DeclSpec.h"
32
#include "clang/Sema/DelayedDiagnostic.h"
33
#include "clang/Sema/Lookup.h"
34
#include "clang/Sema/ParsedTemplate.h"
35
#include "clang/Sema/ScopeInfo.h"
36
#include "clang/Sema/SemaInternal.h"
37
#include "clang/Sema/Template.h"
38
#include "clang/Sema/TemplateInstCallback.h"
39
#include "llvm/ADT/ArrayRef.h"
40
#include "llvm/ADT/SmallPtrSet.h"
41
#include "llvm/ADT/SmallString.h"
42
#include "llvm/ADT/StringExtras.h"
43
#include "llvm/IR/DerivedTypes.h"
44
#include "llvm/Support/Casting.h"
45
#include "llvm/Support/ErrorHandling.h"
46
#include <bitset>
47
#include <optional>
48
49
using namespace clang;
50
51
enum TypeDiagSelector {
52
  TDS_Function,
53
  TDS_Pointer,
54
  TDS_ObjCObjOrBlock
55
};
56
57
/// isOmittedBlockReturnType - Return true if this declarator is missing a
58
/// return type because this is a omitted return type on a block literal.
59
3.45k
static bool isOmittedBlockReturnType(const Declarator &D) {
60
3.45k
  if (D.getContext() != DeclaratorContext::BlockLiteral ||
61
3.45k
      
D.getDeclSpec().hasTypeSpecifier()3.07k
)
62
382
    return false;
63
64
3.07k
  if (D.getNumTypeObjects() == 0)
65
5
    return true;   // ^{ ... }
66
67
3.07k
  if (D.getNumTypeObjects() == 1 &&
68
3.07k
      
D.getTypeObject(0).Kind == DeclaratorChunk::Function3.07k
)
69
3.07k
    return true;   // ^(int X, float Y) { ... }
70
71
1
  return false;
72
3.07k
}
73
74
/// diagnoseBadTypeAttribute - Diagnoses a type attribute which
75
/// doesn't apply to the given type.
76
static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr,
77
134
                                     QualType type) {
78
134
  TypeDiagSelector WhichType;
79
134
  bool useExpansionLoc = true;
80
134
  switch (attr.getKind()) {
81
1
  case ParsedAttr::AT_ObjCGC:
82
1
    WhichType = TDS_Pointer;
83
1
    break;
84
6
  case ParsedAttr::AT_ObjCOwnership:
85
6
    WhichType = TDS_ObjCObjOrBlock;
86
6
    break;
87
127
  default:
88
    // Assume everything else was a function attribute.
89
127
    WhichType = TDS_Function;
90
127
    useExpansionLoc = false;
91
127
    break;
92
134
  }
93
94
134
  SourceLocation loc = attr.getLoc();
95
134
  StringRef name = attr.getAttrName()->getName();
96
97
  // The GC attributes are usually written with macros;  special-case them.
98
134
  IdentifierInfo *II = attr.isArgIdent(0) ? 
attr.getArgAsIdent(0)->Ident7
99
134
                                          : 
nullptr127
;
100
134
  if (useExpansionLoc && 
loc.isMacroID()7
&&
II5
) {
101
5
    if (II->isStr("strong")) {
102
2
      if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
103
3
    } else if (II->isStr("weak")) {
104
3
      if (S.findMacroSpelling(loc, "__weak")) 
name = "__weak"2
;
105
3
    }
106
5
  }
107
108
134
  S.Diag(loc, attr.isRegularKeywordAttribute()
109
134
                  ? 
diag::err_type_attribute_wrong_type98
110
134
                  : 
diag::warn_type_attribute_wrong_type36
)
111
134
      << name << WhichType << type;
112
134
}
113
114
// objc_gc applies to Objective-C pointers or, otherwise, to the
115
// smallest available pointer type (i.e. 'void*' in 'void**').
116
#define OBJC_POINTER_TYPE_ATTRS_CASELIST                                       \
117
294
  case ParsedAttr::AT_ObjCGC:                                                  \
118
8.24k
  case ParsedAttr::AT_ObjCOwnership
119
120
// Calling convention attributes.
121
#define CALLING_CONV_ATTRS_CASELIST                                            \
122
1.35M
  case ParsedAttr::AT_CDecl:                                                   \
123
1.35M
  case ParsedAttr::AT_FastCall:                                                \
124
1.35M
  case ParsedAttr::AT_StdCall:                                                 \
125
1.35M
  case ParsedAttr::AT_ThisCall:                                                \
126
1.36M
  case ParsedAttr::AT_RegCall:                                                 \
127
1.36M
  case ParsedAttr::AT_Pascal:                                                  \
128
1.36M
  case ParsedAttr::AT_SwiftCall:                                               \
129
1.36M
  case ParsedAttr::AT_SwiftAsyncCall:                                          \
130
1.36M
  case ParsedAttr::AT_VectorCall:                                              \
131
1.36M
  case ParsedAttr::AT_AArch64VectorPcs:                                        \
132
1.36M
  case ParsedAttr::AT_AArch64SVEPcs:                                           \
133
1.36M
  case ParsedAttr::AT_AMDGPUKernelCall:                                        \
134
1.36M
  case ParsedAttr::AT_MSABI:                                                   \
135
1.36M
  case ParsedAttr::AT_SysVABI:                                                 \
136
1.36M
  case ParsedAttr::AT_Pcs:                                                     \
137
1.36M
  case ParsedAttr::AT_IntelOclBicc:                                            \
138
1.36M
  case ParsedAttr::AT_PreserveMost:                                            \
139
1.36M
  case ParsedAttr::AT_PreserveAll:                                             \
140
1.36M
  case ParsedAttr::AT_M68kRTD
141
142
// Function type attributes.
143
#define FUNCTION_TYPE_ATTRS_CASELIST                                           \
144
102k
  case ParsedAttr::AT_NSReturnsRetained:                                       \
145
116k
  case ParsedAttr::AT_NoReturn:                                                \
146
116k
  case ParsedAttr::AT_Regparm:                                                 \
147
116k
  case ParsedAttr::AT_CmseNSCall:                                              \
148
117k
  case ParsedAttr::AT_ArmStreaming:                                            \
149
1.35M
  case ParsedAttr::AT_ArmStreamingCompatible:                                  \
150
1.35M
  case ParsedAttr::AT_ArmSharedZA:                                             \
151
1.35M
  case ParsedAttr::AT_ArmPreservesZA:                                          \
152
1.35M
  case ParsedAttr::AT_AnyX86NoCallerSavedRegisters:                            \
153
1.35M
  case ParsedAttr::AT_AnyX86NoCfCheck:                                         \
154
1.35M
    CALLING_CONV_ATTRS_CASELIST
155
156
// Microsoft-specific type qualifiers.
157
#define MS_TYPE_ATTRS_CASELIST                                                 \
158
67
  case ParsedAttr::AT_Ptr32:                                                   \
159
105
  case ParsedAttr::AT_Ptr64:                                                   \
160
129
  case ParsedAttr::AT_SPtr:                                                    \
161
147
  case ParsedAttr::AT_UPtr
162
163
// Nullability qualifiers.
164
#define NULLABILITY_TYPE_ATTRS_CASELIST                                        \
165
1.04M
  case ParsedAttr::AT_TypeNonNull:                                             \
166
1.99M
  case ParsedAttr::AT_TypeNullable:                                            \
167
1.99M
  case ParsedAttr::AT_TypeNullableResult:                                      \
168
2.04M
  case ParsedAttr::AT_TypeNullUnspecified
169
170
namespace {
171
  /// An object which stores processing state for the entire
172
  /// GetTypeForDeclarator process.
173
  class TypeProcessingState {
174
    Sema &sema;
175
176
    /// The declarator being processed.
177
    Declarator &declarator;
178
179
    /// The index of the declarator chunk we're currently processing.
180
    /// May be the total number of valid chunks, indicating the
181
    /// DeclSpec.
182
    unsigned chunkIndex;
183
184
    /// The original set of attributes on the DeclSpec.
185
    SmallVector<ParsedAttr *, 2> savedAttrs;
186
187
    /// A list of attributes to diagnose the uselessness of when the
188
    /// processing is complete.
189
    SmallVector<ParsedAttr *, 2> ignoredTypeAttrs;
190
191
    /// Attributes corresponding to AttributedTypeLocs that we have not yet
192
    /// populated.
193
    // FIXME: The two-phase mechanism by which we construct Types and fill
194
    // their TypeLocs makes it hard to correctly assign these. We keep the
195
    // attributes in creation order as an attempt to make them line up
196
    // properly.
197
    using TypeAttrPair = std::pair<const AttributedType*, const Attr*>;
198
    SmallVector<TypeAttrPair, 8> AttrsForTypes;
199
    bool AttrsForTypesSorted = true;
200
201
    /// MacroQualifiedTypes mapping to macro expansion locations that will be
202
    /// stored in a MacroQualifiedTypeLoc.
203
    llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros;
204
205
    /// Flag to indicate we parsed a noderef attribute. This is used for
206
    /// validating that noderef was used on a pointer or array.
207
    bool parsedNoDeref;
208
209
  public:
210
    TypeProcessingState(Sema &sema, Declarator &declarator)
211
155M
        : sema(sema), declarator(declarator),
212
155M
          chunkIndex(declarator.getNumTypeObjects()), parsedNoDeref(false) {}
213
214
664M
    Sema &getSema() const {
215
664M
      return sema;
216
664M
    }
217
218
1.15G
    Declarator &getDeclarator() const {
219
1.15G
      return declarator;
220
1.15G
    }
221
222
159M
    bool isProcessingDeclSpec() const {
223
159M
      return chunkIndex == declarator.getNumTypeObjects();
224
159M
    }
225
226
1.55M
    unsigned getCurrentChunkIndex() const {
227
1.55M
      return chunkIndex;
228
1.55M
    }
229
230
49.5M
    void setCurrentChunkIndex(unsigned idx) {
231
49.5M
      assert(idx <= declarator.getNumTypeObjects());
232
49.5M
      chunkIndex = idx;
233
49.5M
    }
234
235
159M
    ParsedAttributesView &getCurrentAttributes() const {
236
159M
      if (isProcessingDeclSpec())
237
156M
        return getMutableDeclSpec().getAttributes();
238
3.71M
      return declarator.getTypeObject(chunkIndex).getAttrs();
239
159M
    }
240
241
    /// Save the current set of attributes on the DeclSpec.
242
45.6k
    void saveDeclSpecAttrs() {
243
      // Don't try to save them multiple times.
244
45.6k
      if (!savedAttrs.empty())
245
626
        return;
246
247
45.0k
      DeclSpec &spec = getMutableDeclSpec();
248
45.0k
      llvm::append_range(savedAttrs,
249
45.0k
                         llvm::make_pointer_range(spec.getAttributes()));
250
45.0k
    }
251
252
    /// Record that we had nowhere to put the given type attribute.
253
    /// We will diagnose such attributes later.
254
28
    void addIgnoredTypeAttr(ParsedAttr &attr) {
255
28
      ignoredTypeAttrs.push_back(&attr);
256
28
    }
257
258
    /// Diagnose all the ignored type attributes, given that the
259
    /// declarator worked out to the given type.
260
155M
    void diagnoseIgnoredTypeAttrs(QualType type) const {
261
155M
      for (auto *Attr : ignoredTypeAttrs)
262
28
        diagnoseBadTypeAttribute(getSema(), *Attr, type);
263
155M
    }
264
265
    /// Get an attributed type for the given attribute, and remember the Attr
266
    /// object so that we can attach it to the AttributedTypeLoc.
267
    QualType getAttributedType(Attr *A, QualType ModifiedType,
268
3.27M
                               QualType EquivType) {
269
3.27M
      QualType T =
270
3.27M
          sema.Context.getAttributedType(A->getKind(), ModifiedType, EquivType);
271
3.27M
      AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A});
272
3.27M
      AttrsForTypesSorted = false;
273
3.27M
      return T;
274
3.27M
    }
275
276
    /// Get a BTFTagAttributed type for the btf_type_tag attribute.
277
    QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
278
67
                                     QualType WrappedType) {
279
67
      return sema.Context.getBTFTagAttributedType(BTFAttr, WrappedType);
280
67
    }
281
282
    /// Completely replace the \c auto in \p TypeWithAuto by
283
    /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if
284
    /// necessary.
285
3.28k
    QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) {
286
3.28k
      QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement);
287
3.28k
      if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) {
288
        // Attributed type still should be an attributed type after replacement.
289
1
        auto *NewAttrTy = cast<AttributedType>(T.getTypePtr());
290
1
        for (TypeAttrPair &A : AttrsForTypes) {
291
1
          if (A.first == AttrTy)
292
1
            A.first = NewAttrTy;
293
1
        }
294
1
        AttrsForTypesSorted = false;
295
1
      }
296
3.28k
      return T;
297
3.28k
    }
298
299
    /// Extract and remove the Attr* for a given attributed type.
300
3.27M
    const Attr *takeAttrForAttributedType(const AttributedType *AT) {
301
3.27M
      if (!AttrsForTypesSorted) {
302
3.13M
        llvm::stable_sort(AttrsForTypes, llvm::less_first());
303
3.13M
        AttrsForTypesSorted = true;
304
3.13M
      }
305
306
      // FIXME: This is quadratic if we have lots of reuses of the same
307
      // attributed type.
308
3.27M
      for (auto It = std::partition_point(
309
3.27M
               AttrsForTypes.begin(), AttrsForTypes.end(),
310
3.56M
               [=](const TypeAttrPair &A) { return A.first < AT; });
311
3.27M
           It != AttrsForTypes.end() && It->first == AT; 
++It0
) {
312
3.27M
        if (It->second) {
313
3.27M
          const Attr *Result = It->second;
314
3.27M
          It->second = nullptr;
315
3.27M
          return Result;
316
3.27M
        }
317
3.27M
      }
318
319
0
      llvm_unreachable("no Attr* for AttributedType*");
320
0
    }
321
322
    SourceLocation
323
238k
    getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const {
324
238k
      auto FoundLoc = LocsForMacros.find(MQT);
325
238k
      assert(FoundLoc != LocsForMacros.end() &&
326
238k
             "Unable to find macro expansion location for MacroQualifedType");
327
238k
      return FoundLoc->second;
328
238k
    }
329
330
    void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT,
331
238k
                                              SourceLocation Loc) {
332
238k
      LocsForMacros[MQT] = Loc;
333
238k
    }
334
335
672M
    void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; }
336
337
49.2M
    bool didParseNoDeref() const { return parsedNoDeref; }
338
339
155M
    ~TypeProcessingState() {
340
155M
      if (savedAttrs.empty())
341
155M
        return;
342
343
44.9k
      getMutableDeclSpec().getAttributes().clearListOnly();
344
44.9k
      for (ParsedAttr *AL : savedAttrs)
345
171k
        getMutableDeclSpec().getAttributes().addAtEnd(AL);
346
44.9k
    }
347
348
  private:
349
156M
    DeclSpec &getMutableDeclSpec() const {
350
156M
      return const_cast<DeclSpec&>(declarator.getDeclSpec());
351
156M
    }
352
  };
353
} // end anonymous namespace
354
355
static void moveAttrFromListToList(ParsedAttr &attr,
356
                                   ParsedAttributesView &fromList,
357
54.1k
                                   ParsedAttributesView &toList) {
358
54.1k
  fromList.remove(&attr);
359
54.1k
  toList.addAtEnd(&attr);
360
54.1k
}
361
362
/// The location of a type attribute.
363
enum TypeAttrLocation {
364
  /// The attribute is in the decl-specifier-seq.
365
  TAL_DeclSpec,
366
  /// The attribute is part of a DeclaratorChunk.
367
  TAL_DeclChunk,
368
  /// The attribute is immediately after the declaration's name.
369
  TAL_DeclName
370
};
371
372
static void
373
processTypeAttrs(TypeProcessingState &state, QualType &type,
374
                 TypeAttrLocation TAL, const ParsedAttributesView &attrs,
375
                 Sema::CUDAFunctionTarget CFT = Sema::CFT_HostDevice);
376
377
static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
378
                                   QualType &type,
379
                                   Sema::CUDAFunctionTarget CFT);
380
381
static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
382
                                             ParsedAttr &attr, QualType &type);
383
384
static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
385
                                 QualType &type);
386
387
static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
388
                                        ParsedAttr &attr, QualType &type);
389
390
static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
391
8.24k
                                      ParsedAttr &attr, QualType &type) {
392
8.24k
  if (attr.getKind() == ParsedAttr::AT_ObjCGC)
393
294
    return handleObjCGCTypeAttr(state, attr, type);
394
7.94k
  assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership);
395
7.94k
  return handleObjCOwnershipTypeAttr(state, attr, type);
396
7.94k
}
397
398
/// Given the index of a declarator chunk, check whether that chunk
399
/// directly specifies the return type of a function and, if so, find
400
/// an appropriate place for it.
401
///
402
/// \param i - a notional index which the search will start
403
///   immediately inside
404
///
405
/// \param onlyBlockPointers Whether we should only look into block
406
/// pointer types (vs. all pointer types).
407
static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
408
                                                unsigned i,
409
5.40k
                                                bool onlyBlockPointers) {
410
5.40k
  assert(i <= declarator.getNumTypeObjects());
411
412
5.40k
  DeclaratorChunk *result = nullptr;
413
414
  // First, look inwards past parens for a function declarator.
415
5.43k
  for (; i != 0; 
--i37
) {
416
3.79k
    DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
417
3.79k
    switch (fnChunk.Kind) {
418
9
    case DeclaratorChunk::Paren:
419
9
      continue;
420
421
    // If we find anything except a function, bail out.
422
1.55k
    case DeclaratorChunk::Pointer:
423
1.55k
    case DeclaratorChunk::BlockPointer:
424
3.57k
    case DeclaratorChunk::Array:
425
3.74k
    case DeclaratorChunk::Reference:
426
3.74k
    case DeclaratorChunk::MemberPointer:
427
3.74k
    case DeclaratorChunk::Pipe:
428
3.74k
      return result;
429
430
    // If we do find a function declarator, scan inwards from that,
431
    // looking for a (block-)pointer declarator.
432
42
    case DeclaratorChunk::Function:
433
78
      for (--i; i != 0; 
--i36
) {
434
64
        DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
435
64
        switch (ptrChunk.Kind) {
436
32
        case DeclaratorChunk::Paren:
437
32
        case DeclaratorChunk::Array:
438
32
        case DeclaratorChunk::Function:
439
32
        case DeclaratorChunk::Reference:
440
32
        case DeclaratorChunk::Pipe:
441
32
          continue;
442
443
2
        case DeclaratorChunk::MemberPointer:
444
10
        case DeclaratorChunk::Pointer:
445
10
          if (onlyBlockPointers)
446
4
            continue;
447
448
10
          
[[fallthrough]];6
449
450
28
        case DeclaratorChunk::BlockPointer:
451
28
          result = &ptrChunk;
452
28
          goto continue_outer;
453
64
        }
454
0
        llvm_unreachable("bad declarator chunk kind");
455
0
      }
456
457
      // If we run out of declarators doing that, we're done.
458
14
      return result;
459
3.79k
    }
460
0
    llvm_unreachable("bad declarator chunk kind");
461
462
    // Okay, reconsider from our new point.
463
28
  continue_outer: ;
464
28
  }
465
466
  // Ran out of chunks, bail out.
467
1.64k
  return result;
468
5.40k
}
469
470
/// Given that an objc_gc attribute was written somewhere on a
471
/// declaration *other* than on the declarator itself (for which, use
472
/// distributeObjCPointerTypeAttrFromDeclarator), and given that it
473
/// didn't apply in whatever position it was written in, try to move
474
/// it to a more appropriate position.
475
static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
476
1.62k
                                          ParsedAttr &attr, QualType type) {
477
1.62k
  Declarator &declarator = state.getDeclarator();
478
479
  // Move it to the outermost normal or block pointer declarator.
480
1.62k
  for (unsigned i = state.getCurrentChunkIndex(); i != 0; 
--i0
) {
481
1.62k
    DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
482
1.62k
    switch (chunk.Kind) {
483
1.61k
    case DeclaratorChunk::Pointer:
484
1.61k
    case DeclaratorChunk::BlockPointer: {
485
      // But don't move an ARC ownership attribute to the return type
486
      // of a block.
487
1.61k
      DeclaratorChunk *destChunk = nullptr;
488
1.61k
      if (state.isProcessingDeclSpec() &&
489
1.61k
          attr.getKind() == ParsedAttr::AT_ObjCOwnership)
490
1.54k
        destChunk = maybeMovePastReturnType(declarator, i - 1,
491
1.54k
                                            /*onlyBlockPointers=*/true);
492
1.61k
      if (!destChunk) 
destChunk = &chunk1.61k
;
493
494
1.61k
      moveAttrFromListToList(attr, state.getCurrentAttributes(),
495
1.61k
                             destChunk->getAttrs());
496
1.61k
      return;
497
1.61k
    }
498
499
0
    case DeclaratorChunk::Paren:
500
0
    case DeclaratorChunk::Array:
501
0
      continue;
502
503
    // We may be starting at the return type of a block.
504
8
    case DeclaratorChunk::Function:
505
8
      if (state.isProcessingDeclSpec() &&
506
8
          attr.getKind() == ParsedAttr::AT_ObjCOwnership) {
507
8
        if (DeclaratorChunk *dest = maybeMovePastReturnType(
508
8
                                      declarator, i,
509
8
                                      /*onlyBlockPointers=*/true)) {
510
8
          moveAttrFromListToList(attr, state.getCurrentAttributes(),
511
8
                                 dest->getAttrs());
512
8
          return;
513
8
        }
514
8
      }
515
0
      goto error;
516
517
    // Don't walk through these.
518
0
    case DeclaratorChunk::Reference:
519
0
    case DeclaratorChunk::MemberPointer:
520
0
    case DeclaratorChunk::Pipe:
521
0
      goto error;
522
1.62k
    }
523
1.62k
  }
524
6
 error:
525
526
6
  diagnoseBadTypeAttribute(state.getSema(), attr, type);
527
6
}
528
529
/// Distribute an objc_gc type attribute that was written on the
530
/// declarator.
531
static void distributeObjCPointerTypeAttrFromDeclarator(
532
18
    TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) {
533
18
  Declarator &declarator = state.getDeclarator();
534
535
  // objc_gc goes on the innermost pointer to something that's not a
536
  // pointer.
537
18
  unsigned innermost = -1U;
538
18
  bool considerDeclSpec = true;
539
28
  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; 
++i10
) {
540
15
    DeclaratorChunk &chunk = declarator.getTypeObject(i);
541
15
    switch (chunk.Kind) {
542
0
    case DeclaratorChunk::Pointer:
543
4
    case DeclaratorChunk::BlockPointer:
544
4
      innermost = i;
545
4
      continue;
546
547
0
    case DeclaratorChunk::Reference:
548
0
    case DeclaratorChunk::MemberPointer:
549
4
    case DeclaratorChunk::Paren:
550
6
    case DeclaratorChunk::Array:
551
6
    case DeclaratorChunk::Pipe:
552
6
      continue;
553
554
5
    case DeclaratorChunk::Function:
555
5
      considerDeclSpec = false;
556
5
      goto done;
557
15
    }
558
15
  }
559
18
 done:
560
561
  // That might actually be the decl spec if we weren't blocked by
562
  // anything in the declarator.
563
18
  if (considerDeclSpec) {
564
13
    if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
565
      // Splice the attribute into the decl spec.  Prevents the
566
      // attribute from being applied multiple times and gives
567
      // the source-location-filler something to work with.
568
13
      state.saveDeclSpecAttrs();
569
13
      declarator.getMutableDeclSpec().getAttributes().takeOneFrom(
570
13
          declarator.getAttributes(), &attr);
571
13
      return;
572
13
    }
573
13
  }
574
575
  // Otherwise, if we found an appropriate chunk, splice the attribute
576
  // into it.
577
5
  if (innermost != -1U) {
578
4
    moveAttrFromListToList(attr, declarator.getAttributes(),
579
4
                           declarator.getTypeObject(innermost).getAttrs());
580
4
    return;
581
4
  }
582
583
  // Otherwise, diagnose when we're done building the type.
584
1
  declarator.getAttributes().remove(&attr);
585
1
  state.addIgnoredTypeAttr(attr);
586
1
}
587
588
/// A function type attribute was written somewhere in a declaration
589
/// *other* than on the declarator itself or in the decl spec.  Given
590
/// that it didn't apply in whatever position it was written in, try
591
/// to move it to a more appropriate position.
592
static void distributeFunctionTypeAttr(TypeProcessingState &state,
593
34
                                       ParsedAttr &attr, QualType type) {
594
34
  Declarator &declarator = state.getDeclarator();
595
596
  // Try to push the attribute from the return type of a function to
597
  // the function itself.
598
36
  for (unsigned i = state.getCurrentChunkIndex(); i != 0; 
--i2
) {
599
36
    DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
600
36
    switch (chunk.Kind) {
601
34
    case DeclaratorChunk::Function:
602
34
      moveAttrFromListToList(attr, state.getCurrentAttributes(),
603
34
                             chunk.getAttrs());
604
34
      return;
605
606
2
    case DeclaratorChunk::Paren:
607
2
    case DeclaratorChunk::Pointer:
608
2
    case DeclaratorChunk::BlockPointer:
609
2
    case DeclaratorChunk::Array:
610
2
    case DeclaratorChunk::Reference:
611
2
    case DeclaratorChunk::MemberPointer:
612
2
    case DeclaratorChunk::Pipe:
613
2
      continue;
614
36
    }
615
36
  }
616
617
0
  diagnoseBadTypeAttribute(state.getSema(), attr, type);
618
0
}
619
620
/// Try to distribute a function type attribute to the innermost
621
/// function chunk or type.  Returns true if the attribute was
622
/// distributed, false if no location was found.
623
static bool distributeFunctionTypeAttrToInnermost(
624
    TypeProcessingState &state, ParsedAttr &attr,
625
    ParsedAttributesView &attrList, QualType &declSpecType,
626
52.5k
    Sema::CUDAFunctionTarget CFT) {
627
52.5k
  Declarator &declarator = state.getDeclarator();
628
629
  // Put it on the innermost function chunk, if there is one.
630
52.8k
  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; 
++i325
) {
631
52.7k
    DeclaratorChunk &chunk = declarator.getTypeObject(i);
632
52.7k
    if (chunk.Kind != DeclaratorChunk::Function) 
continue325
;
633
634
52.4k
    moveAttrFromListToList(attr, attrList, chunk.getAttrs());
635
52.4k
    return true;
636
52.7k
  }
637
638
62
  return handleFunctionTypeAttr(state, attr, declSpecType, CFT);
639
52.5k
}
640
641
/// A function type attribute was written in the decl spec.  Try to
642
/// apply it somewhere.
643
static void
644
distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
645
                                       ParsedAttr &attr, QualType &declSpecType,
646
45.6k
                                       Sema::CUDAFunctionTarget CFT) {
647
45.6k
  state.saveDeclSpecAttrs();
648
649
  // Try to distribute to the innermost.
650
45.6k
  if (distributeFunctionTypeAttrToInnermost(
651
45.6k
          state, attr, state.getCurrentAttributes(), declSpecType, CFT))
652
45.6k
    return;
653
654
  // If that failed, diagnose the bad attribute when the declarator is
655
  // fully built.
656
12
  state.addIgnoredTypeAttr(attr);
657
12
}
658
659
/// A function type attribute was written on the declarator or declaration.
660
/// Try to apply it somewhere.
661
/// `Attrs` is the attribute list containing the declaration (either of the
662
/// declarator or the declaration).
663
static void distributeFunctionTypeAttrFromDeclarator(
664
    TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType,
665
6.88k
    Sema::CUDAFunctionTarget CFT) {
666
6.88k
  Declarator &declarator = state.getDeclarator();
667
668
  // Try to distribute to the innermost.
669
6.88k
  if (distributeFunctionTypeAttrToInnermost(
670
6.88k
          state, attr, declarator.getAttributes(), declSpecType, CFT))
671
6.86k
    return;
672
673
  // If that failed, diagnose the bad attribute when the declarator is
674
  // fully built.
675
15
  declarator.getAttributes().remove(&attr);
676
15
  state.addIgnoredTypeAttr(attr);
677
15
}
678
679
/// Given that there are attributes written on the declarator or declaration
680
/// itself, try to distribute any type attributes to the appropriate
681
/// declarator chunk.
682
///
683
/// These are attributes like the following:
684
///   int f ATTR;
685
///   int (f ATTR)();
686
/// but not necessarily this:
687
///   int f() ATTR;
688
///
689
/// `Attrs` is the attribute list containing the declaration (either of the
690
/// declarator or the declaration).
691
static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
692
                                              QualType &declSpecType,
693
155M
                                              Sema::CUDAFunctionTarget CFT) {
694
  // The called functions in this loop actually remove things from the current
695
  // list, so iterating over the existing list isn't possible.  Instead, make a
696
  // non-owning copy and iterate over that.
697
155M
  ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()};
698
155M
  for (ParsedAttr &attr : AttrsCopy) {
699
    // Do not distribute [[]] attributes. They have strict rules for what
700
    // they appertain to.
701
4.68M
    if (attr.isStandardAttributeSyntax() || 
attr.isRegularKeywordAttribute()4.68M
)
702
307
      continue;
703
704
4.68M
    switch (attr.getKind()) {
705
18
    
OBJC_POINTER_TYPE_ATTRS_CASELIST2
:
706
18
      distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType);
707
18
      break;
708
709
6.88k
    
FUNCTION_TYPE_ATTRS_CASELIST511
:
710
6.88k
      distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType, CFT);
711
6.88k
      break;
712
713
0
    MS_TYPE_ATTRS_CASELIST:
714
      // Microsoft type attributes cannot go after the declarator-id.
715
0
      continue;
716
717
0
    NULLABILITY_TYPE_ATTRS_CASELIST:
718
      // Nullability specifiers cannot go after the declarator-id.
719
720
    // Objective-C __kindof does not get distributed.
721
0
    case ParsedAttr::AT_ObjCKindOf:
722
0
      continue;
723
724
4.67M
    default:
725
4.67M
      break;
726
4.68M
    }
727
4.68M
  }
728
155M
}
729
730
/// Add a synthetic '()' to a block-literal declarator if it is
731
/// required, given the return type.
732
static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
733
3.36k
                                          QualType declSpecType) {
734
3.36k
  Declarator &declarator = state.getDeclarator();
735
736
  // First, check whether the declarator would produce a function,
737
  // i.e. whether the innermost semantic chunk is a function.
738
3.36k
  if (declarator.isFunctionDeclarator()) {
739
    // If so, make that declarator a prototyped declarator.
740
3.34k
    declarator.getFunctionTypeInfo().hasPrototype = true;
741
3.34k
    return;
742
3.34k
  }
743
744
  // If there are any type objects, the type as written won't name a
745
  // function, regardless of the decl spec type.  This is because a
746
  // block signature declarator is always an abstract-declarator, and
747
  // abstract-declarators can't just be parentheses chunks.  Therefore
748
  // we need to build a function chunk unless there are no type
749
  // objects and the decl spec type is a function.
750
24
  if (!declarator.getNumTypeObjects() && 
declSpecType->isFunctionType()21
)
751
4
    return;
752
753
  // Note that there *are* cases with invalid declarators where
754
  // declarators consist solely of parentheses.  In general, these
755
  // occur only in failed efforts to make function declarators, so
756
  // faking up the function chunk is still the right thing to do.
757
758
  // Otherwise, we need to fake up a function declarator.
759
20
  SourceLocation loc = declarator.getBeginLoc();
760
761
  // ...and *prepend* it to the declarator.
762
20
  SourceLocation NoLoc;
763
20
  declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
764
20
      /*HasProto=*/true,
765
20
      /*IsAmbiguous=*/false,
766
20
      /*LParenLoc=*/NoLoc,
767
20
      /*ArgInfo=*/nullptr,
768
20
      /*NumParams=*/0,
769
20
      /*EllipsisLoc=*/NoLoc,
770
20
      /*RParenLoc=*/NoLoc,
771
20
      /*RefQualifierIsLvalueRef=*/true,
772
20
      /*RefQualifierLoc=*/NoLoc,
773
20
      /*MutableLoc=*/NoLoc, EST_None,
774
20
      /*ESpecRange=*/SourceRange(),
775
20
      /*Exceptions=*/nullptr,
776
20
      /*ExceptionRanges=*/nullptr,
777
20
      /*NumExceptions=*/0,
778
20
      /*NoexceptExpr=*/nullptr,
779
20
      /*ExceptionSpecTokens=*/nullptr,
780
20
      /*DeclsInPrototype=*/std::nullopt, loc, loc, declarator));
781
782
  // For consistency, make sure the state still has us as processing
783
  // the decl spec.
784
20
  assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
785
20
  state.setCurrentChunkIndex(declarator.getNumTypeObjects());
786
20
}
787
788
static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
789
                                            unsigned &TypeQuals,
790
                                            QualType TypeSoFar,
791
                                            unsigned RemoveTQs,
792
3.17k
                                            unsigned DiagID) {
793
  // If this occurs outside a template instantiation, warn the user about
794
  // it; they probably didn't mean to specify a redundant qualifier.
795
3.17k
  typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
796
3.17k
  for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
797
3.17k
                       QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()),
798
3.17k
                       QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
799
12.7k
                       QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
800
12.7k
    if (!(RemoveTQs & Qual.first))
801
122
      continue;
802
803
12.5k
    if (!S.inTemplateInstantiation()) {
804
12.5k
      if (TypeQuals & Qual.first)
805
100
        S.Diag(Qual.second, DiagID)
806
100
          << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
807
100
          << FixItHint::CreateRemoval(Qual.second);
808
12.5k
    }
809
810
12.5k
    TypeQuals &= ~Qual.first;
811
12.5k
  }
812
3.17k
}
813
814
/// Return true if this is omitted block return type. Also check type
815
/// attributes and type qualifiers when returning true.
816
static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
817
3.45k
                                        QualType Result) {
818
3.45k
  if (!isOmittedBlockReturnType(declarator))
819
383
    return false;
820
821
  // Warn if we see type attributes for omitted return type on a block literal.
822
3.07k
  SmallVector<ParsedAttr *, 2> ToBeRemoved;
823
3.07k
  for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) {
824
22
    if (AL.isInvalid() || !AL.isTypeAttr())
825
17
      continue;
826
5
    S.Diag(AL.getLoc(),
827
5
           diag::warn_block_literal_attributes_on_omitted_return_type)
828
5
        << AL;
829
5
    ToBeRemoved.push_back(&AL);
830
5
  }
831
  // Remove bad attributes from the list.
832
3.07k
  for (ParsedAttr *AL : ToBeRemoved)
833
5
    declarator.getMutableDeclSpec().getAttributes().remove(AL);
834
835
  // Warn if we see type qualifiers for omitted return type on a block literal.
836
3.07k
  const DeclSpec &DS = declarator.getDeclSpec();
837
3.07k
  unsigned TypeQuals = DS.getTypeQualifiers();
838
3.07k
  diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
839
3.07k
      diag::warn_block_literal_qualifiers_on_omitted_return_type);
840
3.07k
  declarator.getMutableDeclSpec().ClearTypeQualifiers();
841
842
3.07k
  return true;
843
3.45k
}
844
845
/// Apply Objective-C type arguments to the given type.
846
static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
847
                                  ArrayRef<TypeSourceInfo *> typeArgs,
848
                                  SourceRange typeArgsRange, bool failOnError,
849
130k
                                  bool rebuilding) {
850
  // We can only apply type arguments to an Objective-C class type.
851
130k
  const auto *objcObjectType = type->getAs<ObjCObjectType>();
852
130k
  if (!objcObjectType || 
!objcObjectType->getInterface()130k
) {
853
1
    S.Diag(loc, diag::err_objc_type_args_non_class)
854
1
      << type
855
1
      << typeArgsRange;
856
857
1
    if (failOnError)
858
0
      return QualType();
859
1
    return type;
860
1
  }
861
862
  // The class type must be parameterized.
863
130k
  ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
864
130k
  ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
865
130k
  if (!typeParams) {
866
1
    S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
867
1
      << objcClass->getDeclName()
868
1
      << FixItHint::CreateRemoval(typeArgsRange);
869
870
1
    if (failOnError)
871
0
      return QualType();
872
873
1
    return type;
874
1
  }
875
876
  // The type must not already be specialized.
877
130k
  if (objcObjectType->isSpecialized()) {
878
3
    S.Diag(loc, diag::err_objc_type_args_specialized_class)
879
3
      << type
880
3
      << FixItHint::CreateRemoval(typeArgsRange);
881
882
3
    if (failOnError)
883
0
      return QualType();
884
885
3
    return type;
886
3
  }
887
888
  // Check the type arguments.
889
130k
  SmallVector<QualType, 4> finalTypeArgs;
890
130k
  unsigned numTypeParams = typeParams->size();
891
130k
  bool anyPackExpansions = false;
892
291k
  for (unsigned i = 0, n = typeArgs.size(); i != n; 
++i161k
) {
893
161k
    TypeSourceInfo *typeArgInfo = typeArgs[i];
894
161k
    QualType typeArg = typeArgInfo->getType();
895
896
    // Type arguments cannot have explicit qualifiers or nullability.
897
    // We ignore indirect sources of these, e.g. behind typedefs or
898
    // template arguments.
899
161k
    if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
900
23
      bool diagnosed = false;
901
23
      SourceRange rangeToRemove;
902
23
      if (auto attr = qual.getAs<AttributedTypeLoc>()) {
903
14
        rangeToRemove = attr.getLocalSourceRange();
904
14
        if (attr.getTypePtr()->getImmediateNullability()) {
905
1
          typeArg = attr.getTypePtr()->getModifiedType();
906
1
          S.Diag(attr.getBeginLoc(),
907
1
                 diag::err_objc_type_arg_explicit_nullability)
908
1
              << typeArg << FixItHint::CreateRemoval(rangeToRemove);
909
1
          diagnosed = true;
910
1
        }
911
14
      }
912
913
      // When rebuilding, qualifiers might have gotten here through a
914
      // final substitution.
915
23
      if (!rebuilding && 
!diagnosed17
) {
916
16
        S.Diag(qual.getBeginLoc(), diag::err_objc_type_arg_qualified)
917
16
            << typeArg << typeArg.getQualifiers().getAsString()
918
16
            << FixItHint::CreateRemoval(rangeToRemove);
919
16
      }
920
23
    }
921
922
    // Remove qualifiers even if they're non-local.
923
161k
    typeArg = typeArg.getUnqualifiedType();
924
925
161k
    finalTypeArgs.push_back(typeArg);
926
927
161k
    if (typeArg->getAs<PackExpansionType>())
928
1
      anyPackExpansions = true;
929
930
    // Find the corresponding type parameter, if there is one.
931
161k
    ObjCTypeParamDecl *typeParam = nullptr;
932
161k
    if (!anyPackExpansions) {
933
161k
      if (i < numTypeParams) {
934
161k
        typeParam = typeParams->begin()[i];
935
161k
      } else {
936
        // Too many arguments.
937
2
        S.Diag(loc, diag::err_objc_type_args_wrong_arity)
938
2
          << false
939
2
          << objcClass->getDeclName()
940
2
          << (unsigned)typeArgs.size()
941
2
          << numTypeParams;
942
2
        S.Diag(objcClass->getLocation(), diag::note_previous_decl)
943
2
          << objcClass;
944
945
2
        if (failOnError)
946
1
          return QualType();
947
948
1
        return type;
949
2
      }
950
161k
    }
951
952
    // Objective-C object pointer types must be substitutable for the bounds.
953
161k
    if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
954
      // If we don't have a type parameter to match against, assume
955
      // everything is fine. There was a prior pack expansion that
956
      // means we won't be able to match anything.
957
161k
      if (!typeParam) {
958
0
        assert(anyPackExpansions && "Too many arguments?");
959
0
        continue;
960
0
      }
961
962
      // Retrieve the bound.
963
161k
      QualType bound = typeParam->getUnderlyingType();
964
161k
      const auto *boundObjC = bound->castAs<ObjCObjectPointerType>();
965
966
      // Determine whether the type argument is substitutable for the bound.
967
161k
      if (typeArgObjC->isObjCIdType()) {
968
        // When the type argument is 'id', the only acceptable type
969
        // parameter bound is 'id'.
970
63.8k
        if (boundObjC->isObjCIdType())
971
63.8k
          continue;
972
97.3k
      } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
973
        // Otherwise, we follow the assignability rules.
974
97.3k
        continue;
975
97.3k
      }
976
977
      // Diagnose the mismatch.
978
6
      S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
979
6
             diag::err_objc_type_arg_does_not_match_bound)
980
6
          << typeArg << bound << typeParam->getDeclName();
981
6
      S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
982
6
        << typeParam->getDeclName();
983
984
6
      if (failOnError)
985
2
        return QualType();
986
987
4
      return type;
988
6
    }
989
990
    // Block pointer types are permitted for unqualified 'id' bounds.
991
237
    if (typeArg->isBlockPointerType()) {
992
      // If we don't have a type parameter to match against, assume
993
      // everything is fine. There was a prior pack expansion that
994
      // means we won't be able to match anything.
995
229
      if (!typeParam) {
996
0
        assert(anyPackExpansions && "Too many arguments?");
997
0
        continue;
998
0
      }
999
1000
      // Retrieve the bound.
1001
229
      QualType bound = typeParam->getUnderlyingType();
1002
229
      if (bound->isBlockCompatibleObjCPointerType(S.Context))
1003
229
        continue;
1004
1005
      // Diagnose the mismatch.
1006
0
      S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
1007
0
             diag::err_objc_type_arg_does_not_match_bound)
1008
0
          << typeArg << bound << typeParam->getDeclName();
1009
0
      S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
1010
0
        << typeParam->getDeclName();
1011
1012
0
      if (failOnError)
1013
0
        return QualType();
1014
1015
0
      return type;
1016
0
    }
1017
1018
    // Dependent types will be checked at instantiation time.
1019
8
    if (typeArg->isDependentType()) {
1020
8
      continue;
1021
8
    }
1022
1023
    // Diagnose non-id-compatible type arguments.
1024
0
    S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
1025
0
           diag::err_objc_type_arg_not_id_compatible)
1026
0
        << typeArg << typeArgInfo->getTypeLoc().getSourceRange();
1027
1028
0
    if (failOnError)
1029
0
      return QualType();
1030
1031
0
    return type;
1032
0
  }
1033
1034
  // Make sure we didn't have the wrong number of arguments.
1035
130k
  if (!anyPackExpansions && 
finalTypeArgs.size() != numTypeParams130k
) {
1036
3
    S.Diag(loc, diag::err_objc_type_args_wrong_arity)
1037
3
      << (typeArgs.size() < typeParams->size())
1038
3
      << objcClass->getDeclName()
1039
3
      << (unsigned)finalTypeArgs.size()
1040
3
      << (unsigned)numTypeParams;
1041
3
    S.Diag(objcClass->getLocation(), diag::note_previous_decl)
1042
3
      << objcClass;
1043
1044
3
    if (failOnError)
1045
1
      return QualType();
1046
1047
2
    return type;
1048
3
  }
1049
1050
  // Success. Form the specialized type.
1051
130k
  return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
1052
130k
}
1053
1054
QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1055
                                      SourceLocation ProtocolLAngleLoc,
1056
                                      ArrayRef<ObjCProtocolDecl *> Protocols,
1057
                                      ArrayRef<SourceLocation> ProtocolLocs,
1058
                                      SourceLocation ProtocolRAngleLoc,
1059
0
                                      bool FailOnError) {
1060
0
  QualType Result = QualType(Decl->getTypeForDecl(), 0);
1061
0
  if (!Protocols.empty()) {
1062
0
    bool HasError;
1063
0
    Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1064
0
                                                 HasError);
1065
0
    if (HasError) {
1066
0
      Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers)
1067
0
        << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1068
0
      if (FailOnError) Result = QualType();
1069
0
    }
1070
0
    if (FailOnError && Result.isNull())
1071
0
      return QualType();
1072
0
  }
1073
1074
0
  return Result;
1075
0
}
1076
1077
QualType Sema::BuildObjCObjectType(
1078
    QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc,
1079
    ArrayRef<TypeSourceInfo *> TypeArgs, SourceLocation TypeArgsRAngleLoc,
1080
    SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols,
1081
    ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc,
1082
153k
    bool FailOnError, bool Rebuilding) {
1083
153k
  QualType Result = BaseType;
1084
153k
  if (!TypeArgs.empty()) {
1085
130k
    Result =
1086
130k
        applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
1087
130k
                          SourceRange(TypeArgsLAngleLoc, TypeArgsRAngleLoc),
1088
130k
                          FailOnError, Rebuilding);
1089
130k
    if (FailOnError && 
Result.isNull()17
)
1090
4
      return QualType();
1091
130k
  }
1092
1093
153k
  if (!Protocols.empty()) {
1094
23.0k
    bool HasError;
1095
23.0k
    Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1096
23.0k
                                                 HasError);
1097
23.0k
    if (HasError) {
1098
1
      Diag(Loc, diag::err_invalid_protocol_qualifiers)
1099
1
        << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1100
1
      if (FailOnError) 
Result = QualType()0
;
1101
1
    }
1102
23.0k
    if (FailOnError && 
Result.isNull()0
)
1103
0
      return QualType();
1104
23.0k
  }
1105
1106
153k
  return Result;
1107
153k
}
1108
1109
TypeResult Sema::actOnObjCProtocolQualifierType(
1110
             SourceLocation lAngleLoc,
1111
             ArrayRef<Decl *> protocols,
1112
             ArrayRef<SourceLocation> protocolLocs,
1113
7
             SourceLocation rAngleLoc) {
1114
  // Form id<protocol-list>.
1115
7
  QualType Result = Context.getObjCObjectType(
1116
7
      Context.ObjCBuiltinIdTy, {},
1117
7
      llvm::ArrayRef((ObjCProtocolDecl *const *)protocols.data(),
1118
7
                     protocols.size()),
1119
7
      false);
1120
7
  Result = Context.getObjCObjectPointerType(Result);
1121
1122
7
  TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1123
7
  TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1124
1125
7
  auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1126
7
  ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1127
1128
7
  auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1129
7
                        .castAs<ObjCObjectTypeLoc>();
1130
7
  ObjCObjectTL.setHasBaseTypeAsWritten(false);
1131
7
  ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1132
1133
  // No type arguments.
1134
7
  ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1135
7
  ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1136
1137
  // Fill in protocol qualifiers.
1138
7
  ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
1139
7
  ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
1140
14
  for (unsigned i = 0, n = protocols.size(); i != n; 
++i7
)
1141
7
    ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
1142
1143
  // We're done. Return the completed type to the parser.
1144
7
  return CreateParsedType(Result, ResultTInfo);
1145
7
}
1146
1147
TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers(
1148
             Scope *S,
1149
             SourceLocation Loc,
1150
             ParsedType BaseType,
1151
             SourceLocation TypeArgsLAngleLoc,
1152
             ArrayRef<ParsedType> TypeArgs,
1153
             SourceLocation TypeArgsRAngleLoc,
1154
             SourceLocation ProtocolLAngleLoc,
1155
             ArrayRef<Decl *> Protocols,
1156
             ArrayRef<SourceLocation> ProtocolLocs,
1157
153k
             SourceLocation ProtocolRAngleLoc) {
1158
153k
  TypeSourceInfo *BaseTypeInfo = nullptr;
1159
153k
  QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
1160
153k
  if (T.isNull())
1161
0
    return true;
1162
1163
  // Handle missing type-source info.
1164
153k
  if (!BaseTypeInfo)
1165
153k
    BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
1166
1167
  // Extract type arguments.
1168
153k
  SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
1169
315k
  for (unsigned i = 0, n = TypeArgs.size(); i != n; 
++i161k
) {
1170
161k
    TypeSourceInfo *TypeArgInfo = nullptr;
1171
161k
    QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
1172
161k
    if (TypeArg.isNull()) {
1173
0
      ActualTypeArgInfos.clear();
1174
0
      break;
1175
0
    }
1176
1177
161k
    assert(TypeArgInfo && "No type source info?");
1178
161k
    ActualTypeArgInfos.push_back(TypeArgInfo);
1179
161k
  }
1180
1181
  // Build the object type.
1182
153k
  QualType Result = BuildObjCObjectType(
1183
153k
      T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1184
153k
      TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1185
153k
      ProtocolLAngleLoc,
1186
153k
      llvm::ArrayRef((ObjCProtocolDecl *const *)Protocols.data(),
1187
153k
                     Protocols.size()),
1188
153k
      ProtocolLocs, ProtocolRAngleLoc,
1189
153k
      /*FailOnError=*/false,
1190
153k
      /*Rebuilding=*/false);
1191
1192
153k
  if (Result == T)
1193
57
    return BaseType;
1194
1195
  // Create source information for this type.
1196
153k
  TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1197
153k
  TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1198
1199
  // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
1200
  // object pointer type. Fill in source information for it.
1201
153k
  if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
1202
    // The '*' is implicit.
1203
15.6k
    ObjCObjectPointerTL.setStarLoc(SourceLocation());
1204
15.6k
    ResultTL = ObjCObjectPointerTL.getPointeeLoc();
1205
15.6k
  }
1206
1207
153k
  if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) {
1208
    // Protocol qualifier information.
1209
1.76k
    if (OTPTL.getNumProtocols() > 0) {
1210
1.76k
      assert(OTPTL.getNumProtocols() == Protocols.size());
1211
1.76k
      OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1212
1.76k
      OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1213
3.53k
      for (unsigned i = 0, n = Protocols.size(); i != n; 
++i1.76k
)
1214
1.76k
        OTPTL.setProtocolLoc(i, ProtocolLocs[i]);
1215
1.76k
    }
1216
1217
    // We're done. Return the completed type to the parser.
1218
1.76k
    return CreateParsedType(Result, ResultTInfo);
1219
1.76k
  }
1220
1221
151k
  auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
1222
1223
  // Type argument information.
1224
151k
  if (ObjCObjectTL.getNumTypeArgs() > 0) {
1225
130k
    assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
1226
130k
    ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
1227
130k
    ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
1228
291k
    for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; 
++i161k
)
1229
161k
      ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
1230
130k
  } else {
1231
21.2k
    ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1232
21.2k
    ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1233
21.2k
  }
1234
1235
  // Protocol qualifier information.
1236
151k
  if (ObjCObjectTL.getNumProtocols() > 0) {
1237
21.2k
    assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
1238
21.2k
    ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1239
21.2k
    ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1240
43.4k
    for (unsigned i = 0, n = Protocols.size(); i != n; 
++i22.1k
)
1241
22.1k
      ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
1242
130k
  } else {
1243
130k
    ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1244
130k
    ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1245
130k
  }
1246
1247
  // Base type.
1248
151k
  ObjCObjectTL.setHasBaseTypeAsWritten(true);
1249
151k
  if (ObjCObjectTL.getType() == T)
1250
0
    ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1251
151k
  else
1252
151k
    ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1253
1254
  // We're done. Return the completed type to the parser.
1255
151k
  return CreateParsedType(Result, ResultTInfo);
1256
151k
}
1257
1258
static OpenCLAccessAttr::Spelling
1259
8.62k
getImageAccess(const ParsedAttributesView &Attrs) {
1260
8.62k
  for (const ParsedAttr &AL : Attrs)
1261
8.47k
    if (AL.getKind() == ParsedAttr::AT_OpenCLAccess)
1262
8.47k
      return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling());
1263
147
  return OpenCLAccessAttr::Keyword_read_only;
1264
8.62k
}
1265
1266
static UnaryTransformType::UTTKind
1267
11.9k
TSTToUnaryTransformType(DeclSpec::TST SwitchTST) {
1268
11.9k
  switch (SwitchTST) {
1269
0
#define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait)                                  \
1270
11.9k
  case TST_##Trait:                                                            \
1271
11.9k
    return UnaryTransformType::Enum;
1272
0
#include "clang/Basic/TransformTypeTraits.def"
1273
0
  default:
1274
0
    llvm_unreachable("attempted to parse a non-unary transform builtin");
1275
11.9k
  }
1276
11.9k
}
1277
1278
/// Convert the specified declspec to the appropriate type
1279
/// object.
1280
/// \param state Specifies the declarator containing the declaration specifier
1281
/// to be converted, along with other associated processing state.
1282
/// \returns The type described by the declaration specifiers.  This function
1283
/// never returns null.
1284
155M
static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
1285
  // FIXME: Should move the logic from DeclSpec::Finish to here for validity
1286
  // checking.
1287
1288
155M
  Sema &S = state.getSema();
1289
155M
  Declarator &declarator = state.getDeclarator();
1290
155M
  DeclSpec &DS = declarator.getMutableDeclSpec();
1291
155M
  SourceLocation DeclLoc = declarator.getIdentifierLoc();
1292
155M
  if (DeclLoc.isInvalid())
1293
997k
    DeclLoc = DS.getBeginLoc();
1294
1295
155M
  ASTContext &Context = S.Context;
1296
1297
155M
  QualType Result;
1298
155M
  switch (DS.getTypeSpecType()) {
1299
4.66M
  case DeclSpec::TST_void:
1300
4.66M
    Result = Context.VoidTy;
1301
4.66M
    break;
1302
1.18M
  case DeclSpec::TST_char:
1303
1.18M
    if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
1304
992k
      Result = Context.CharTy;
1305
193k
    else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed)
1306
52.7k
      Result = Context.SignedCharTy;
1307
140k
    else {
1308
140k
      assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&
1309
140k
             "Unknown TSS value");
1310
140k
      Result = Context.UnsignedCharTy;
1311
140k
    }
1312
1.18M
    break;
1313
1.18M
  case DeclSpec::TST_wchar:
1314
191k
    if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
1315
191k
      Result = Context.WCharTy;
1316
6
    else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed) {
1317
3
      S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
1318
3
        << DS.getSpecifierName(DS.getTypeSpecType(),
1319
3
                               Context.getPrintingPolicy());
1320
3
      Result = Context.getSignedWCharType();
1321
3
    } else {
1322
3
      assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&
1323
3
             "Unknown TSS value");
1324
3
      S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
1325
3
        << DS.getSpecifierName(DS.getTypeSpecType(),
1326
3
                               Context.getPrintingPolicy());
1327
3
      Result = Context.getUnsignedWCharType();
1328
3
    }
1329
191k
    break;
1330
191k
  case DeclSpec::TST_char8:
1331
362
    assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1332
362
           "Unknown TSS value");
1333
362
    Result = Context.Char8Ty;
1334
362
    break;
1335
16.1k
  case DeclSpec::TST_char16:
1336
16.1k
    assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1337
16.1k
           "Unknown TSS value");
1338
16.1k
    Result = Context.Char16Ty;
1339
16.1k
    break;
1340
16.3k
  case DeclSpec::TST_char32:
1341
16.3k
    assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1342
16.3k
           "Unknown TSS value");
1343
16.3k
    Result = Context.Char32Ty;
1344
16.3k
    break;
1345
11.2k
  case DeclSpec::TST_unspecified:
1346
    // If this is a missing declspec in a block literal return context, then it
1347
    // is inferred from the return statements inside the block.
1348
    // The declspec is always missing in a lambda expr context; it is either
1349
    // specified with a trailing return type or inferred.
1350
11.2k
    if (S.getLangOpts().CPlusPlus14 &&
1351
11.2k
        
declarator.getContext() == DeclaratorContext::LambdaExpr6.53k
) {
1352
      // In C++1y, a lambda's implicit return type is 'auto'.
1353
5.49k
      Result = Context.getAutoDeductType();
1354
5.49k
      break;
1355
5.73k
    } else if (declarator.getContext() == DeclaratorContext::LambdaExpr ||
1356
5.73k
               checkOmittedBlockReturnType(S, declarator,
1357
5.34k
                                           Context.DependentTy)) {
1358
5.34k
      Result = Context.DependentTy;
1359
5.34k
      break;
1360
5.34k
    }
1361
1362
    // Unspecified typespec defaults to int in C90.  However, the C90 grammar
1363
    // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
1364
    // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
1365
    // Note that the one exception to this is function definitions, which are
1366
    // allowed to be completely missing a declspec.  This is handled in the
1367
    // parser already though by it pretending to have seen an 'int' in this
1368
    // case.
1369
383
    if (S.getLangOpts().isImplicitIntRequired()) {
1370
14
      S.Diag(DeclLoc, diag::warn_missing_type_specifier)
1371
14
          << DS.getSourceRange()
1372
14
          << FixItHint::CreateInsertion(DS.getBeginLoc(), "int");
1373
369
    } else if (!DS.hasTypeSpecifier()) {
1374
      // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
1375
      // "At least one type specifier shall be given in the declaration
1376
      // specifiers in each declaration, and in the specifier-qualifier list in
1377
      // each struct declaration and type name."
1378
369
      if (!S.getLangOpts().isImplicitIntAllowed() && 
!DS.isTypeSpecPipe()241
) {
1379
238
        S.Diag(DeclLoc, diag::err_missing_type_specifier)
1380
238
            << DS.getSourceRange();
1381
1382
        // When this occurs, often something is very broken with the value
1383
        // being declared, poison it as invalid so we don't get chains of
1384
        // errors.
1385
238
        declarator.setInvalidType(true);
1386
238
      } else 
if (131
S.getLangOpts().getOpenCLCompatibleVersion() >= 200131
&&
1387
131
                 
DS.isTypeSpecPipe()7
) {
1388
6
        S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1389
6
            << DS.getSourceRange();
1390
6
        declarator.setInvalidType(true);
1391
125
      } else {
1392
125
        assert(S.getLangOpts().isImplicitIntAllowed() &&
1393
125
               "implicit int is disabled?");
1394
125
        S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1395
125
            << DS.getSourceRange()
1396
125
            << FixItHint::CreateInsertion(DS.getBeginLoc(), "int");
1397
125
      }
1398
369
    }
1399
1400
383
    [[fallthrough]];
1401
3.51M
  case DeclSpec::TST_int: {
1402
3.51M
    if (DS.getTypeSpecSign() != TypeSpecifierSign::Unsigned) {
1403
2.84M
      switch (DS.getTypeSpecWidth()) {
1404
2.37M
      case TypeSpecifierWidth::Unspecified:
1405
2.37M
        Result = Context.IntTy;
1406
2.37M
        break;
1407
157k
      case TypeSpecifierWidth::Short:
1408
157k
        Result = Context.ShortTy;
1409
157k
        break;
1410
194k
      case TypeSpecifierWidth::Long:
1411
194k
        Result = Context.LongTy;
1412
194k
        break;
1413
118k
      case TypeSpecifierWidth::LongLong:
1414
118k
        Result = Context.LongLongTy;
1415
1416
        // 'long long' is a C99 or C++11 feature.
1417
118k
        if (!S.getLangOpts().C99) {
1418
64.0k
          if (S.getLangOpts().CPlusPlus)
1419
64.0k
            S.Diag(DS.getTypeSpecWidthLoc(),
1420
64.0k
                   S.getLangOpts().CPlusPlus11 ?
1421
62.9k
                   diag::warn_cxx98_compat_longlong : 
diag::ext_cxx11_longlong1.12k
);
1422
41
          else
1423
41
            S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1424
64.0k
        }
1425
118k
        break;
1426
2.84M
      }
1427
2.84M
    } else {
1428
664k
      switch (DS.getTypeSpecWidth()) {
1429
327k
      case TypeSpecifierWidth::Unspecified:
1430
327k
        Result = Context.UnsignedIntTy;
1431
327k
        break;
1432
117k
      case TypeSpecifierWidth::Short:
1433
117k
        Result = Context.UnsignedShortTy;
1434
117k
        break;
1435
114k
      case TypeSpecifierWidth::Long:
1436
114k
        Result = Context.UnsignedLongTy;
1437
114k
        break;
1438
104k
      case TypeSpecifierWidth::LongLong:
1439
104k
        Result = Context.UnsignedLongLongTy;
1440
1441
        // 'long long' is a C99 or C++11 feature.
1442
104k
        if (!S.getLangOpts().C99) {
1443
61.2k
          if (S.getLangOpts().CPlusPlus)
1444
61.2k
            S.Diag(DS.getTypeSpecWidthLoc(),
1445
61.2k
                   S.getLangOpts().CPlusPlus11 ?
1446
60.2k
                   diag::warn_cxx98_compat_longlong : 
diag::ext_cxx11_longlong941
);
1447
14
          else
1448
14
            S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1449
61.2k
        }
1450
104k
        break;
1451
664k
      }
1452
664k
    }
1453
3.51M
    break;
1454
3.51M
  }
1455
3.51M
  case DeclSpec::TST_bitint: {
1456
1.36k
    if (!S.Context.getTargetInfo().hasBitIntType())
1457
2
      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "_BitInt";
1458
1.36k
    Result =
1459
1.36k
        S.BuildBitIntType(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned,
1460
1.36k
                          DS.getRepAsExpr(), DS.getBeginLoc());
1461
1.36k
    if (Result.isNull()) {
1462
11
      Result = Context.IntTy;
1463
11
      declarator.setInvalidType(true);
1464
11
    }
1465
1.36k
    break;
1466
3.51M
  }
1467
1.03k
  case DeclSpec::TST_accum: {
1468
1.03k
    switch (DS.getTypeSpecWidth()) {
1469
520
    case TypeSpecifierWidth::Short:
1470
520
      Result = Context.ShortAccumTy;
1471
520
      break;
1472
320
    case TypeSpecifierWidth::Unspecified:
1473
320
      Result = Context.AccumTy;
1474
320
      break;
1475
191
    case TypeSpecifierWidth::Long:
1476
191
      Result = Context.LongAccumTy;
1477
191
      break;
1478
0
    case TypeSpecifierWidth::LongLong:
1479
0
      llvm_unreachable("Unable to specify long long as _Accum width");
1480
1.03k
    }
1481
1482
1.03k
    if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1483
331
      Result = Context.getCorrespondingUnsignedType(Result);
1484
1485
1.03k
    if (DS.isTypeSpecSat())
1486
372
      Result = Context.getCorrespondingSaturatedType(Result);
1487
1488
1.03k
    break;
1489
1.03k
  }
1490
551
  case DeclSpec::TST_fract: {
1491
551
    switch (DS.getTypeSpecWidth()) {
1492
168
    case TypeSpecifierWidth::Short:
1493
168
      Result = Context.ShortFractTy;
1494
168
      break;
1495
218
    case TypeSpecifierWidth::Unspecified:
1496
218
      Result = Context.FractTy;
1497
218
      break;
1498
165
    case TypeSpecifierWidth::Long:
1499
165
      Result = Context.LongFractTy;
1500
165
      break;
1501
0
    case TypeSpecifierWidth::LongLong:
1502
0
      llvm_unreachable("Unable to specify long long as _Fract width");
1503
551
    }
1504
1505
551
    if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1506
210
      Result = Context.getCorrespondingUnsignedType(Result);
1507
1508
551
    if (DS.isTypeSpecSat())
1509
179
      Result = Context.getCorrespondingSaturatedType(Result);
1510
1511
551
    break;
1512
551
  }
1513
1.08k
  case DeclSpec::TST_int128:
1514
1.08k
    if (!S.Context.getTargetInfo().hasInt128Type() &&
1515
1.08k
        
!(31
S.getLangOpts().SYCLIsDevice31
||
S.getLangOpts().CUDAIsDevice13
||
1516
31
          
(9
S.getLangOpts().OpenMP9
&&
S.getLangOpts().OpenMPIsTargetDevice0
)))
1517
9
      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1518
9
        << "__int128";
1519
1.08k
    if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1520
685
      Result = Context.UnsignedInt128Ty;
1521
401
    else
1522
401
      Result = Context.Int128Ty;
1523
1.08k
    break;
1524
29.3k
  case DeclSpec::TST_float16:
1525
    // CUDA host and device may have different _Float16 support, therefore
1526
    // do not diagnose _Float16 usage to avoid false alarm.
1527
    // ToDo: more precise diagnostics for CUDA.
1528
29.3k
    if (!S.Context.getTargetInfo().hasFloat16Type() && 
!S.getLangOpts().CUDA2
&&
1529
29.3k
        
!(2
S.getLangOpts().OpenMP2
&&
S.getLangOpts().OpenMPIsTargetDevice0
))
1530
2
      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1531
2
        << "_Float16";
1532
29.3k
    Result = Context.Float16Ty;
1533
29.3k
    break;
1534
25.0k
  case DeclSpec::TST_half:    Result = Context.HalfTy; break;
1535
6.60k
  case DeclSpec::TST_BFloat16:
1536
6.60k
    if (!S.Context.getTargetInfo().hasBFloat16Type() &&
1537
6.60k
        
!(21
S.getLangOpts().OpenMP21
&&
S.getLangOpts().OpenMPIsTargetDevice0
) &&
1538
6.60k
        
!S.getLangOpts().SYCLIsDevice21
)
1539
18
      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__bf16";
1540
6.60k
    Result = Context.BFloat16Ty;
1541
6.60k
    break;
1542
385k
  case DeclSpec::TST_float:   Result = Context.FloatTy; break;
1543
630k
  case DeclSpec::TST_double:
1544
630k
    if (DS.getTypeSpecWidth() == TypeSpecifierWidth::Long)
1545
197k
      Result = Context.LongDoubleTy;
1546
433k
    else
1547
433k
      Result = Context.DoubleTy;
1548
630k
    if (S.getLangOpts().OpenCL) {
1549
15.3k
      if (!S.getOpenCLOptions().isSupported("cl_khr_fp64", S.getLangOpts()))
1550
38
        S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1551
38
            << 0 << Result
1552
38
            << (S.getLangOpts().getOpenCLCompatibleVersion() == 300
1553
38
                    ? 
"cl_khr_fp64 and __opencl_c_fp64"16
1554
38
                    : 
"cl_khr_fp64"22
);
1555
15.3k
      else if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp64", S.getLangOpts()))
1556
24
        S.Diag(DS.getTypeSpecTypeLoc(), diag::ext_opencl_double_without_pragma);
1557
15.3k
    }
1558
630k
    break;
1559
456
  case DeclSpec::TST_float128:
1560
456
    if (!S.Context.getTargetInfo().hasFloat128Type() &&
1561
456
        
!S.getLangOpts().SYCLIsDevice40
&&
1562
456
        
!(23
S.getLangOpts().OpenMP23
&&
S.getLangOpts().OpenMPIsTargetDevice11
))
1563
12
      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1564
12
        << "__float128";
1565
456
    Result = Context.Float128Ty;
1566
456
    break;
1567
109
  case DeclSpec::TST_ibm128:
1568
109
    if (!S.Context.getTargetInfo().hasIbm128Type() &&
1569
109
        
!S.getLangOpts().SYCLIsDevice17
&&
1570
109
        
!(17
S.getLangOpts().OpenMP17
&&
S.getLangOpts().OpenMPIsTargetDevice2
))
1571
15
      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__ibm128";
1572
109
    Result = Context.Ibm128Ty;
1573
109
    break;
1574
887k
  case DeclSpec::TST_bool:
1575
887k
    Result = Context.BoolTy; // _Bool or bool
1576
887k
    break;
1577
6
  case DeclSpec::TST_decimal32:    // _Decimal32
1578
6
  case DeclSpec::TST_decimal64:    // _Decimal64
1579
8
  case DeclSpec::TST_decimal128:   // _Decimal128
1580
8
    S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1581
8
    Result = Context.IntTy;
1582
8
    declarator.setInvalidType(true);
1583
8
    break;
1584
26.0k
  case DeclSpec::TST_class:
1585
472k
  case DeclSpec::TST_enum:
1586
505k
  case DeclSpec::TST_union:
1587
1.42M
  case DeclSpec::TST_struct:
1588
1.42M
  case DeclSpec::TST_interface: {
1589
1.42M
    TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl());
1590
1.42M
    if (!D) {
1591
      // This can happen in C++ with ambiguous lookups.
1592
16.5k
      Result = Context.IntTy;
1593
16.5k
      declarator.setInvalidType(true);
1594
16.5k
      break;
1595
16.5k
    }
1596
1597
    // If the type is deprecated or unavailable, diagnose it.
1598
1.40M
    S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
1599
1600
1.40M
    assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&
1601
1.40M
           DS.getTypeSpecComplex() == 0 &&
1602
1.40M
           DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1603
1.40M
           "No qualifiers on tag names!");
1604
1605
    // TypeQuals handled by caller.
1606
1.40M
    Result = Context.getTypeDeclType(D);
1607
1608
    // In both C and C++, make an ElaboratedType.
1609
1.40M
    ElaboratedTypeKeyword Keyword
1610
1.40M
      = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
1611
1.40M
    Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result,
1612
1.40M
                                 DS.isTypeSpecOwned() ? 
D450k
:
nullptr954k
);
1613
1.40M
    break;
1614
1.40M
  }
1615
142M
  case DeclSpec::TST_typename: {
1616
142M
    assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&
1617
142M
           DS.getTypeSpecComplex() == 0 &&
1618
142M
           DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1619
142M
           "Can't handle qualifiers on typedef names yet!");
1620
142M
    Result = S.GetTypeFromParser(DS.getRepAsType());
1621
142M
    if (Result.isNull()) {
1622
0
      declarator.setInvalidType(true);
1623
0
    }
1624
1625
    // TypeQuals handled by caller.
1626
142M
    break;
1627
142M
  }
1628
23
  case DeclSpec::TST_typeof_unqualType:
1629
158
  case DeclSpec::TST_typeofType:
1630
    // FIXME: Preserve type source info.
1631
158
    Result = S.GetTypeFromParser(DS.getRepAsType());
1632
158
    assert(!Result.isNull() && "Didn't get a type for typeof?");
1633
158
    if (!Result->isDependentType())
1634
155
      if (const TagType *TT = Result->getAs<TagType>())
1635
13
        S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1636
    // TypeQuals handled by caller.
1637
158
    Result = Context.getTypeOfType(
1638
158
        Result, DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualType
1639
158
                    ? 
TypeOfKind::Unqualified23
1640
158
                    : 
TypeOfKind::Qualified135
);
1641
158
    break;
1642
38
  case DeclSpec::TST_typeof_unqualExpr:
1643
3.26k
  case DeclSpec::TST_typeofExpr: {
1644
3.26k
    Expr *E = DS.getRepAsExpr();
1645
3.26k
    assert(E && "Didn't get an expression for typeof?");
1646
    // TypeQuals handled by caller.
1647
3.26k
    Result = S.BuildTypeofExprType(E, DS.getTypeSpecType() ==
1648
3.26k
                                              DeclSpec::TST_typeof_unqualExpr
1649
3.26k
                                          ? 
TypeOfKind::Unqualified38
1650
3.26k
                                          : 
TypeOfKind::Qualified3.22k
);
1651
3.26k
    if (Result.isNull()) {
1652
0
      Result = Context.IntTy;
1653
0
      declarator.setInvalidType(true);
1654
0
    }
1655
3.26k
    break;
1656
3.26k
  }
1657
62.1k
  case DeclSpec::TST_decltype: {
1658
62.1k
    Expr *E = DS.getRepAsExpr();
1659
62.1k
    assert(E && "Didn't get an expression for decltype?");
1660
    // TypeQuals handled by caller.
1661
62.1k
    Result = S.BuildDecltypeType(E);
1662
62.1k
    if (Result.isNull()) {
1663
0
      Result = Context.IntTy;
1664
0
      declarator.setInvalidType(true);
1665
0
    }
1666
62.1k
    break;
1667
62.1k
  }
1668
96.5k
#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
1669
96.5k
#include 
"clang/Basic/TransformTypeTraits.def"62.1k
1670
96.5k
    Result = S.GetTypeFromParser(DS.getRepAsType());
1671
96.5k
    assert(!Result.isNull() && "Didn't get a type for the transformation?");
1672
11.9k
    Result = S.BuildUnaryTransformType(
1673
11.9k
        Result, TSTToUnaryTransformType(DS.getTypeSpecType()),
1674
11.9k
        DS.getTypeSpecTypeLoc());
1675
11.9k
    if (Result.isNull()) {
1676
140
      Result = Context.IntTy;
1677
140
      declarator.setInvalidType(true);
1678
140
    }
1679
11.9k
    break;
1680
1681
93.2k
  case DeclSpec::TST_auto:
1682
94.2k
  case DeclSpec::TST_decltype_auto: {
1683
94.2k
    auto AutoKW = DS.getTypeSpecType() == DeclSpec::TST_decltype_auto
1684
94.2k
                      ? 
AutoTypeKeyword::DecltypeAuto944
1685
94.2k
                      : 
AutoTypeKeyword::Auto93.2k
;
1686
1687
94.2k
    ConceptDecl *TypeConstraintConcept = nullptr;
1688
94.2k
    llvm::SmallVector<TemplateArgument, 8> TemplateArgs;
1689
94.2k
    if (DS.isConstrainedAuto()) {
1690
391
      if (TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId()) {
1691
381
        TypeConstraintConcept =
1692
381
            cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl());
1693
381
        TemplateArgumentListInfo TemplateArgsInfo;
1694
381
        TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc);
1695
381
        TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc);
1696
381
        ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1697
381
                                           TemplateId->NumArgs);
1698
381
        S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
1699
381
        for (const auto &ArgLoc : TemplateArgsInfo.arguments())
1700
205
          TemplateArgs.push_back(ArgLoc.getArgument());
1701
381
      } else {
1702
10
        declarator.setInvalidType(true);
1703
10
      }
1704
391
    }
1705
94.2k
    Result = S.Context.getAutoType(QualType(), AutoKW,
1706
94.2k
                                   /*IsDependent*/ false, /*IsPack=*/false,
1707
94.2k
                                   TypeConstraintConcept, TemplateArgs);
1708
94.2k
    break;
1709
93.2k
  }
1710
1711
52
  case DeclSpec::TST_auto_type:
1712
52
    Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1713
52
    break;
1714
1715
62
  case DeclSpec::TST_unknown_anytype:
1716
62
    Result = Context.UnknownAnyTy;
1717
62
    break;
1718
1719
3.11k
  case DeclSpec::TST_atomic:
1720
3.11k
    Result = S.GetTypeFromParser(DS.getRepAsType());
1721
3.11k
    assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1722
3.11k
    Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1723
3.11k
    if (Result.isNull()) {
1724
13
      Result = Context.IntTy;
1725
13
      declarator.setInvalidType(true);
1726
13
    }
1727
3.11k
    break;
1728
1729
0
#define GENERIC_IMAGE_TYPE(ImgType, Id)                                        \
1730
8.62k
  case DeclSpec::TST_##ImgType##_t:                                            \
1731
8.62k
    switch (getImageAccess(DS.getAttributes())) {                              \
1732
2.33k
    case OpenCLAccessAttr::Keyword_write_only:                                 \
1733
2.33k
      Result = Context.Id##WOTy;                                               \
1734
2.33k
      break;                                                                   \
1735
2.21k
    case OpenCLAccessAttr::Keyword_read_write:                                 \
1736
2.21k
      Result = Context.Id##RWTy;                                               \
1737
2.21k
      break;                                                                   \
1738
4.07k
    case OpenCLAccessAttr::Keyword_read_only:                                  \
1739
4.07k
      Result = Context.Id##ROTy;                                               \
1740
4.07k
      break;                                                                   \
1741
0
    case OpenCLAccessAttr::SpellingNotCalculated:                              \
1742
0
      llvm_unreachable("Spelling not yet calculated");                         \
1743
8.62k
    }                                                                          \
1744
8.62k
    break;
1745
3.11k
#include "clang/Basic/OpenCLImageTypes.def"
1746
1747
1.80k
  case DeclSpec::TST_error:
1748
1.80k
    Result = Context.IntTy;
1749
1.80k
    declarator.setInvalidType(true);
1750
1.80k
    break;
1751
155M
  }
1752
1753
  // FIXME: we want resulting declarations to be marked invalid, but claiming
1754
  // the type is invalid is too strong - e.g. it causes ActOnTypeName to return
1755
  // a null type.
1756
155M
  if (Result->containsErrors())
1757
105
    declarator.setInvalidType();
1758
1759
155M
  if (S.getLangOpts().OpenCL) {
1760
791k
    const auto &OpenCLOptions = S.getOpenCLOptions();
1761
791k
    bool IsOpenCLC30Compatible =
1762
791k
        S.getLangOpts().getOpenCLCompatibleVersion() == 300;
1763
    // OpenCL C v3.0 s6.3.3 - OpenCL image types require __opencl_c_images
1764
    // support.
1765
    // OpenCL C v3.0 s6.2.1 - OpenCL 3d image write types requires support
1766
    // for OpenCL C 2.0, or OpenCL C 3.0 or newer and the
1767
    // __opencl_c_3d_image_writes feature. OpenCL C v3.0 API s4.2 - For devices
1768
    // that support OpenCL 3.0, cl_khr_3d_image_writes must be returned when and
1769
    // only when the optional feature is supported
1770
791k
    if ((Result->isImageType() || 
Result->isSamplerT()782k
) &&
1771
791k
        
(10.9k
IsOpenCLC30Compatible10.9k
&&
1772
10.9k
         
!OpenCLOptions.isSupported("__opencl_c_images", S.getLangOpts())1.55k
)) {
1773
24
      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1774
24
          << 0 << Result << "__opencl_c_images";
1775
24
      declarator.setInvalidType();
1776
791k
    } else if (Result->isOCLImage3dWOType() &&
1777
791k
               !OpenCLOptions.isSupported("cl_khr_3d_image_writes",
1778
327
                                          S.getLangOpts())) {
1779
3
      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1780
3
          << 0 << Result
1781
3
          << (IsOpenCLC30Compatible
1782
3
                  ? 
"cl_khr_3d_image_writes and __opencl_c_3d_image_writes"2
1783
3
                  : 
"cl_khr_3d_image_writes"1
);
1784
3
      declarator.setInvalidType();
1785
3
    }
1786
791k
  }
1787
1788
155M
  bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1789
155M
                          
DS.getTypeSpecType() == DeclSpec::TST_fract155M
;
1790
1791
  // Only fixed point types can be saturated
1792
155M
  if (DS.isTypeSpecSat() && 
!IsFixedPointType562
)
1793
11
    S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
1794
11
        << DS.getSpecifierName(DS.getTypeSpecType(),
1795
11
                               Context.getPrintingPolicy());
1796
1797
  // Handle complex types.
1798
155M
  if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1799
6.35k
    if (S.getLangOpts().Freestanding)
1800
798
      S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1801
6.35k
    Result = Context.getComplexType(Result);
1802
155M
  } else if (DS.isTypeAltiVecVector()) {
1803
97.7k
    unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1804
97.7k
    assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1805
97.7k
    VectorKind VecKind = VectorKind::AltiVecVector;
1806
97.7k
    if (DS.isTypeAltiVecPixel())
1807
2.40k
      VecKind = VectorKind::AltiVecPixel;
1808
95.3k
    else if (DS.isTypeAltiVecBool())
1809
17.6k
      VecKind = VectorKind::AltiVecBool;
1810
97.7k
    Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1811
97.7k
  }
1812
1813
  // FIXME: Imaginary.
1814
155M
  if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1815
10
    S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1816
1817
  // Before we process any type attributes, synthesize a block literal
1818
  // function declarator if necessary.
1819
155M
  if (declarator.getContext() == DeclaratorContext::BlockLiteral)
1820
3.36k
    maybeSynthesizeBlockSignature(state, Result);
1821
1822
  // Apply any type attributes from the decl spec.  This may cause the
1823
  // list of type attributes to be temporarily saved while the type
1824
  // attributes are pushed around.
1825
  // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1826
155M
  if (!DS.isTypeSpecPipe()) {
1827
    // We also apply declaration attributes that "slide" to the decl spec.
1828
    // Ordering can be important for attributes. The decalaration attributes
1829
    // come syntactically before the decl spec attributes, so we process them
1830
    // in that order.
1831
155M
    ParsedAttributesView SlidingAttrs;
1832
155M
    for (ParsedAttr &AL : declarator.getDeclarationAttributes()) {
1833
117k
      if (AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
1834
32
        SlidingAttrs.addAtEnd(&AL);
1835
1836
        // For standard syntax attributes, which would normally appertain to the
1837
        // declaration here, suggest moving them to the type instead. But only
1838
        // do this for our own vendor attributes; moving other vendors'
1839
        // attributes might hurt portability.
1840
        // There's one special case that we need to deal with here: The
1841
        // `MatrixType` attribute may only be used in a typedef declaration. If
1842
        // it's being used anywhere else, don't output the warning as
1843
        // ProcessDeclAttributes() will output an error anyway.
1844
32
        if (AL.isStandardAttributeSyntax() && AL.isClangScope() &&
1845
32
            !(AL.getKind() == ParsedAttr::AT_MatrixType &&
1846
32
              
DS.getStorageClassSpec() != DeclSpec::SCS_typedef3
)) {
1847
31
          S.Diag(AL.getLoc(), diag::warn_type_attribute_deprecated_on_decl)
1848
31
              << AL;
1849
31
        }
1850
32
      }
1851
117k
    }
1852
    // During this call to processTypeAttrs(),
1853
    // TypeProcessingState::getCurrentAttributes() will erroneously return a
1854
    // reference to the DeclSpec attributes, rather than the declaration
1855
    // attributes. However, this doesn't matter, as getCurrentAttributes()
1856
    // is only called when distributing attributes from one attribute list
1857
    // to another. Declaration attributes are always C++11 attributes, and these
1858
    // are never distributed.
1859
155M
    processTypeAttrs(state, Result, TAL_DeclSpec, SlidingAttrs);
1860
155M
    processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes());
1861
155M
  }
1862
1863
  // Apply const/volatile/restrict qualifiers to T.
1864
155M
  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1865
    // Warn about CV qualifiers on function types.
1866
    // C99 6.7.3p8:
1867
    //   If the specification of a function type includes any type qualifiers,
1868
    //   the behavior is undefined.
1869
    // C++11 [dcl.fct]p7:
1870
    //   The effect of a cv-qualifier-seq in a function declarator is not the
1871
    //   same as adding cv-qualification on top of the function type. In the
1872
    //   latter case, the cv-qualifiers are ignored.
1873
6.52M
    if (Result->isFunctionType()) {
1874
22
      diagnoseAndRemoveTypeQualifiers(
1875
22
          S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1876
22
          S.getLangOpts().CPlusPlus
1877
22
              ? 
diag::warn_typecheck_function_qualifiers_ignored18
1878
22
              : 
diag::warn_typecheck_function_qualifiers_unspecified4
);
1879
      // No diagnostic for 'restrict' or '_Atomic' applied to a
1880
      // function type; we'll diagnose those later, in BuildQualifiedType.
1881
22
    }
1882
1883
    // C++11 [dcl.ref]p1:
1884
    //   Cv-qualified references are ill-formed except when the
1885
    //   cv-qualifiers are introduced through the use of a typedef-name
1886
    //   or decltype-specifier, in which case the cv-qualifiers are ignored.
1887
    //
1888
    // There don't appear to be any other contexts in which a cv-qualified
1889
    // reference type could be formed, so the 'ill-formed' clause here appears
1890
    // to never happen.
1891
6.52M
    if (TypeQuals && 
Result->isReferenceType()6.52M
) {
1892
78
      diagnoseAndRemoveTypeQualifiers(
1893
78
          S, DS, TypeQuals, Result,
1894
78
          DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1895
78
          diag::warn_typecheck_reference_qualifiers);
1896
78
    }
1897
1898
    // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1899
    // than once in the same specifier-list or qualifier-list, either directly
1900
    // or via one or more typedefs."
1901
6.52M
    if (!S.getLangOpts().C99 && 
!S.getLangOpts().CPlusPlus3.50M
1902
6.52M
        && 
TypeQuals & Result.getCVRQualifiers()594
) {
1903
8
      if (TypeQuals & DeclSpec::TQ_const && 
Result.isConstQualified()6
) {
1904
6
        S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1905
6
          << "const";
1906
6
      }
1907
1908
8
      if (TypeQuals & DeclSpec::TQ_volatile && 
Result.isVolatileQualified()2
) {
1909
2
        S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1910
2
          << "volatile";
1911
2
      }
1912
1913
      // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1914
      // produce a warning in this case.
1915
8
    }
1916
1917
6.52M
    QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1918
1919
    // If adding qualifiers fails, just use the unqualified type.
1920
6.52M
    if (Qualified.isNull())
1921
21
      declarator.setInvalidType(true);
1922
6.52M
    else
1923
6.52M
      Result = Qualified;
1924
6.52M
  }
1925
1926
155M
  assert(!Result.isNull() && "This function should not return a null type");
1927
155M
  return Result;
1928
155M
}
1929
1930
143
static std::string getPrintableNameForEntity(DeclarationName Entity) {
1931
143
  if (Entity)
1932
108
    return Entity.getAsString();
1933
1934
35
  return "type name";
1935
143
}
1936
1937
4.00k
static bool isDependentOrGNUAutoType(QualType T) {
1938
4.00k
  if (T->isDependentType())
1939
490
    return true;
1940
1941
3.51k
  const auto *AT = dyn_cast<AutoType>(T);
1942
3.51k
  return AT && 
AT->isGNUAutoType()6
;
1943
4.00k
}
1944
1945
QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1946
7.55M
                                  Qualifiers Qs, const DeclSpec *DS) {
1947
7.55M
  if (T.isNull())
1948
0
    return QualType();
1949
1950
  // Ignore any attempt to form a cv-qualified reference.
1951
7.55M
  if (T->isReferenceType()) {
1952
113
    Qs.removeConst();
1953
113
    Qs.removeVolatile();
1954
113
  }
1955
1956
  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1957
  // object or incomplete types shall not be restrict-qualified."
1958
7.55M
  if (Qs.hasRestrict()) {
1959
66.4k
    unsigned DiagID = 0;
1960
66.4k
    QualType ProblemTy;
1961
1962
66.4k
    if (T->isAnyPointerType() || 
T->isReferenceType()52
||
1963
66.4k
        
T->isMemberPointerType()33
) {
1964
66.4k
      QualType EltTy;
1965
66.4k
      if (T->isObjCObjectPointerType())
1966
6
        EltTy = T;
1967
66.4k
      else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1968
6
        EltTy = PTy->getPointeeType();
1969
66.4k
      else
1970
66.4k
        EltTy = T->getPointeeType();
1971
1972
      // If we have a pointer or reference, the pointee must have an object
1973
      // incomplete type.
1974
66.4k
      if (!EltTy->isIncompleteOrObjectType()) {
1975
2
        DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1976
2
        ProblemTy = EltTy;
1977
2
      }
1978
66.4k
    } else 
if (27
!isDependentOrGNUAutoType(T)27
) {
1979
      // For an __auto_type variable, we may not have seen the initializer yet
1980
      // and so have no idea whether the underlying type is a pointer type or
1981
      // not.
1982
20
      DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1983
20
      ProblemTy = T;
1984
20
    }
1985
1986
66.4k
    if (DiagID) {
1987
22
      Diag(DS ? 
DS->getRestrictSpecLoc()15
:
Loc7
, DiagID) << ProblemTy;
1988
22
      Qs.removeRestrict();
1989
22
    }
1990
66.4k
  }
1991
1992
7.55M
  return Context.getQualifiedType(T, Qs);
1993
7.55M
}
1994
1995
QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1996
6.67M
                                  unsigned CVRAU, const DeclSpec *DS) {
1997
6.67M
  if (T.isNull())
1998
6
    return QualType();
1999
2000
  // Ignore any attempt to form a cv-qualified reference.
2001
6.67M
  if (T->isReferenceType())
2002
93
    CVRAU &=
2003
93
        ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic);
2004
2005
  // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
2006
  // TQ_unaligned;
2007
6.67M
  unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
2008
2009
  // C11 6.7.3/5:
2010
  //   If the same qualifier appears more than once in the same
2011
  //   specifier-qualifier-list, either directly or via one or more typedefs,
2012
  //   the behavior is the same as if it appeared only once.
2013
  //
2014
  // It's not specified what happens when the _Atomic qualifier is applied to
2015
  // a type specified with the _Atomic specifier, but we assume that this
2016
  // should be treated as if the _Atomic qualifier appeared multiple times.
2017
6.67M
  if (CVRAU & DeclSpec::TQ_atomic && 
!T->isAtomicType()248
) {
2018
    // C11 6.7.3/5:
2019
    //   If other qualifiers appear along with the _Atomic qualifier in a
2020
    //   specifier-qualifier-list, the resulting type is the so-qualified
2021
    //   atomic type.
2022
    //
2023
    // Don't need to worry about array types here, since _Atomic can't be
2024
    // applied to such types.
2025
246
    SplitQualType Split = T.getSplitUnqualifiedType();
2026
246
    T = BuildAtomicType(QualType(Split.Ty, 0),
2027
246
                        DS ? 
DS->getAtomicSpecLoc()228
:
Loc18
);
2028
246
    if (T.isNull())
2029
21
      return T;
2030
225
    Split.Quals.addCVRQualifiers(CVR);
2031
225
    return BuildQualifiedType(T, Loc, Split.Quals);
2032
246
  }
2033
2034
6.67M
  Qualifiers Q = Qualifiers::fromCVRMask(CVR);
2035
6.67M
  Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned);
2036
6.67M
  return BuildQualifiedType(T, Loc, Q, DS);
2037
6.67M
}
2038
2039
/// Build a paren type including \p T.
2040
325k
QualType Sema::BuildParenType(QualType T) {
2041
325k
  return Context.getParenType(T);
2042
325k
}
2043
2044
/// Given that we're building a pointer or reference to the given
2045
static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
2046
                                           SourceLocation loc,
2047
68.4k
                                           bool isReference) {
2048
  // Bail out if retention is unrequired or already specified.
2049
68.4k
  if (!type->isObjCLifetimeType() ||
2050
68.4k
      
type.getObjCLifetime() != Qualifiers::OCL_None1.59k
)
2051
68.4k
    return type;
2052
2053
24
  Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
2054
2055
  // If the object type is const-qualified, we can safely use
2056
  // __unsafe_unretained.  This is safe (because there are no read
2057
  // barriers), and it'll be safe to coerce anything but __weak* to
2058
  // the resulting type.
2059
24
  if (type.isConstQualified()) {
2060
2
    implicitLifetime = Qualifiers::OCL_ExplicitNone;
2061
2062
  // Otherwise, check whether the static type does not require
2063
  // retaining.  This currently only triggers for Class (possibly
2064
  // protocol-qualifed, and arrays thereof).
2065
22
  } else if (type->isObjCARCImplicitlyUnretainedType()) {
2066
3
    implicitLifetime = Qualifiers::OCL_ExplicitNone;
2067
2068
  // If we are in an unevaluated context, like sizeof, skip adding a
2069
  // qualification.
2070
19
  } else if (S.isUnevaluatedContext()) {
2071
4
    return type;
2072
2073
  // If that failed, give an error and recover using __strong.  __strong
2074
  // is the option most likely to prevent spurious second-order diagnostics,
2075
  // like when binding a reference to a field.
2076
15
  } else {
2077
    // These types can show up in private ivars in system headers, so
2078
    // we need this to not be an error in those cases.  Instead we
2079
    // want to delay.
2080
15
    if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
2081
14
      S.DelayedDiagnostics.add(
2082
14
          sema::DelayedDiagnostic::makeForbiddenType(loc,
2083
14
              diag::err_arc_indirect_no_ownership, type, isReference));
2084
14
    } else {
2085
1
      S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
2086
1
    }
2087
15
    implicitLifetime = Qualifiers::OCL_Strong;
2088
15
  }
2089
20
  assert(implicitLifetime && "didn't infer any lifetime!");
2090
2091
20
  Qualifiers qs;
2092
20
  qs.addObjCLifetime(implicitLifetime);
2093
20
  return S.Context.getQualifiedType(type, qs);
2094
20
}
2095
2096
87
static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
2097
87
  std::string Quals = FnTy->getMethodQuals().getAsString();
2098
2099
87
  switch (FnTy->getRefQualifier()) {
2100
48
  case RQ_None:
2101
48
    break;
2102
2103
18
  case RQ_LValue:
2104
18
    if (!Quals.empty())
2105
0
      Quals += ' ';
2106
18
    Quals += '&';
2107
18
    break;
2108
2109
21
  case RQ_RValue:
2110
21
    if (!Quals.empty())
2111
2
      Quals += ' ';
2112
21
    Quals += "&&";
2113
21
    break;
2114
87
  }
2115
2116
87
  return Quals;
2117
87
}
2118
2119
namespace {
2120
/// Kinds of declarator that cannot contain a qualified function type.
2121
///
2122
/// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
2123
///     a function type with a cv-qualifier or a ref-qualifier can only appear
2124
///     at the topmost level of a type.
2125
///
2126
/// Parens and member pointers are permitted. We don't diagnose array and
2127
/// function declarators, because they don't allow function types at all.
2128
///
2129
/// The values of this enum are used in diagnostics.
2130
enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
2131
} // end anonymous namespace
2132
2133
/// Check whether the type T is a qualified function type, and if it is,
2134
/// diagnose that it cannot be contained within the given kind of declarator.
2135
static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
2136
12.9M
                                   QualifiedFunctionKind QFK) {
2137
  // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
2138
12.9M
  const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
2139
12.9M
  if (!FPT ||
2140
12.9M
      
(277k
FPT->getMethodQuals().empty()277k
&&
FPT->getRefQualifier() == RQ_None277k
))
2141
12.9M
    return false;
2142
2143
24
  S.Diag(Loc, diag::err_compound_qualified_function_type)
2144
24
    << QFK << isa<FunctionType>(T.IgnoreParens()) << T
2145
24
    << getFunctionQualifiersAsString(FPT);
2146
24
  return true;
2147
12.9M
}
2148
2149
4.39k
bool Sema::CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc) {
2150
4.39k
  const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
2151
4.39k
  if (!FPT ||
2152
4.39k
      
(6
FPT->getMethodQuals().empty()6
&&
FPT->getRefQualifier() == RQ_None3
))
2153
4.38k
    return false;
2154
2155
6
  Diag(Loc, diag::err_qualified_function_typeid)
2156
6
      << T << getFunctionQualifiersAsString(FPT);
2157
6
  return true;
2158
4.39k
}
2159
2160
// Helper to deduce addr space of a pointee type in OpenCL mode.
2161
48.6k
static QualType deduceOpenCLPointeeAddrSpace(Sema &S, QualType PointeeType) {
2162
48.6k
  if (!PointeeType->isUndeducedAutoType() && 
!PointeeType->isDependentType()48.6k
&&
2163
48.6k
      
!PointeeType->isSamplerT()48.5k
&&
2164
48.6k
      
!PointeeType.hasAddressSpace()48.5k
)
2165
7.62k
    PointeeType = S.getASTContext().getAddrSpaceQualType(
2166
7.62k
        PointeeType, S.getASTContext().getDefaultOpenCLPointeeAddrSpace());
2167
48.6k
  return PointeeType;
2168
48.6k
}
2169
2170
/// Build a pointer type.
2171
///
2172
/// \param T The type to which we'll be building a pointer.
2173
///
2174
/// \param Loc The location of the entity whose type involves this
2175
/// pointer type or, if there is no such entity, the location of the
2176
/// type that will have pointer type.
2177
///
2178
/// \param Entity The name of the entity that involves the pointer
2179
/// type, if known.
2180
///
2181
/// \returns A suitable pointer type, if there are no
2182
/// errors. Otherwise, returns a NULL type.
2183
QualType Sema::BuildPointerType(QualType T,
2184
9.12M
                                SourceLocation Loc, DeclarationName Entity) {
2185
9.12M
  if (T->isReferenceType()) {
2186
    // C++ 8.3.2p4: There shall be no ... pointers to references ...
2187
61
    Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
2188
61
      << getPrintableNameForEntity(Entity) << T;
2189
61
    return QualType();
2190
61
  }
2191
2192
9.12M
  if (T->isFunctionType() && 
getLangOpts().OpenCL209k
&&
2193
9.12M
      !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2194
11
                                            getLangOpts())) {
2195
7
    Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
2196
7
    return QualType();
2197
7
  }
2198
2199
9.12M
  if (getLangOpts().HLSL && 
Loc.isValid()36
) {
2200
8
    Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
2201
8
    return QualType();
2202
8
  }
2203
2204
9.12M
  if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
2205
12
    return QualType();
2206
2207
9.12M
  assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
2208
2209
  // In ARC, it is forbidden to build pointers to unqualified pointers.
2210
9.12M
  if (getLangOpts().ObjCAutoRefCount)
2211
51.5k
    T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
2212
2213
9.12M
  if (getLangOpts().OpenCL)
2214
48.3k
    T = deduceOpenCLPointeeAddrSpace(*this, T);
2215
2216
  // In WebAssembly, pointers to reference types and pointers to tables are
2217
  // illegal.
2218
9.12M
  if (getASTContext().getTargetInfo().getTriple().isWasm()) {
2219
255
    if (T.isWebAssemblyReferenceType()) {
2220
34
      Diag(Loc, diag::err_wasm_reference_pr) << 0;
2221
34
      return QualType();
2222
34
    }
2223
2224
    // We need to desugar the type here in case T is a ParenType.
2225
221
    if (T->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
2226
12
      Diag(Loc, diag::err_wasm_table_pr) << 0;
2227
12
      return QualType();
2228
12
    }
2229
221
  }
2230
2231
  // Build the pointer type.
2232
9.12M
  return Context.getPointerType(T);
2233
9.12M
}
2234
2235
/// Build a reference type.
2236
///
2237
/// \param T The type to which we'll be building a reference.
2238
///
2239
/// \param Loc The location of the entity whose type involves this
2240
/// reference type or, if there is no such entity, the location of the
2241
/// type that will have reference type.
2242
///
2243
/// \param Entity The name of the entity that involves the reference
2244
/// type, if known.
2245
///
2246
/// \returns A suitable reference type, if there are no
2247
/// errors. Otherwise, returns a NULL type.
2248
QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
2249
                                  SourceLocation Loc,
2250
3.73M
                                  DeclarationName Entity) {
2251
3.73M
  assert(Context.getCanonicalType(T) != Context.OverloadTy &&
2252
3.73M
         "Unresolved overloaded function type");
2253
2254
  // C++0x [dcl.ref]p6:
2255
  //   If a typedef (7.1.3), a type template-parameter (14.3.1), or a
2256
  //   decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
2257
  //   type T, an attempt to create the type "lvalue reference to cv TR" creates
2258
  //   the type "lvalue reference to T", while an attempt to create the type
2259
  //   "rvalue reference to cv TR" creates the type TR.
2260
3.73M
  bool LValueRef = SpelledAsLValue || 
T->getAs<LValueReferenceType>()836k
;
2261
2262
  // C++ [dcl.ref]p4: There shall be no references to references.
2263
  //
2264
  // According to C++ DR 106, references to references are only
2265
  // diagnosed when they are written directly (e.g., "int & &"),
2266
  // but not when they happen via a typedef:
2267
  //
2268
  //   typedef int& intref;
2269
  //   typedef intref& intref2;
2270
  //
2271
  // Parser::ParseDeclaratorInternal diagnoses the case where
2272
  // references are written directly; here, we handle the
2273
  // collapsing of references-to-references as described in C++0x.
2274
  // DR 106 and 540 introduce reference-collapsing into C++98/03.
2275
2276
  // C++ [dcl.ref]p1:
2277
  //   A declarator that specifies the type "reference to cv void"
2278
  //   is ill-formed.
2279
3.73M
  if (T->isVoidType()) {
2280
29
    Diag(Loc, diag::err_reference_to_void);
2281
29
    return QualType();
2282
29
  }
2283
2284
3.73M
  if (getLangOpts().HLSL && 
Loc.isValid()33
) {
2285
5
    Diag(Loc, diag::err_hlsl_pointers_unsupported) << 1;
2286
5
    return QualType();
2287
5
  }
2288
2289
3.73M
  if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
2290
12
    return QualType();
2291
2292
3.73M
  if (T->isFunctionType() && 
getLangOpts().OpenCL7.18k
&&
2293
3.73M
      !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2294
10
                                            getLangOpts())) {
2295
5
    Diag(Loc, diag::err_opencl_function_pointer) << /*reference*/ 1;
2296
5
    return QualType();
2297
5
  }
2298
2299
  // In ARC, it is forbidden to build references to unqualified pointers.
2300
3.73M
  if (getLangOpts().ObjCAutoRefCount)
2301
16.9k
    T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
2302
2303
3.73M
  if (getLangOpts().OpenCL)
2304
112
    T = deduceOpenCLPointeeAddrSpace(*this, T);
2305
2306
  // In WebAssembly, references to reference types and tables are illegal.
2307
3.73M
  if (getASTContext().getTargetInfo().getTriple().isWasm() &&
2308
3.73M
      
T.isWebAssemblyReferenceType()38
) {
2309
0
    Diag(Loc, diag::err_wasm_reference_pr) << 1;
2310
0
    return QualType();
2311
0
  }
2312
3.73M
  if (T->isWebAssemblyTableType()) {
2313
0
    Diag(Loc, diag::err_wasm_table_pr) << 1;
2314
0
    return QualType();
2315
0
  }
2316
2317
  // Handle restrict on references.
2318
3.73M
  if (LValueRef)
2319
2.96M
    return Context.getLValueReferenceType(T, SpelledAsLValue);
2320
768k
  return Context.getRValueReferenceType(T);
2321
3.73M
}
2322
2323
/// Build a Read-only Pipe type.
2324
///
2325
/// \param T The type to which we'll be building a Pipe.
2326
///
2327
/// \param Loc We do not use it for now.
2328
///
2329
/// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2330
/// NULL type.
2331
249
QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) {
2332
249
  return Context.getReadPipeType(T);
2333
249
}
2334
2335
/// Build a Write-only Pipe type.
2336
///
2337
/// \param T The type to which we'll be building a Pipe.
2338
///
2339
/// \param Loc We do not use it for now.
2340
///
2341
/// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2342
/// NULL type.
2343
0
QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) {
2344
0
  return Context.getWritePipeType(T);
2345
0
}
2346
2347
/// Build a bit-precise integer type.
2348
///
2349
/// \param IsUnsigned Boolean representing the signedness of the type.
2350
///
2351
/// \param BitWidth Size of this int type in bits, or an expression representing
2352
/// that.
2353
///
2354
/// \param Loc Location of the keyword.
2355
QualType Sema::BuildBitIntType(bool IsUnsigned, Expr *BitWidth,
2356
1.54k
                               SourceLocation Loc) {
2357
1.54k
  if (BitWidth->isInstantiationDependent())
2358
25
    return Context.getDependentBitIntType(IsUnsigned, BitWidth);
2359
2360
1.52k
  llvm::APSInt Bits(32);
2361
1.52k
  ExprResult ICE =
2362
1.52k
      VerifyIntegerConstantExpression(BitWidth, &Bits, /*FIXME*/ AllowFold);
2363
2364
1.52k
  if (ICE.isInvalid())
2365
2
    return QualType();
2366
2367
1.51k
  size_t NumBits = Bits.getZExtValue();
2368
1.51k
  if (!IsUnsigned && 
NumBits < 21.24k
) {
2369
5
    Diag(Loc, diag::err_bit_int_bad_size) << 0;
2370
5
    return QualType();
2371
5
  }
2372
2373
1.51k
  if (IsUnsigned && 
NumBits < 1275
) {
2374
2
    Diag(Loc, diag::err_bit_int_bad_size) << 1;
2375
2
    return QualType();
2376
2
  }
2377
2378
1.51k
  const TargetInfo &TI = getASTContext().getTargetInfo();
2379
1.51k
  if (NumBits > TI.getMaxBitIntWidth()) {
2380
7
    Diag(Loc, diag::err_bit_int_max_size)
2381
7
        << IsUnsigned << static_cast<uint64_t>(TI.getMaxBitIntWidth());
2382
7
    return QualType();
2383
7
  }
2384
2385
1.50k
  return Context.getBitIntType(IsUnsigned, NumBits);
2386
1.51k
}
2387
2388
/// Check whether the specified array bound can be evaluated using the relevant
2389
/// language rules. If so, returns the possibly-converted expression and sets
2390
/// SizeVal to the size. If not, but the expression might be a VLA bound,
2391
/// returns ExprResult(). Otherwise, produces a diagnostic and returns
2392
/// ExprError().
2393
static ExprResult checkArraySize(Sema &S, Expr *&ArraySize,
2394
                                 llvm::APSInt &SizeVal, unsigned VLADiag,
2395
294k
                                 bool VLAIsError) {
2396
294k
  if (S.getLangOpts().CPlusPlus14 &&
2397
294k
      
(35.6k
VLAIsError35.6k
||
2398
35.6k
       
!ArraySize->getType()->isIntegralOrUnscopedEnumerationType()34.7k
)) {
2399
    // C++14 [dcl.array]p1:
2400
    //   The constant-expression shall be a converted constant expression of
2401
    //   type std::size_t.
2402
    //
2403
    // Don't apply this rule if we might be forming a VLA: in that case, we
2404
    // allow non-constant expressions and constant-folding. We only need to use
2405
    // the converted constant expression rules (to properly convert the source)
2406
    // when the source expression is of class type.
2407
897
    return S.CheckConvertedConstantExpression(
2408
897
        ArraySize, S.Context.getSizeType(), SizeVal, Sema::CCEK_ArrayBound);
2409
897
  }
2410
2411
  // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2412
  // (like gnu99, but not c99) accept any evaluatable value as an extension.
2413
293k
  class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2414
293k
  public:
2415
293k
    unsigned VLADiag;
2416
293k
    bool VLAIsError;
2417
293k
    bool IsVLA = false;
2418
2419
293k
    VLADiagnoser(unsigned VLADiag, bool VLAIsError)
2420
293k
        : VLADiag(VLADiag), VLAIsError(VLAIsError) {}
2421
2422
293k
    Sema::SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
2423
293k
                                                   QualType T) override {
2424
1
      return S.Diag(Loc, diag::err_array_size_non_int) << T;
2425
1
    }
2426
2427
293k
    Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
2428
293k
                                               SourceLocation Loc) override {
2429
3.97k
      IsVLA = !VLAIsError;
2430
3.97k
      return S.Diag(Loc, VLADiag);
2431
3.97k
    }
2432
2433
293k
    Sema::SemaDiagnosticBuilder diagnoseFold(Sema &S,
2434
293k
                                             SourceLocation Loc) override {
2435
0
      return S.Diag(Loc, diag::ext_vla_folded_to_constant);
2436
0
    }
2437
293k
  } Diagnoser(VLADiag, VLAIsError);
2438
2439
293k
  ExprResult R =
2440
293k
      S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser);
2441
293k
  if (Diagnoser.IsVLA)
2442
3.96k
    return ExprResult();
2443
289k
  return R;
2444
293k
}
2445
2446
375k
bool Sema::checkArrayElementAlignment(QualType EltTy, SourceLocation Loc) {
2447
375k
  EltTy = Context.getBaseElementType(EltTy);
2448
375k
  if (EltTy->isIncompleteType() || 
EltTy->isDependentType()374k
||
2449
375k
      
EltTy->isUndeducedType()336k
)
2450
38.4k
    return true;
2451
2452
336k
  CharUnits Size = Context.getTypeSizeInChars(EltTy);
2453
336k
  CharUnits Alignment = Context.getTypeAlignInChars(EltTy);
2454
2455
336k
  if (Size.isMultipleOf(Alignment))
2456
336k
    return true;
2457
2458
21
  Diag(Loc, diag::err_array_element_alignment)
2459
21
      << EltTy << Size.getQuantity() << Alignment.getQuantity();
2460
21
  return false;
2461
336k
}
2462
2463
/// Build an array type.
2464
///
2465
/// \param T The type of each element in the array.
2466
///
2467
/// \param ASM C99 array size modifier (e.g., '*', 'static').
2468
///
2469
/// \param ArraySize Expression describing the size of the array.
2470
///
2471
/// \param Brackets The range from the opening '[' to the closing ']'.
2472
///
2473
/// \param Entity The name of the entity that involves the array
2474
/// type, if known.
2475
///
2476
/// \returns A suitable array type, if there are no errors. Otherwise,
2477
/// returns a NULL type.
2478
QualType Sema::BuildArrayType(QualType T, ArraySizeModifier ASM,
2479
                              Expr *ArraySize, unsigned Quals,
2480
373k
                              SourceRange Brackets, DeclarationName Entity) {
2481
2482
373k
  SourceLocation Loc = Brackets.getBegin();
2483
373k
  if (getLangOpts().CPlusPlus) {
2484
    // C++ [dcl.array]p1:
2485
    //   T is called the array element type; this type shall not be a reference
2486
    //   type, the (possibly cv-qualified) type void, a function type or an
2487
    //   abstract class type.
2488
    //
2489
    // C++ [dcl.array]p3:
2490
    //   When several "array of" specifications are adjacent, [...] only the
2491
    //   first of the constant expressions that specify the bounds of the arrays
2492
    //   may be omitted.
2493
    //
2494
    // Note: function types are handled in the common path with C.
2495
194k
    if (T->isReferenceType()) {
2496
9
      Diag(Loc, diag::err_illegal_decl_array_of_references)
2497
9
      << getPrintableNameForEntity(Entity) << T;
2498
9
      return QualType();
2499
9
    }
2500
2501
194k
    if (T->isVoidType() || 
T->isIncompleteArrayType()194k
) {
2502
2
      Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 0 << T;
2503
2
      return QualType();
2504
2
    }
2505
2506
194k
    if (RequireNonAbstractType(Brackets.getBegin(), T,
2507
194k
                               diag::err_array_of_abstract_type))
2508
22
      return QualType();
2509
2510
    // Mentioning a member pointer type for an array type causes us to lock in
2511
    // an inheritance model, even if it's inside an unused typedef.
2512
194k
    if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2513
943
      if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2514
0
        if (!MPTy->getClass()->isDependentType())
2515
0
          (void)isCompleteType(Loc, T);
2516
2517
194k
  } else {
2518
    // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2519
    // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2520
178k
    if (!T.isWebAssemblyReferenceType() &&
2521
178k
        RequireCompleteSizedType(Loc, T,
2522
178k
                                 diag::err_array_incomplete_or_sizeless_type))
2523
74
      return QualType();
2524
178k
  }
2525
2526
  // Multi-dimensional arrays of WebAssembly references are not allowed.
2527
372k
  if (Context.getTargetInfo().getTriple().isWasm() && 
T->isArrayType()99
) {
2528
14
    const auto *ATy = dyn_cast<ArrayType>(T);
2529
14
    if (ATy && ATy->getElementType().isWebAssemblyReferenceType()) {
2530
14
      Diag(Loc, diag::err_wasm_reftype_multidimensional_array);
2531
14
      return QualType();
2532
14
    }
2533
14
  }
2534
2535
372k
  if (T->isSizelessType() && 
!T.isWebAssemblyReferenceType()95
) {
2536
19
    Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 1 << T;
2537
19
    return QualType();
2538
19
  }
2539
2540
372k
  if (T->isFunctionType()) {
2541
14
    Diag(Loc, diag::err_illegal_decl_array_of_functions)
2542
14
      << getPrintableNameForEntity(Entity) << T;
2543
14
    return QualType();
2544
14
  }
2545
2546
372k
  if (const RecordType *EltTy = T->getAs<RecordType>()) {
2547
    // If the element type is a struct or union that contains a variadic
2548
    // array, accept it as a GNU extension: C99 6.7.2.1p2.
2549
34.8k
    if (EltTy->getDecl()->hasFlexibleArrayMember())
2550
7
      Diag(Loc, diag::ext_flexible_array_in_array) << T;
2551
338k
  } else if (T->isObjCObjectType()) {
2552
1
    Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2553
1
    return QualType();
2554
1
  }
2555
2556
372k
  if (!checkArrayElementAlignment(T, Loc))
2557
19
    return QualType();
2558
2559
  // Do placeholder conversions on the array size expression.
2560
372k
  if (ArraySize && 
ArraySize->hasPlaceholderType()317k
) {
2561
2
    ExprResult Result = CheckPlaceholderExpr(ArraySize);
2562
2
    if (Result.isInvalid()) 
return QualType()0
;
2563
2
    ArraySize = Result.get();
2564
2
  }
2565
2566
  // Do lvalue-to-rvalue conversions on the array size expression.
2567
372k
  if (ArraySize && 
!ArraySize->isPRValue()317k
) {
2568
13.7k
    ExprResult Result = DefaultLvalueConversion(ArraySize);
2569
13.7k
    if (Result.isInvalid())
2570
0
      return QualType();
2571
2572
13.7k
    ArraySize = Result.get();
2573
13.7k
  }
2574
2575
  // C99 6.7.5.2p1: The size expression shall have integer type.
2576
  // C++11 allows contextual conversions to such types.
2577
372k
  if (!getLangOpts().CPlusPlus11 &&
2578
372k
      
ArraySize183k
&&
!ArraySize->isTypeDependent()156k
&&
2579
372k
      
!ArraySize->getType()->isIntegralOrUnscopedEnumerationType()156k
) {
2580
5
    Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2581
5
        << ArraySize->getType() << ArraySize->getSourceRange();
2582
5
    return QualType();
2583
5
  }
2584
2585
372k
  auto IsStaticAssertLike = [](const Expr *ArraySize, ASTContext &Context) {
2586
188k
    if (!ArraySize)
2587
28.7k
      return false;
2588
2589
    // If the array size expression is a conditional expression whose branches
2590
    // are both integer constant expressions, one negative and one positive,
2591
    // then it's assumed to be like an old-style static assertion. e.g.,
2592
    //   int old_style_assert[expr ? 1 : -1];
2593
    // We will accept any integer constant expressions instead of assuming the
2594
    // values 1 and -1 are always used.
2595
159k
    if (const auto *CondExpr = dyn_cast_if_present<ConditionalOperator>(
2596
159k
            ArraySize->IgnoreParenImpCasts())) {
2597
8.40k
      std::optional<llvm::APSInt> LHS =
2598
8.40k
          CondExpr->getLHS()->getIntegerConstantExpr(Context);
2599
8.40k
      std::optional<llvm::APSInt> RHS =
2600
8.40k
          CondExpr->getRHS()->getIntegerConstantExpr(Context);
2601
8.40k
      return LHS && 
RHS8.38k
&&
LHS->isNegative() != RHS->isNegative()8.36k
;
2602
8.40k
    }
2603
150k
    return false;
2604
159k
  };
2605
2606
  // VLAs always produce at least a -Wvla diagnostic, sometimes an error.
2607
372k
  unsigned VLADiag;
2608
372k
  bool VLAIsError;
2609
372k
  if (getLangOpts().OpenCL) {
2610
    // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2611
698
    VLADiag = diag::err_opencl_vla;
2612
698
    VLAIsError = true;
2613
372k
  } else if (getLangOpts().C99) {
2614
177k
    VLADiag = diag::warn_vla_used;
2615
177k
    VLAIsError = false;
2616
195k
  } else if (isSFINAEContext()) {
2617
1.32k
    VLADiag = diag::err_vla_in_sfinae;
2618
1.32k
    VLAIsError = true;
2619
193k
  } else if (getLangOpts().OpenMP && 
isInOpenMPTaskUntiedContext()36.1k
) {
2620
10
    VLADiag = diag::err_openmp_vla_in_task_untied;
2621
10
    VLAIsError = true;
2622
193k
  } else if (getLangOpts().CPlusPlus) {
2623
193k
    if (getLangOpts().CPlusPlus11 && 
IsStaticAssertLike(ArraySize, Context)188k
)
2624
7.71k
      VLADiag = getLangOpts().GNUMode
2625
7.71k
                    ? 
diag::ext_vla_cxx_in_gnu_mode_static_assert6.09k
2626
7.71k
                    : 
diag::ext_vla_cxx_static_assert1.61k
;
2627
185k
    else
2628
185k
      VLADiag = getLangOpts().GNUMode ? 
diag::ext_vla_cxx_in_gnu_mode32.1k
2629
185k
                                      : 
diag::ext_vla_cxx153k
;
2630
193k
    VLAIsError = false;
2631
193k
  } else {
2632
425
    VLADiag = diag::ext_vla;
2633
425
    VLAIsError = false;
2634
425
  }
2635
2636
372k
  llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2637
372k
  if (!ArraySize) {
2638
55.6k
    if (ASM == ArraySizeModifier::Star) {
2639
34
      Diag(Loc, VLADiag);
2640
34
      if (VLAIsError)
2641
0
        return QualType();
2642
2643
34
      T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2644
55.5k
    } else {
2645
55.5k
      T = Context.getIncompleteArrayType(T, ASM, Quals);
2646
55.5k
    }
2647
317k
  } else if (ArraySize->isTypeDependent() || 
ArraySize->isValueDependent()316k
) {
2648
22.6k
    T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2649
294k
  } else {
2650
294k
    ExprResult R =
2651
294k
        checkArraySize(*this, ArraySize, ConstVal, VLADiag, VLAIsError);
2652
294k
    if (R.isInvalid())
2653
25
      return QualType();
2654
2655
294k
    if (!R.isUsable()) {
2656
      // C99: an array with a non-ICE size is a VLA. We accept any expression
2657
      // that we can fold to a non-zero positive value as a non-VLA as an
2658
      // extension.
2659
3.96k
      T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2660
290k
    } else if (!T->isDependentType() && 
!T->isIncompleteType()279k
&&
2661
290k
               
!T->isConstantSizeType()279k
) {
2662
      // C99: an array with an element type that has a non-constant-size is a
2663
      // VLA.
2664
      // FIXME: Add a note to explain why this isn't a VLA.
2665
1.21k
      Diag(Loc, VLADiag);
2666
1.21k
      if (VLAIsError)
2667
0
        return QualType();
2668
1.21k
      T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2669
289k
    } else {
2670
      // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2671
      // have a value greater than zero.
2672
      // In C++, this follows from narrowing conversions being disallowed.
2673
289k
      if (ConstVal.isSigned() && 
ConstVal.isNegative()277k
) {
2674
156
        if (Entity)
2675
54
          Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size)
2676
54
              << getPrintableNameForEntity(Entity)
2677
54
              << ArraySize->getSourceRange();
2678
102
        else
2679
102
          Diag(ArraySize->getBeginLoc(),
2680
102
               diag::err_typecheck_negative_array_size)
2681
102
              << ArraySize->getSourceRange();
2682
156
        return QualType();
2683
156
      }
2684
289k
      if (ConstVal == 0 && 
!T.isWebAssemblyReferenceType()3.24k
) {
2685
        // GCC accepts zero sized static arrays. We allow them when
2686
        // we're not in a SFINAE context.
2687
3.18k
        Diag(ArraySize->getBeginLoc(),
2688
3.18k
             isSFINAEContext() ? 
diag::err_typecheck_zero_array_size3
2689
3.18k
                               : 
diag::ext_typecheck_zero_array_size3.18k
)
2690
3.18k
            << 0 << ArraySize->getSourceRange();
2691
3.18k
      }
2692
2693
      // Is the array too large?
2694
289k
      unsigned ActiveSizeBits =
2695
289k
          (!T->isDependentType() && 
!T->isVariablyModifiedType()277k
&&
2696
289k
           
!T->isIncompleteType()277k
&&
!T->isUndeducedType()277k
)
2697
289k
              ? 
ConstantArrayType::getNumAddressingBits(Context, T, ConstVal)277k
2698
289k
              : 
ConstVal.getActiveBits()11.5k
;
2699
289k
      if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2700
23
        Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2701
23
            << toString(ConstVal, 10) << ArraySize->getSourceRange();
2702
23
        return QualType();
2703
23
      }
2704
2705
289k
      T = Context.getConstantArrayType(T, ConstVal, ArraySize, ASM, Quals);
2706
289k
    }
2707
294k
  }
2708
2709
372k
  if (T->isVariableArrayType()) {
2710
5.20k
    if (!Context.getTargetInfo().isVLASupported()) {
2711
      // CUDA device code and some other targets don't support VLAs.
2712
30
      bool IsCUDADevice = (getLangOpts().CUDA && 
getLangOpts().CUDAIsDevice6
);
2713
30
      targetDiag(Loc,
2714
30
                 IsCUDADevice ? 
diag::err_cuda_vla6
:
diag::err_vla_unsupported24
)
2715
30
          << (IsCUDADevice ? 
CurrentCUDATarget()6
:
024
);
2716
5.17k
    } else if (sema::FunctionScopeInfo *FSI = getCurFunction()) {
2717
      // VLAs are supported on this target, but we may need to do delayed
2718
      // checking that the VLA is not being used within a coroutine.
2719
4.57k
      FSI->setHasVLA(Loc);
2720
4.57k
    }
2721
5.20k
  }
2722
2723
  // If this is not C99, diagnose array size modifiers on non-VLAs.
2724
372k
  if (!getLangOpts().C99 && 
!T->isVariableArrayType()195k
&&
2725
372k
      
(190k
ASM != ArraySizeModifier::Normal190k
||
Quals != 0190k
)) {
2726
6
    Diag(Loc, getLangOpts().CPlusPlus ? 
diag::err_c99_array_usage_cxx3
2727
6
                                      : 
diag::ext_c99_array_usage3
)
2728
6
        << llvm::to_underlying(ASM);
2729
6
  }
2730
2731
  // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2732
  // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2733
  // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2734
372k
  if (getLangOpts().OpenCL) {
2735
691
    const QualType ArrType = Context.getBaseElementType(T);
2736
691
    if (ArrType->isBlockPointerType() || 
ArrType->isPipeType()689
||
2737
691
        
ArrType->isSamplerT()689
||
ArrType->isImageType()683
) {
2738
12
      Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2739
12
      return QualType();
2740
12
    }
2741
691
  }
2742
2743
372k
  return T;
2744
372k
}
2745
2746
QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr,
2747
36.1k
                               SourceLocation AttrLoc) {
2748
  // The base type must be integer (not Boolean or enumeration) or float, and
2749
  // can't already be a vector.
2750
36.1k
  if ((!CurType->isDependentType() &&
2751
36.1k
       
(36.0k
!CurType->isBuiltinType()36.0k
||
CurType->isBooleanType()36.0k
||
2752
36.0k
        
(35.9k
!CurType->isIntegerType()35.9k
&&
!CurType->isRealFloatingType()16.2k
)) &&
2753
36.1k
       
!CurType->isBitIntType()74
) ||
2754
36.1k
      
CurType->isArrayType()36.0k
) {
2755
43
    Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType;
2756
43
    return QualType();
2757
43
  }
2758
  // Only support _BitInt elements with byte-sized power of 2 NumBits.
2759
36.0k
  if (const auto *BIT = CurType->getAs<BitIntType>()) {
2760
32
    unsigned NumBits = BIT->getNumBits();
2761
32
    if (!llvm::isPowerOf2_32(NumBits) || 
NumBits < 830
) {
2762
4
      Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type)
2763
4
          << (NumBits < 8);
2764
4
      return QualType();
2765
4
    }
2766
32
  }
2767
2768
36.0k
  if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
2769
40
    return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2770
40
                                          VectorKind::Generic);
2771
2772
36.0k
  std::optional<llvm::APSInt> VecSize =
2773
36.0k
      SizeExpr->getIntegerConstantExpr(Context);
2774
36.0k
  if (!VecSize) {
2775
0
    Diag(AttrLoc, diag::err_attribute_argument_type)
2776
0
        << "vector_size" << AANT_ArgumentIntegerConstant
2777
0
        << SizeExpr->getSourceRange();
2778
0
    return QualType();
2779
0
  }
2780
2781
36.0k
  if (CurType->isDependentType())
2782
22
    return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2783
22
                                          VectorKind::Generic);
2784
2785
  // vecSize is specified in bytes - convert to bits.
2786
36.0k
  if (!VecSize->isIntN(61)) {
2787
    // Bit size will overflow uint64.
2788
12
    Diag(AttrLoc, diag::err_attribute_size_too_large)
2789
12
        << SizeExpr->getSourceRange() << "vector";
2790
12
    return QualType();
2791
12
  }
2792
36.0k
  uint64_t VectorSizeBits = VecSize->getZExtValue() * 8;
2793
36.0k
  unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
2794
2795
36.0k
  if (VectorSizeBits == 0) {
2796
12
    Diag(AttrLoc, diag::err_attribute_zero_size)
2797
12
        << SizeExpr->getSourceRange() << "vector";
2798
12
    return QualType();
2799
12
  }
2800
2801
35.9k
  if (!TypeSize || 
VectorSizeBits % TypeSize35.9k
) {
2802
13
    Diag(AttrLoc, diag::err_attribute_invalid_size)
2803
13
        << SizeExpr->getSourceRange();
2804
13
    return QualType();
2805
13
  }
2806
2807
35.9k
  if (VectorSizeBits / TypeSize > std::numeric_limits<uint32_t>::max()) {
2808
24
    Diag(AttrLoc, diag::err_attribute_size_too_large)
2809
24
        << SizeExpr->getSourceRange() << "vector";
2810
24
    return QualType();
2811
24
  }
2812
2813
35.9k
  return Context.getVectorType(CurType, VectorSizeBits / TypeSize,
2814
35.9k
                               VectorKind::Generic);
2815
35.9k
}
2816
2817
/// Build an ext-vector type.
2818
///
2819
/// Run the required checks for the extended vector type.
2820
QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
2821
6.74k
                                  SourceLocation AttrLoc) {
2822
  // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2823
  // in conjunction with complex types (pointers, arrays, functions, etc.).
2824
  //
2825
  // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2826
  // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2827
  // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2828
  // of bool aren't allowed.
2829
  //
2830
  // We explictly allow bool elements in ext_vector_type for C/C++.
2831
6.74k
  bool IsNoBoolVecLang = getLangOpts().OpenCL || 
getLangOpts().OpenCLCPlusPlus2.12k
;
2832
6.74k
  if ((!T->isDependentType() && 
!T->isIntegerType()6.70k
&&
2833
6.74k
       
!T->isRealFloatingType()2.08k
) ||
2834
6.74k
      
(6.73k
IsNoBoolVecLang6.73k
&&
T->isBooleanType()4.61k
)) {
2835
16
    Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2836
16
    return QualType();
2837
16
  }
2838
2839
  // Only support _BitInt elements with byte-sized power of 2 NumBits.
2840
6.72k
  if (T->isBitIntType()) {
2841
32
    unsigned NumBits = T->castAs<BitIntType>()->getNumBits();
2842
32
    if (!llvm::isPowerOf2_32(NumBits) || 
NumBits < 830
) {
2843
4
      Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type)
2844
4
          << (NumBits < 8);
2845
4
      return QualType();
2846
4
    }
2847
32
  }
2848
2849
6.72k
  if (!ArraySize->isTypeDependent() && 
!ArraySize->isValueDependent()6.72k
) {
2850
6.68k
    std::optional<llvm::APSInt> vecSize =
2851
6.68k
        ArraySize->getIntegerConstantExpr(Context);
2852
6.68k
    if (!vecSize) {
2853
0
      Diag(AttrLoc, diag::err_attribute_argument_type)
2854
0
        << "ext_vector_type" << AANT_ArgumentIntegerConstant
2855
0
        << ArraySize->getSourceRange();
2856
0
      return QualType();
2857
0
    }
2858
2859
6.68k
    if (!vecSize->isIntN(32)) {
2860
6
      Diag(AttrLoc, diag::err_attribute_size_too_large)
2861
6
          << ArraySize->getSourceRange() << "vector";
2862
6
      return QualType();
2863
6
    }
2864
    // Unlike gcc's vector_size attribute, the size is specified as the
2865
    // number of elements, not the number of bytes.
2866
6.67k
    unsigned vectorSize = static_cast<unsigned>(vecSize->getZExtValue());
2867
2868
6.67k
    if (vectorSize == 0) {
2869
9
      Diag(AttrLoc, diag::err_attribute_zero_size)
2870
9
          << ArraySize->getSourceRange() << "vector";
2871
9
      return QualType();
2872
9
    }
2873
2874
6.66k
    return Context.getExtVectorType(T, vectorSize);
2875
6.67k
  }
2876
2877
42
  return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2878
6.72k
}
2879
2880
QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols,
2881
450
                               SourceLocation AttrLoc) {
2882
450
  assert(Context.getLangOpts().MatrixTypes &&
2883
450
         "Should never build a matrix type when it is disabled");
2884
2885
  // Check element type, if it is not dependent.
2886
450
  if (!ElementTy->isDependentType() &&
2887
450
      
!MatrixType::isValidElementType(ElementTy)406
) {
2888
6
    Diag(AttrLoc, diag::err_attribute_invalid_matrix_type) << ElementTy;
2889
6
    return QualType();
2890
6
  }
2891
2892
444
  if (NumRows->isTypeDependent() || 
NumCols->isTypeDependent()443
||
2893
444
      
NumRows->isValueDependent()443
||
NumCols->isValueDependent()389
)
2894
81
    return Context.getDependentSizedMatrixType(ElementTy, NumRows, NumCols,
2895
81
                                               AttrLoc);
2896
2897
363
  std::optional<llvm::APSInt> ValueRows =
2898
363
      NumRows->getIntegerConstantExpr(Context);
2899
363
  std::optional<llvm::APSInt> ValueColumns =
2900
363
      NumCols->getIntegerConstantExpr(Context);
2901
2902
363
  auto const RowRange = NumRows->getSourceRange();
2903
363
  auto const ColRange = NumCols->getSourceRange();
2904
2905
  // Both are row and column expressions are invalid.
2906
363
  if (!ValueRows && 
!ValueColumns2
) {
2907
1
    Diag(AttrLoc, diag::err_attribute_argument_type)
2908
1
        << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange
2909
1
        << ColRange;
2910
1
    return QualType();
2911
1
  }
2912
2913
  // Only the row expression is invalid.
2914
362
  if (!ValueRows) {
2915
1
    Diag(AttrLoc, diag::err_attribute_argument_type)
2916
1
        << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange;
2917
1
    return QualType();
2918
1
  }
2919
2920
  // Only the column expression is invalid.
2921
361
  if (!ValueColumns) {
2922
1
    Diag(AttrLoc, diag::err_attribute_argument_type)
2923
1
        << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange;
2924
1
    return QualType();
2925
1
  }
2926
2927
  // Check the matrix dimensions.
2928
360
  unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue());
2929
360
  unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue());
2930
360
  if (MatrixRows == 0 && 
MatrixColumns == 03
) {
2931
0
    Diag(AttrLoc, diag::err_attribute_zero_size)
2932
0
        << "matrix" << RowRange << ColRange;
2933
0
    return QualType();
2934
0
  }
2935
360
  if (MatrixRows == 0) {
2936
3
    Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << RowRange;
2937
3
    return QualType();
2938
3
  }
2939
357
  if (MatrixColumns == 0) {
2940
1
    Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << ColRange;
2941
1
    return QualType();
2942
1
  }
2943
356
  if (!ConstantMatrixType::isDimensionValid(MatrixRows)) {
2944
3
    Diag(AttrLoc, diag::err_attribute_size_too_large)
2945
3
        << RowRange << "matrix row";
2946
3
    return QualType();
2947
3
  }
2948
353
  if (!ConstantMatrixType::isDimensionValid(MatrixColumns)) {
2949
1
    Diag(AttrLoc, diag::err_attribute_size_too_large)
2950
1
        << ColRange << "matrix column";
2951
1
    return QualType();
2952
1
  }
2953
352
  return Context.getConstantMatrixType(ElementTy, MatrixRows, MatrixColumns);
2954
353
}
2955
2956
2.05M
bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2957
2.05M
  if (T->isArrayType() || 
T->isFunctionType()2.05M
) {
2958
26
    Diag(Loc, diag::err_func_returning_array_function)
2959
26
      << T->isFunctionType() << T;
2960
26
    return true;
2961
26
  }
2962
2963
  // Functions cannot return half FP.
2964
2.05M
  if (T->isHalfType() && 
!getLangOpts().NativeHalfArgsAndReturns0
&&
2965
2.05M
      
!Context.getTargetInfo().allowHalfArgsAndReturns()0
) {
2966
0
    Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2967
0
      FixItHint::CreateInsertion(Loc, "*");
2968
0
    return true;
2969
0
  }
2970
2971
  // Methods cannot return interface types. All ObjC objects are
2972
  // passed by reference.
2973
2.05M
  if (T->isObjCObjectType()) {
2974
3
    Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2975
3
        << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2976
3
    return true;
2977
3
  }
2978
2979
2.05M
  if (T.hasNonTrivialToPrimitiveDestructCUnion() ||
2980
2.05M
      
T.hasNonTrivialToPrimitiveCopyCUnion()2.05M
)
2981
2
    checkNonTrivialCUnion(T, Loc, NTCUC_FunctionReturn,
2982
2
                          NTCUK_Destruct|NTCUK_Copy);
2983
2984
  // C++2a [dcl.fct]p12:
2985
  //   A volatile-qualified return type is deprecated
2986
2.05M
  if (T.isVolatileQualified() && 
getLangOpts().CPlusPlus2040
)
2987
10
    Diag(Loc, diag::warn_deprecated_volatile_return) << T;
2988
2989
2.05M
  if (T.getAddressSpace() != LangAS::Default && 
getLangOpts().HLSL3
)
2990
1
    return true;
2991
2.05M
  return false;
2992
2.05M
}
2993
2994
/// Check the extended parameter information.  Most of the necessary
2995
/// checking should occur when applying the parameter attribute; the
2996
/// only other checks required are positional restrictions.
2997
static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes,
2998
                    const FunctionProtoType::ExtProtoInfo &EPI,
2999
8.95k
                    llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
3000
8.95k
  assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
3001
3002
8.95k
  bool emittedError = false;
3003
8.95k
  auto actualCC = EPI.ExtInfo.getCC();
3004
8.95k
  enum class RequiredCC { OnlySwift, SwiftOrSwiftAsync };
3005
8.95k
  auto checkCompatible = [&](unsigned paramIndex, RequiredCC required) {
3006
181
    bool isCompatible =
3007
181
        (required == RequiredCC::OnlySwift)
3008
181
            ? 
(actualCC == CC_Swift)34
3009
181
            : 
(147
actualCC == CC_Swift147
||
actualCC == CC_SwiftAsync21
);
3010
181
    if (isCompatible || 
emittedError9
)
3011
172
      return;
3012
9
    S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
3013
9
        << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI())
3014
9
        << (required == RequiredCC::OnlySwift);
3015
9
    emittedError = true;
3016
9
  };
3017
8.95k
  for (size_t paramIndex = 0, numParams = paramTypes.size();
3018
36.2k
          paramIndex != numParams; 
++paramIndex27.2k
) {
3019
27.2k
    switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
3020
    // Nothing interesting to check for orindary-ABI parameters.
3021
26.9k
    case ParameterABI::Ordinary:
3022
26.9k
      continue;
3023
3024
    // swift_indirect_result parameters must be a prefix of the function
3025
    // arguments.
3026
83
    case ParameterABI::SwiftIndirectResult:
3027
83
      checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
3028
83
      if (paramIndex != 0 &&
3029
83
          EPI.ExtParameterInfos[paramIndex - 1].getABI()
3030
33
            != ParameterABI::SwiftIndirectResult) {
3031
3
        S.Diag(getParamLoc(paramIndex),
3032
3
               diag::err_swift_indirect_result_not_first);
3033
3
      }
3034
83
      continue;
3035
3036
64
    case ParameterABI::SwiftContext:
3037
64
      checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
3038
64
      continue;
3039
3040
    // SwiftAsyncContext is not limited to swiftasynccall functions.
3041
149
    case ParameterABI::SwiftAsyncContext:
3042
149
      continue;
3043
3044
    // swift_error parameters must be preceded by a swift_context parameter.
3045
34
    case ParameterABI::SwiftErrorResult:
3046
34
      checkCompatible(paramIndex, RequiredCC::OnlySwift);
3047
34
      if (paramIndex == 0 ||
3048
34
          EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
3049
31
              ParameterABI::SwiftContext) {
3050
6
        S.Diag(getParamLoc(paramIndex),
3051
6
               diag::err_swift_error_result_not_after_swift_context);
3052
6
      }
3053
34
      continue;
3054
27.2k
    }
3055
0
    llvm_unreachable("bad ABI kind");
3056
0
  }
3057
8.95k
}
3058
3059
QualType Sema::BuildFunctionType(QualType T,
3060
                                 MutableArrayRef<QualType> ParamTypes,
3061
                                 SourceLocation Loc, DeclarationName Entity,
3062
1.39M
                                 const FunctionProtoType::ExtProtoInfo &EPI) {
3063
1.39M
  bool Invalid = false;
3064
3065
1.39M
  Invalid |= CheckFunctionReturnType(T, Loc);
3066
3067
3.51M
  for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; 
++Idx2.11M
) {
3068
    // FIXME: Loc is too inprecise here, should use proper locations for args.
3069
2.11M
    QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
3070
2.11M
    if (ParamType->isVoidType()) {
3071
0
      Diag(Loc, diag::err_param_with_void_type);
3072
0
      Invalid = true;
3073
2.11M
    } else if (ParamType->isHalfType() && 
!getLangOpts().NativeHalfArgsAndReturns0
&&
3074
2.11M
               
!Context.getTargetInfo().allowHalfArgsAndReturns()0
) {
3075
      // Disallow half FP arguments.
3076
0
      Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
3077
0
        FixItHint::CreateInsertion(Loc, "*");
3078
0
      Invalid = true;
3079
2.11M
    } else if (ParamType->isWebAssemblyTableType()) {
3080
0
      Diag(Loc, diag::err_wasm_table_as_function_parameter);
3081
0
      Invalid = true;
3082
0
    }
3083
3084
    // C++2a [dcl.fct]p4:
3085
    //   A parameter with volatile-qualified type is deprecated
3086
2.11M
    if (ParamType.isVolatileQualified() && 
getLangOpts().CPlusPlus2012
)
3087
2
      Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType;
3088
3089
2.11M
    ParamTypes[Idx] = ParamType;
3090
2.11M
  }
3091
3092
1.39M
  if (EPI.ExtParameterInfos) {
3093
86
    checkExtParameterInfos(*this, ParamTypes, EPI,
3094
86
                           [=](unsigned i) 
{ return Loc; }0
);
3095
86
  }
3096
3097
1.39M
  if (EPI.ExtInfo.getProducesResult()) {
3098
    // This is just a warning, so we can't fail to build if we see it.
3099
18
    checkNSReturnsRetainedReturnType(Loc, T);
3100
18
  }
3101
3102
1.39M
  if (Invalid)
3103
26
    return QualType();
3104
3105
1.39M
  return Context.getFunctionType(T, ParamTypes, EPI);
3106
1.39M
}
3107
3108
/// Build a member pointer type \c T Class::*.
3109
///
3110
/// \param T the type to which the member pointer refers.
3111
/// \param Class the class type into which the member pointer points.
3112
/// \param Loc the location where this type begins
3113
/// \param Entity the name of the entity that will have this member pointer type
3114
///
3115
/// \returns a member pointer type, if successful, or a NULL type if there was
3116
/// an error.
3117
QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
3118
                                      SourceLocation Loc,
3119
33.3k
                                      DeclarationName Entity) {
3120
  // Verify that we're not building a pointer to pointer to function with
3121
  // exception specification.
3122
33.3k
  if (CheckDistantExceptionSpec(T)) {
3123
0
    Diag(Loc, diag::err_distant_exception_spec);
3124
0
    return QualType();
3125
0
  }
3126
3127
  // C++ 8.3.3p3: A pointer to member shall not point to ... a member
3128
  //   with reference type, or "cv void."
3129
33.3k
  if (T->isReferenceType()) {
3130
2
    Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
3131
2
      << getPrintableNameForEntity(Entity) << T;
3132
2
    return QualType();
3133
2
  }
3134
3135
33.3k
  if (T->isVoidType()) {
3136
3
    Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
3137
3
      << getPrintableNameForEntity(Entity);
3138
3
    return QualType();
3139
3
  }
3140
3141
33.2k
  if (!Class->isDependentType() && 
!Class->isRecordType()4.60k
) {
3142
106
    Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
3143
106
    return QualType();
3144
106
  }
3145
3146
33.1k
  if (T->isFunctionType() && 
getLangOpts().OpenCL27.6k
&&
3147
33.1k
      !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
3148
4
                                            getLangOpts())) {
3149
2
    Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
3150
2
    return QualType();
3151
2
  }
3152
3153
33.1k
  if (getLangOpts().HLSL && 
Loc.isValid()2
) {
3154
2
    Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
3155
2
    return QualType();
3156
2
  }
3157
3158
  // Adjust the default free function calling convention to the default method
3159
  // calling convention.
3160
33.1k
  bool IsCtorOrDtor =
3161
33.1k
      (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
3162
33.1k
      (Entity.getNameKind() == DeclarationName::CXXDestructorName);
3163
33.1k
  if (T->isFunctionType())
3164
27.6k
    adjustMemberFunctionCC(T, /*HasThisPointer=*/true, IsCtorOrDtor, Loc);
3165
3166
33.1k
  return Context.getMemberPointerType(T, Class.getTypePtr());
3167
33.1k
}
3168
3169
/// Build a block pointer type.
3170
///
3171
/// \param T The type to which we'll be building a block pointer.
3172
///
3173
/// \param Loc The source location, used for diagnostics.
3174
///
3175
/// \param Entity The name of the entity that involves the block pointer
3176
/// type, if known.
3177
///
3178
/// \returns A suitable block pointer type, if there are no
3179
/// errors. Otherwise, returns a NULL type.
3180
QualType Sema::BuildBlockPointerType(QualType T,
3181
                                     SourceLocation Loc,
3182
61.4k
                                     DeclarationName Entity) {
3183
61.4k
  if (!T->isFunctionType()) {
3184
11
    Diag(Loc, diag::err_nonfunction_block_type);
3185
11
    return QualType();
3186
11
  }
3187
3188
61.4k
  if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
3189
0
    return QualType();
3190
3191
61.4k
  if (getLangOpts().OpenCL)
3192
163
    T = deduceOpenCLPointeeAddrSpace(*this, T);
3193
3194
61.4k
  return Context.getBlockPointerType(T);
3195
61.4k
}
3196
3197
297M
QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
3198
297M
  QualType QT = Ty.get();
3199
297M
  if (QT.isNull()) {
3200
2.31M
    if (TInfo) 
*TInfo = nullptr162
;
3201
2.31M
    return QualType();
3202
2.31M
  }
3203
3204
295M
  TypeSourceInfo *DI = nullptr;
3205
295M
  if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
3206
21.5M
    QT = LIT->getType();
3207
21.5M
    DI = LIT->getTypeSourceInfo();
3208
21.5M
  }
3209
3210
295M
  if (TInfo) 
*TInfo = DI152M
;
3211
295M
  return QT;
3212
297M
}
3213
3214
static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
3215
                                            Qualifiers::ObjCLifetime ownership,
3216
                                            unsigned chunkIndex);
3217
3218
/// Given that this is the declaration of a parameter under ARC,
3219
/// attempt to infer attributes and such for pointer-to-whatever
3220
/// types.
3221
static void inferARCWriteback(TypeProcessingState &state,
3222
163k
                              QualType &declSpecType) {
3223
163k
  Sema &S = state.getSema();
3224
163k
  Declarator &declarator = state.getDeclarator();
3225
3226
  // TODO: should we care about decl qualifiers?
3227
3228
  // Check whether the declarator has the expected form.  We walk
3229
  // from the inside out in order to make the block logic work.
3230
163k
  unsigned outermostPointerIndex = 0;
3231
163k
  bool isBlockPointer = false;
3232
163k
  unsigned numPointers = 0;
3233
221k
  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; 
++i57.8k
) {
3234
59.5k
    unsigned chunkIndex = i;
3235
59.5k
    DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
3236
59.5k
    switch (chunk.Kind) {
3237
270
    case DeclaratorChunk::Paren:
3238
      // Ignore parens.
3239
270
      break;
3240
3241
8.05k
    case DeclaratorChunk::Reference:
3242
57.5k
    case DeclaratorChunk::Pointer:
3243
      // Count the number of pointers.  Treat references
3244
      // interchangeably as pointers; if they're mis-ordered, normal
3245
      // type building will discover that.
3246
57.5k
      outermostPointerIndex = chunkIndex;
3247
57.5k
      numPointers++;
3248
57.5k
      break;
3249
3250
804
    case DeclaratorChunk::BlockPointer:
3251
      // If we have a pointer to block pointer, that's an acceptable
3252
      // indirect reference; anything else is not an application of
3253
      // the rules.
3254
804
      if (numPointers != 1) return;
3255
0
      numPointers++;
3256
0
      outermostPointerIndex = chunkIndex;
3257
0
      isBlockPointer = true;
3258
3259
      // We don't care about pointer structure in return values here.
3260
0
      goto done;
3261
3262
682
    case DeclaratorChunk::Array: // suppress if written (id[])?
3263
944
    case DeclaratorChunk::Function:
3264
950
    case DeclaratorChunk::MemberPointer:
3265
950
    case DeclaratorChunk::Pipe:
3266
950
      return;
3267
59.5k
    }
3268
59.5k
  }
3269
161k
 done:
3270
3271
  // If we have *one* pointer, then we want to throw the qualifier on
3272
  // the declaration-specifiers, which means that it needs to be a
3273
  // retainable object type.
3274
161k
  if (numPointers == 1) {
3275
    // If it's not a retainable object type, the rule doesn't apply.
3276
53.6k
    if (!declSpecType->isObjCRetainableType()) 
return53.3k
;
3277
3278
    // If it already has lifetime, don't do anything.
3279
235
    if (declSpecType.getObjCLifetime()) 
return133
;
3280
3281
    // Otherwise, modify the type in-place.
3282
102
    Qualifiers qs;
3283
3284
102
    if (declSpecType->isObjCARCImplicitlyUnretainedType())
3285
4
      qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
3286
98
    else
3287
98
      qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
3288
102
    declSpecType = S.Context.getQualifiedType(declSpecType, qs);
3289
3290
  // If we have *two* pointers, then we want to throw the qualifier on
3291
  // the outermost pointer.
3292
108k
  } else if (numPointers == 2) {
3293
    // If we don't have a block pointer, we need to check whether the
3294
    // declaration-specifiers gave us something that will turn into a
3295
    // retainable object pointer after we slap the first pointer on it.
3296
1.80k
    if (!isBlockPointer && !declSpecType->isObjCObjectType())
3297
962
      return;
3298
3299
    // Look for an explicit lifetime attribute there.
3300
845
    DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
3301
845
    if (chunk.Kind != DeclaratorChunk::Pointer &&
3302
845
        
chunk.Kind != DeclaratorChunk::BlockPointer1
)
3303
1
      return;
3304
844
    for (const ParsedAttr &AL : chunk.getAttrs())
3305
263
      if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
3306
91
        return;
3307
3308
753
    transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
3309
753
                                          outermostPointerIndex);
3310
3311
  // Any other number of pointers/references does not trigger the rule.
3312
106k
  } else return;
3313
3314
  // TODO: mark whether we did this inference?
3315
161k
}
3316
3317
void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
3318
                                     SourceLocation FallbackLoc,
3319
                                     SourceLocation ConstQualLoc,
3320
                                     SourceLocation VolatileQualLoc,
3321
                                     SourceLocation RestrictQualLoc,
3322
                                     SourceLocation AtomicQualLoc,
3323
365
                                     SourceLocation UnalignedQualLoc) {
3324
365
  if (!Quals)
3325
19
    return;
3326
3327
346
  struct Qual {
3328
346
    const char *Name;
3329
346
    unsigned Mask;
3330
346
    SourceLocation Loc;
3331
346
  } const QualKinds[5] = {
3332
346
    { "const", DeclSpec::TQ_const, ConstQualLoc },
3333
346
    { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
3334
346
    { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
3335
346
    { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
3336
346
    { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
3337
346
  };
3338
3339
346
  SmallString<32> QualStr;
3340
346
  unsigned NumQuals = 0;
3341
346
  SourceLocation Loc;
3342
346
  FixItHint FixIts[5];
3343
3344
  // Build a string naming the redundant qualifiers.
3345
1.73k
  for (auto &E : QualKinds) {
3346
1.73k
    if (Quals & E.Mask) {
3347
376
      if (!QualStr.empty()) 
QualStr += ' '30
;
3348
376
      QualStr += E.Name;
3349
3350
      // If we have a location for the qualifier, offer a fixit.
3351
376
      SourceLocation QualLoc = E.Loc;
3352
376
      if (QualLoc.isValid()) {
3353
347
        FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
3354
347
        if (Loc.isInvalid() ||
3355
347
            
getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc)29
)
3356
319
          Loc = QualLoc;
3357
347
      }
3358
3359
376
      ++NumQuals;
3360
376
    }
3361
1.73k
  }
3362
3363
346
  Diag(Loc.isInvalid() ? 
FallbackLoc28
:
Loc318
, DiagID)
3364
346
    << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
3365
346
}
3366
3367
// Diagnose pointless type qualifiers on the return type of a function.
3368
static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
3369
                                                  Declarator &D,
3370
377
                                                  unsigned FunctionChunkIndex) {
3371
377
  const DeclaratorChunk::FunctionTypeInfo &FTI =
3372
377
      D.getTypeObject(FunctionChunkIndex).Fun;
3373
377
  if (FTI.hasTrailingReturnType()) {
3374
18
    S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3375
18
                                RetTy.getLocalCVRQualifiers(),
3376
18
                                FTI.getTrailingReturnTypeLoc());
3377
18
    return;
3378
18
  }
3379
3380
359
  for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
3381
359
                End = D.getNumTypeObjects();
3382
362
       OuterChunkIndex != End; 
++OuterChunkIndex3
) {
3383
35
    DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
3384
35
    switch (OuterChunk.Kind) {
3385
3
    case DeclaratorChunk::Paren:
3386
3
      continue;
3387
3388
22
    case DeclaratorChunk::Pointer: {
3389
22
      DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
3390
22
      S.diagnoseIgnoredQualifiers(
3391
22
          diag::warn_qual_return_type,
3392
22
          PTI.TypeQuals,
3393
22
          SourceLocation(),
3394
22
          PTI.ConstQualLoc,
3395
22
          PTI.VolatileQualLoc,
3396
22
          PTI.RestrictQualLoc,
3397
22
          PTI.AtomicQualLoc,
3398
22
          PTI.UnalignedQualLoc);
3399
22
      return;
3400
0
    }
3401
3402
0
    case DeclaratorChunk::Function:
3403
0
    case DeclaratorChunk::BlockPointer:
3404
1
    case DeclaratorChunk::Reference:
3405
1
    case DeclaratorChunk::Array:
3406
10
    case DeclaratorChunk::MemberPointer:
3407
10
    case DeclaratorChunk::Pipe:
3408
      // FIXME: We can't currently provide an accurate source location and a
3409
      // fix-it hint for these.
3410
10
      unsigned AtomicQual = RetTy->isAtomicType() ? 
DeclSpec::TQ_atomic0
: 0;
3411
10
      S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3412
10
                                  RetTy.getCVRQualifiers() | AtomicQual,
3413
10
                                  D.getIdentifierLoc());
3414
10
      return;
3415
35
    }
3416
3417
0
    llvm_unreachable("unknown declarator chunk kind");
3418
0
  }
3419
3420
  // If the qualifiers come from a conversion function type, don't diagnose
3421
  // them -- they're not necessarily redundant, since such a conversion
3422
  // operator can be explicitly called as "x.operator const int()".
3423
327
  if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3424
15
    return;
3425
3426
  // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
3427
  // which are present there.
3428
312
  S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3429
312
                              D.getDeclSpec().getTypeQualifiers(),
3430
312
                              D.getIdentifierLoc(),
3431
312
                              D.getDeclSpec().getConstSpecLoc(),
3432
312
                              D.getDeclSpec().getVolatileSpecLoc(),
3433
312
                              D.getDeclSpec().getRestrictSpecLoc(),
3434
312
                              D.getDeclSpec().getAtomicSpecLoc(),
3435
312
                              D.getDeclSpec().getUnalignedSpecLoc());
3436
312
}
3437
3438
static std::pair<QualType, TypeSourceInfo *>
3439
InventTemplateParameter(TypeProcessingState &state, QualType T,
3440
                        TypeSourceInfo *TrailingTSI, AutoType *Auto,
3441
3.28k
                        InventedTemplateParameterInfo &Info) {
3442
3.28k
  Sema &S = state.getSema();
3443
3.28k
  Declarator &D = state.getDeclarator();
3444
3445
3.28k
  const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth;
3446
3.28k
  const unsigned AutoParameterPosition = Info.TemplateParams.size();
3447
3.28k
  const bool IsParameterPack = D.hasEllipsis();
3448
3449
  // If auto is mentioned in a lambda parameter or abbreviated function
3450
  // template context, convert it to a template parameter type.
3451
3452
  // Create the TemplateTypeParmDecl here to retrieve the corresponding
3453
  // template parameter type. Template parameters are temporarily added
3454
  // to the TU until the associated TemplateDecl is created.
3455
3.28k
  TemplateTypeParmDecl *InventedTemplateParam =
3456
3.28k
      TemplateTypeParmDecl::Create(
3457
3.28k
          S.Context, S.Context.getTranslationUnitDecl(),
3458
3.28k
          /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(),
3459
3.28k
          /*NameLoc=*/D.getIdentifierLoc(),
3460
3.28k
          TemplateParameterDepth, AutoParameterPosition,
3461
3.28k
          S.InventAbbreviatedTemplateParameterTypeName(
3462
3.28k
              D.getIdentifier(), AutoParameterPosition), false,
3463
3.28k
          IsParameterPack, /*HasTypeConstraint=*/Auto->isConstrained());
3464
3.28k
  InventedTemplateParam->setImplicit();
3465
3.28k
  Info.TemplateParams.push_back(InventedTemplateParam);
3466
3467
  // Attach type constraints to the new parameter.
3468
3.28k
  if (Auto->isConstrained()) {
3469
220
    if (TrailingTSI) {
3470
      // The 'auto' appears in a trailing return type we've already built;
3471
      // extract its type constraints to attach to the template parameter.
3472
0
      AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc();
3473
0
      TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc());
3474
0
      bool Invalid = false;
3475
0
      for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx) {
3476
0
        if (D.getEllipsisLoc().isInvalid() && !Invalid &&
3477
0
            S.DiagnoseUnexpandedParameterPack(AutoLoc.getArgLoc(Idx),
3478
0
                                              Sema::UPPC_TypeConstraint))
3479
0
          Invalid = true;
3480
0
        TAL.addArgument(AutoLoc.getArgLoc(Idx));
3481
0
      }
3482
3483
0
      if (!Invalid) {
3484
0
        S.AttachTypeConstraint(
3485
0
            AutoLoc.getNestedNameSpecifierLoc(), AutoLoc.getConceptNameInfo(),
3486
0
            AutoLoc.getNamedConcept(),
3487
0
            AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr,
3488
0
            InventedTemplateParam, D.getEllipsisLoc());
3489
0
      }
3490
220
    } else {
3491
      // The 'auto' appears in the decl-specifiers; we've not finished forming
3492
      // TypeSourceInfo for it yet.
3493
220
      TemplateIdAnnotation *TemplateId = D.getDeclSpec().getRepAsTemplateId();
3494
220
      TemplateArgumentListInfo TemplateArgsInfo;
3495
220
      bool Invalid = false;
3496
220
      if (TemplateId->LAngleLoc.isValid()) {
3497
150
        ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
3498
150
                                           TemplateId->NumArgs);
3499
150
        S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
3500
3501
150
        if (D.getEllipsisLoc().isInvalid()) {
3502
142
          for (TemplateArgumentLoc Arg : TemplateArgsInfo.arguments()) {
3503
142
            if (S.DiagnoseUnexpandedParameterPack(Arg,
3504
142
                                                  Sema::UPPC_TypeConstraint)) {
3505
2
              Invalid = true;
3506
2
              break;
3507
2
            }
3508
142
          }
3509
142
        }
3510
150
      }
3511
220
      if (!Invalid) {
3512
218
        S.AttachTypeConstraint(
3513
218
            D.getDeclSpec().getTypeSpecScope().getWithLocInContext(S.Context),
3514
218
            DeclarationNameInfo(DeclarationName(TemplateId->Name),
3515
218
                                TemplateId->TemplateNameLoc),
3516
218
            cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl()),
3517
218
            TemplateId->LAngleLoc.isValid() ? 
&TemplateArgsInfo148
:
nullptr70
,
3518
218
            InventedTemplateParam, D.getEllipsisLoc());
3519
218
      }
3520
220
    }
3521
220
  }
3522
3523
  // Replace the 'auto' in the function parameter with this invented
3524
  // template type parameter.
3525
  // FIXME: Retain some type sugar to indicate that this was written
3526
  //  as 'auto'?
3527
3.28k
  QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0);
3528
3.28k
  QualType NewT = state.ReplaceAutoType(T, Replacement);
3529
3.28k
  TypeSourceInfo *NewTSI =
3530
3.28k
      TrailingTSI ? 
S.ReplaceAutoTypeSourceInfo(TrailingTSI, Replacement)8
3531
3.28k
                  : 
nullptr3.27k
;
3532
3.28k
  return {NewT, NewTSI};
3533
3.28k
}
3534
3535
static TypeSourceInfo *
3536
GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3537
                               QualType T, TypeSourceInfo *ReturnTypeInfo);
3538
3539
static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
3540
155M
                                             TypeSourceInfo *&ReturnTypeInfo) {
3541
155M
  Sema &SemaRef = state.getSema();
3542
155M
  Declarator &D = state.getDeclarator();
3543
155M
  QualType T;
3544
155M
  ReturnTypeInfo = nullptr;
3545
3546
  // The TagDecl owned by the DeclSpec.
3547
155M
  TagDecl *OwnedTagDecl = nullptr;
3548
3549
155M
  switch (D.getName().getKind()) {
3550
0
  case UnqualifiedIdKind::IK_ImplicitSelfParam:
3551
489k
  case UnqualifiedIdKind::IK_OperatorFunctionId:
3552
155M
  case UnqualifiedIdKind::IK_Identifier:
3553
155M
  case UnqualifiedIdKind::IK_LiteralOperatorId:
3554
155M
  case UnqualifiedIdKind::IK_TemplateId:
3555
155M
    T = ConvertDeclSpecToType(state);
3556
3557
155M
    if (!D.isInvalidType() && 
D.getDeclSpec().isTypeSpecOwned()155M
) {
3558
450k
      OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3559
      // Owned declaration is embedded in declarator.
3560
450k
      OwnedTagDecl->setEmbeddedInDeclarator(true);
3561
450k
    }
3562
155M
    break;
3563
3564
419k
  case UnqualifiedIdKind::IK_ConstructorName:
3565
419k
  case UnqualifiedIdKind::IK_ConstructorTemplateId:
3566
488k
  case UnqualifiedIdKind::IK_DestructorName:
3567
    // Constructors and destructors don't have return types. Use
3568
    // "void" instead.
3569
488k
    T = SemaRef.Context.VoidTy;
3570
488k
    processTypeAttrs(state, T, TAL_DeclSpec,
3571
488k
                     D.getMutableDeclSpec().getAttributes());
3572
488k
    break;
3573
3574
1.61k
  case UnqualifiedIdKind::IK_DeductionGuideName:
3575
    // Deduction guides have a trailing return type and no type in their
3576
    // decl-specifier sequence. Use a placeholder return type for now.
3577
1.61k
    T = SemaRef.Context.DependentTy;
3578
1.61k
    break;
3579
3580
17.2k
  case UnqualifiedIdKind::IK_ConversionFunctionId:
3581
    // The result type of a conversion function is the type that it
3582
    // converts to.
3583
17.2k
    T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
3584
17.2k
                                  &ReturnTypeInfo);
3585
17.2k
    break;
3586
155M
  }
3587
3588
  // Note: We don't need to distribute declaration attributes (i.e.
3589
  // D.getDeclarationAttributes()) because those are always C++11 attributes,
3590
  // and those don't get distributed.
3591
155M
  distributeTypeAttrsFromDeclarator(
3592
155M
      state, T, SemaRef.IdentifyCUDATarget(D.getAttributes()));
3593
3594
  // Find the deduced type in this type. Look in the trailing return type if we
3595
  // have one, otherwise in the DeclSpec type.
3596
  // FIXME: The standard wording doesn't currently describe this.
3597
155M
  DeducedType *Deduced = T->getContainedDeducedType();
3598
155M
  bool DeducedIsTrailingReturnType = false;
3599
155M
  if (Deduced && 
isa<AutoType>(Deduced)102k
&&
D.hasTrailingReturnType()99.8k
) {
3600
11.8k
    QualType T = SemaRef.GetTypeFromParser(D.getTrailingReturnType());
3601
11.8k
    Deduced = T.isNull() ? 
nullptr67
:
T->getContainedDeducedType()11.8k
;
3602
11.8k
    DeducedIsTrailingReturnType = true;
3603
11.8k
  }
3604
3605
  // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
3606
155M
  if (Deduced) {
3607
90.4k
    AutoType *Auto = dyn_cast<AutoType>(Deduced);
3608
90.4k
    int Error = -1;
3609
3610
    // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
3611
    // class template argument deduction)?
3612
90.4k
    bool IsCXXAutoType =
3613
90.4k
        (Auto && 
Auto->getKeyword() != AutoTypeKeyword::GNUAutoType88.2k
);
3614
90.4k
    bool IsDeducedReturnType = false;
3615
3616
90.4k
    switch (D.getContext()) {
3617
4.56k
    case DeclaratorContext::LambdaExpr:
3618
      // Declared return type of a lambda-declarator is implicit and is always
3619
      // 'auto'.
3620
4.56k
      break;
3621
0
    case DeclaratorContext::ObjCParameter:
3622
0
    case DeclaratorContext::ObjCResult:
3623
0
      Error = 0;
3624
0
      break;
3625
2
    case DeclaratorContext::RequiresExpr:
3626
2
      Error = 22;
3627
2
      break;
3628
575
    case DeclaratorContext::Prototype:
3629
3.31k
    case DeclaratorContext::LambdaExprParameter: {
3630
3.31k
      InventedTemplateParameterInfo *Info = nullptr;
3631
3.31k
      if (D.getContext() == DeclaratorContext::Prototype) {
3632
        // With concepts we allow 'auto' in function parameters.
3633
575
        if (!SemaRef.getLangOpts().CPlusPlus20 || 
!Auto555
||
3634
575
            
Auto->getKeyword() != AutoTypeKeyword::Auto552
) {
3635
27
          Error = 0;
3636
27
          break;
3637
548
        } else if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) {
3638
5
          Error = 21;
3639
5
          break;
3640
5
        }
3641
3642
543
        Info = &SemaRef.InventedParameterInfos.back();
3643
2.74k
      } else {
3644
        // In C++14, generic lambdas allow 'auto' in their parameters.
3645
2.74k
        if (!SemaRef.getLangOpts().CPlusPlus14 || 
!Auto2.73k
||
3646
2.74k
            
Auto->getKeyword() != AutoTypeKeyword::Auto2.73k
) {
3647
4
          Error = 16;
3648
4
          break;
3649
4
        }
3650
2.73k
        Info = SemaRef.getCurLambda();
3651
2.73k
        assert(Info && "No LambdaScopeInfo on the stack!");
3652
2.73k
      }
3653
3654
      // We'll deal with inventing template parameters for 'auto' in trailing
3655
      // return types when we pick up the trailing return type when processing
3656
      // the function chunk.
3657
3.28k
      if (!DeducedIsTrailingReturnType)
3658
3.27k
        T = InventTemplateParameter(state, T, nullptr, Auto, *Info).first;
3659
3.28k
      break;
3660
3.31k
    }
3661
2.28k
    case DeclaratorContext::Member: {
3662
2.28k
      if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
3663
2.28k
          
D.isFunctionDeclarator()1.42k
)
3664
2.25k
        break;
3665
36
      bool Cxx = SemaRef.getLangOpts().CPlusPlus;
3666
36
      if (isa<ObjCContainerDecl>(SemaRef.CurContext)) {
3667
4
        Error = 6; // Interface member.
3668
32
      } else {
3669
32
        switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
3670
0
        case TagTypeKind::Enum:
3671
0
          llvm_unreachable("unhandled tag kind");
3672
25
        case TagTypeKind::Struct:
3673
25
          Error = Cxx ? 
121
:
24
; /* Struct member */
3674
25
          break;
3675
1
        case TagTypeKind::Union:
3676
1
          Error = Cxx ? 
30
: 4; /* Union member */
3677
1
          break;
3678
6
        case TagTypeKind::Class:
3679
6
          Error = 5; /* Class member */
3680
6
          break;
3681
0
        case TagTypeKind::Interface:
3682
0
          Error = 6; /* Interface member */
3683
0
          break;
3684
32
        }
3685
32
      }
3686
36
      if (D.getDeclSpec().isFriendSpecified())
3687
11
        Error = 20; // Friend type
3688
36
      break;
3689
36
    }
3690
9
    case DeclaratorContext::CXXCatch:
3691
10
    case DeclaratorContext::ObjCCatch:
3692
10
      Error = 7; // Exception declaration
3693
10
      break;
3694
291
    case DeclaratorContext::TemplateParam:
3695
291
      if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3696
291
          
!SemaRef.getLangOpts().CPlusPlus2020
)
3697
2
        Error = 19; // Template parameter (until C++20)
3698
289
      else if (!SemaRef.getLangOpts().CPlusPlus17)
3699
5
        Error = 8; // Template parameter (until C++17)
3700
291
      break;
3701
0
    case DeclaratorContext::BlockLiteral:
3702
0
      Error = 9; // Block literal
3703
0
      break;
3704
1.34k
    case DeclaratorContext::TemplateArg:
3705
      // Within a template argument list, a deduced template specialization
3706
      // type will be reinterpreted as a template template argument.
3707
1.34k
      if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3708
1.34k
          
!D.getNumTypeObjects()1.33k
&&
3709
1.34k
          
D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier1.33k
)
3710
1.33k
        break;
3711
1.34k
      
[[fallthrough]];16
3712
17
    case DeclaratorContext::TemplateTypeArg:
3713
17
      Error = 10; // Template type argument
3714
17
      break;
3715
13
    case DeclaratorContext::AliasDecl:
3716
13
    case DeclaratorContext::AliasTemplate:
3717
13
      Error = 12; // Type alias
3718
13
      break;
3719
233
    case DeclaratorContext::TrailingReturn:
3720
284
    case DeclaratorContext::TrailingReturnVar:
3721
284
      if (!SemaRef.getLangOpts().CPlusPlus14 || 
!IsCXXAutoType276
)
3722
9
        Error = 13; // Function return type
3723
284
      IsDeducedReturnType = true;
3724
284
      break;
3725
140
    case DeclaratorContext::ConversionId:
3726
140
      if (!SemaRef.getLangOpts().CPlusPlus14 || 
!IsCXXAutoType138
)
3727
6
        Error = 14; // conversion-type-id
3728
140
      IsDeducedReturnType = true;
3729
140
      break;
3730
407
    case DeclaratorContext::FunctionalCast:
3731
407
      if (isa<DeducedTemplateSpecializationType>(Deduced))
3732
345
        break;
3733
62
      if (SemaRef.getLangOpts().CPlusPlus23 && 
IsCXXAutoType58
&&
3734
62
          
!Auto->isDecltypeAuto()58
)
3735
58
        break; // auto(x)
3736
62
      
[[fallthrough]];4
3737
46
    case DeclaratorContext::TypeName:
3738
49
    case DeclaratorContext::Association:
3739
49
      Error = 15; // Generic
3740
49
      break;
3741
6.23k
    case DeclaratorContext::File:
3742
74.4k
    case DeclaratorContext::Block:
3743
76.5k
    case DeclaratorContext::ForInit:
3744
76.6k
    case DeclaratorContext::SelectionInit:
3745
77.6k
    case DeclaratorContext::Condition:
3746
      // FIXME: P0091R3 (erroneously) does not permit class template argument
3747
      // deduction in conditions, for-init-statements, and other declarations
3748
      // that are not simple-declarations.
3749
77.6k
      break;
3750
97
    case DeclaratorContext::CXXNew:
3751
      // FIXME: P0091R3 does not permit class template argument deduction here,
3752
      // but we follow GCC and allow it anyway.
3753
97
      if (!IsCXXAutoType && 
!isa<DeducedTemplateSpecializationType>(Deduced)18
)
3754
1
        Error = 17; // 'new' type
3755
97
      break;
3756
1
    case DeclaratorContext::KNRTypeList:
3757
1
      Error = 18; // K&R function parameter
3758
1
      break;
3759
90.4k
    }
3760
3761
90.4k
    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3762
13
      Error = 11;
3763
3764
    // In Objective-C it is an error to use 'auto' on a function declarator
3765
    // (and everywhere for '__auto_type').
3766
90.4k
    if (D.isFunctionDeclarator() &&
3767
90.4k
        
(8.58k
!SemaRef.getLangOpts().CPlusPlus118.58k
||
!IsCXXAutoType8.57k
))
3768
13
      Error = 13;
3769
3770
90.4k
    SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
3771
90.4k
    if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3772
62
      AutoRange = D.getName().getSourceRange();
3773
3774
90.4k
    if (Error != -1) {
3775
212
      unsigned Kind;
3776
212
      if (Auto) {
3777
160
        switch (Auto->getKeyword()) {
3778
136
        case AutoTypeKeyword::Auto: Kind = 0; break;
3779
14
        case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3780
10
        case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3781
160
        }
3782
160
      } else {
3783
52
        assert(isa<DeducedTemplateSpecializationType>(Deduced) &&
3784
52
               "unknown auto type");
3785
52
        Kind = 3;
3786
52
      }
3787
3788
212
      auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3789
212
      TemplateName TN = DTST ? 
DTST->getTemplateName()52
:
TemplateName()160
;
3790
3791
212
      SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3792
212
        << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3793
212
        << QualType(Deduced, 0) << AutoRange;
3794
212
      if (auto *TD = TN.getAsTemplateDecl())
3795
52
        SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
3796
3797
212
      T = SemaRef.Context.IntTy;
3798
212
      D.setInvalidType(true);
3799
90.2k
    } else if (Auto && 
D.getContext() != DeclaratorContext::LambdaExpr88.0k
) {
3800
      // If there was a trailing return type, we already got
3801
      // warn_cxx98_compat_trailing_return_type in the parser.
3802
83.4k
      SemaRef.Diag(AutoRange.getBegin(),
3803
83.4k
                   D.getContext() == DeclaratorContext::LambdaExprParameter
3804
83.4k
                       ? 
diag::warn_cxx11_compat_generic_lambda2.73k
3805
83.4k
                   : 
IsDeducedReturnType80.7k
3806
80.7k
                       ? 
diag::warn_cxx11_compat_deduced_return_type409
3807
80.7k
                       : 
diag::warn_cxx98_compat_auto_type_specifier80.3k
)
3808
83.4k
          << AutoRange;
3809
83.4k
    }
3810
90.4k
  }
3811
3812
155M
  if (SemaRef.getLangOpts().CPlusPlus &&
3813
155M
      
OwnedTagDecl69.1M
&&
OwnedTagDecl->isCompleteDefinition()85.7k
) {
3814
    // Check the contexts where C++ forbids the declaration of a new class
3815
    // or enumeration in a type-specifier-seq.
3816
67.5k
    unsigned DiagID = 0;
3817
67.5k
    switch (D.getContext()) {
3818
0
    case DeclaratorContext::TrailingReturn:
3819
0
    case DeclaratorContext::TrailingReturnVar:
3820
      // Class and enumeration definitions are syntactically not allowed in
3821
      // trailing return types.
3822
0
      llvm_unreachable("parser should not have allowed this");
3823
0
      break;
3824
51.6k
    case DeclaratorContext::File:
3825
61.6k
    case DeclaratorContext::Member:
3826
67.4k
    case DeclaratorContext::Block:
3827
67.4k
    case DeclaratorContext::ForInit:
3828
67.4k
    case DeclaratorContext::SelectionInit:
3829
67.4k
    case DeclaratorContext::BlockLiteral:
3830
67.4k
    case DeclaratorContext::LambdaExpr:
3831
      // C++11 [dcl.type]p3:
3832
      //   A type-specifier-seq shall not define a class or enumeration unless
3833
      //   it appears in the type-id of an alias-declaration (7.1.3) that is not
3834
      //   the declaration of a template-declaration.
3835
67.4k
    case DeclaratorContext::AliasDecl:
3836
67.4k
      break;
3837
5
    case DeclaratorContext::AliasTemplate:
3838
5
      DiagID = diag::err_type_defined_in_alias_template;
3839
5
      break;
3840
34
    case DeclaratorContext::TypeName:
3841
34
    case DeclaratorContext::FunctionalCast:
3842
34
    case DeclaratorContext::ConversionId:
3843
34
    case DeclaratorContext::TemplateParam:
3844
34
    case DeclaratorContext::CXXNew:
3845
34
    case DeclaratorContext::CXXCatch:
3846
34
    case DeclaratorContext::ObjCCatch:
3847
34
    case DeclaratorContext::TemplateArg:
3848
34
    case DeclaratorContext::TemplateTypeArg:
3849
35
    case DeclaratorContext::Association:
3850
35
      DiagID = diag::err_type_defined_in_type_specifier;
3851
35
      break;
3852
5
    case DeclaratorContext::Prototype:
3853
5
    case DeclaratorContext::LambdaExprParameter:
3854
5
    case DeclaratorContext::ObjCParameter:
3855
6
    case DeclaratorContext::ObjCResult:
3856
6
    case DeclaratorContext::KNRTypeList:
3857
6
    case DeclaratorContext::RequiresExpr:
3858
      // C++ [dcl.fct]p6:
3859
      //   Types shall not be defined in return or parameter types.
3860
6
      DiagID = diag::err_type_defined_in_param_type;
3861
6
      break;
3862
17
    case DeclaratorContext::Condition:
3863
      // C++ 6.4p2:
3864
      // The type-specifier-seq shall not contain typedef and shall not declare
3865
      // a new class or enumeration.
3866
17
      DiagID = diag::err_type_defined_in_condition;
3867
17
      break;
3868
67.5k
    }
3869
3870
67.5k
    if (DiagID != 0) {
3871
63
      SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3872
63
          << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
3873
63
      D.setInvalidType(true);
3874
63
    }
3875
67.5k
  }
3876
3877
155M
  assert(!T.isNull() && "This function should not return a null type");
3878
155M
  return T;
3879
155M
}
3880
3881
/// Produce an appropriate diagnostic for an ambiguity between a function
3882
/// declarator and a C++ direct-initializer.
3883
static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
3884
18.8k
                                       DeclaratorChunk &DeclType, QualType RT) {
3885
18.8k
  const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3886
18.8k
  assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3887
3888
  // If the return type is void there is no ambiguity.
3889
18.8k
  if (RT->isVoidType())
3890
10.1k
    return;
3891
3892
  // An initializer for a non-class type can have at most one argument.
3893
8.77k
  if (!RT->isRecordType() && 
FTI.NumParams > 17.32k
)
3894
491
    return;
3895
3896
  // An initializer for a reference must have exactly one argument.
3897
8.28k
  if (RT->isReferenceType() && 
FTI.NumParams != 1516
)
3898
451
    return;
3899
3900
  // Only warn if this declarator is declaring a function at block scope, and
3901
  // doesn't have a storage class (such as 'extern') specified.
3902
7.83k
  if (!D.isFunctionDeclarator() ||
3903
7.83k
      
D.getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration7.76k
||
3904
7.83k
      
!S.CurContext->isFunctionOrMethod()7.72k
||
3905
7.83k
      
D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_unspecified142
)
3906
7.69k
    return;
3907
3908
  // Inside a condition, a direct initializer is not permitted. We allow one to
3909
  // be parsed in order to give better diagnostics in condition parsing.
3910
136
  if (D.getContext() == DeclaratorContext::Condition)
3911
4
    return;
3912
3913
132
  SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3914
3915
132
  S.Diag(DeclType.Loc,
3916
132
         FTI.NumParams ? 
diag::warn_parens_disambiguated_as_function_declaration24
3917
132
                       : 
diag::warn_empty_parens_are_function_decl108
)
3918
132
      << ParenRange;
3919
3920
  // If the declaration looks like:
3921
  //   T var1,
3922
  //   f();
3923
  // and name lookup finds a function named 'f', then the ',' was
3924
  // probably intended to be a ';'.
3925
132
  if (!D.isFirstDeclarator() && 
D.getIdentifier()19
) {
3926
19
    FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3927
19
    FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
3928
19
    if (Comma.getFileID() != Name.getFileID() ||
3929
19
        Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3930
19
      LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3931
19
                          Sema::LookupOrdinaryName);
3932
19
      if (S.LookupName(Result, S.getCurScope()))
3933
13
        S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3934
13
          << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
3935
13
          << D.getIdentifier();
3936
19
      Result.suppressDiagnostics();
3937
19
    }
3938
19
  }
3939
3940
132
  if (FTI.NumParams > 0) {
3941
    // For a declaration with parameters, eg. "T var(T());", suggest adding
3942
    // parens around the first parameter to turn the declaration into a
3943
    // variable declaration.
3944
24
    SourceRange Range = FTI.Params[0].Param->getSourceRange();
3945
24
    SourceLocation B = Range.getBegin();
3946
24
    SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3947
    // FIXME: Maybe we should suggest adding braces instead of parens
3948
    // in C++11 for classes that don't have an initializer_list constructor.
3949
24
    S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3950
24
      << FixItHint::CreateInsertion(B, "(")
3951
24
      << FixItHint::CreateInsertion(E, ")");
3952
108
  } else {
3953
    // For a declaration without parameters, eg. "T var();", suggest replacing
3954
    // the parens with an initializer to turn the declaration into a variable
3955
    // declaration.
3956
108
    const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3957
3958
    // Empty parens mean value-initialization, and no parens mean
3959
    // default initialization. These are equivalent if the default
3960
    // constructor is user-provided or if zero-initialization is a
3961
    // no-op.
3962
108
    if (RD && 
RD->hasDefinition()31
&&
3963
108
        
(27
RD->isEmpty()27
||
RD->hasUserProvidedDefaultConstructor()18
))
3964
13
      S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3965
13
        << FixItHint::CreateRemoval(ParenRange);
3966
95
    else {
3967
95
      std::string Init =
3968
95
          S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3969
95
      if (Init.empty() && 
S.LangOpts.CPlusPlus1112
)
3970
9
        Init = "{}";
3971
95
      if (!Init.empty())
3972
92
        S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3973
92
          << FixItHint::CreateReplacement(ParenRange, Init);
3974
95
    }
3975
108
  }
3976
132
}
3977
3978
/// Produce an appropriate diagnostic for a declarator with top-level
3979
/// parentheses.
3980
489
static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) {
3981
489
  DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1);
3982
489
  assert(Paren.Kind == DeclaratorChunk::Paren &&
3983
489
         "do not have redundant top-level parentheses");
3984
3985
  // This is a syntactic check; we're not interested in cases that arise
3986
  // during template instantiation.
3987
489
  if (S.inTemplateInstantiation())
3988
0
    return;
3989
3990
  // Check whether this could be intended to be a construction of a temporary
3991
  // object in C++ via a function-style cast.
3992
489
  bool CouldBeTemporaryObject =
3993
489
      S.getLangOpts().CPlusPlus && 
D.isExpressionContext()450
&&
3994
489
      
!D.isInvalidType()140
&&
D.getIdentifier()128
&&
3995
489
      
D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier122
&&
3996
489
      
(111
T->isRecordType()111
||
T->isDependentType()66
) &&
3997
489
      
D.getDeclSpec().getTypeQualifiers() == 046
&&
D.isFirstDeclarator()46
;
3998
3999
489
  bool StartsWithDeclaratorId = true;
4000
810
  for (auto &C : D.type_objects()) {
4001
810
    switch (C.Kind) {
4002
551
    case DeclaratorChunk::Paren:
4003
551
      if (&C == &Paren)
4004
489
        continue;
4005
551
      
[[fallthrough]];62
4006
103
    case DeclaratorChunk::Pointer:
4007
103
      StartsWithDeclaratorId = false;
4008
103
      continue;
4009
4010
18
    case DeclaratorChunk::Array:
4011
18
      if (!C.Arr.NumElts)
4012
0
        CouldBeTemporaryObject = false;
4013
18
      continue;
4014
4015
10
    case DeclaratorChunk::Reference:
4016
      // FIXME: Suppress the warning here if there is no initializer; we're
4017
      // going to give an error anyway.
4018
      // We assume that something like 'T (&x) = y;' is highly likely to not
4019
      // be intended to be a temporary object.
4020
10
      CouldBeTemporaryObject = false;
4021
10
      StartsWithDeclaratorId = false;
4022
10
      continue;
4023
4024
56
    case DeclaratorChunk::Function:
4025
      // In a new-type-id, function chunks require parentheses.
4026
56
      if (D.getContext() == DeclaratorContext::CXXNew)
4027
0
        return;
4028
      // FIXME: "A(f())" deserves a vexing-parse warning, not just a
4029
      // redundant-parens warning, but we don't know whether the function
4030
      // chunk was syntactically valid as an expression here.
4031
56
      CouldBeTemporaryObject = false;
4032
56
      continue;
4033
4034
0
    case DeclaratorChunk::BlockPointer:
4035
134
    case DeclaratorChunk::MemberPointer:
4036
134
    case DeclaratorChunk::Pipe:
4037
      // These cannot appear in expressions.
4038
134
      CouldBeTemporaryObject = false;
4039
134
      StartsWithDeclaratorId = false;
4040
134
      continue;
4041
810
    }
4042
810
  }
4043
4044
  // FIXME: If there is an initializer, assume that this is not intended to be
4045
  // a construction of a temporary object.
4046
4047
  // Check whether the name has already been declared; if not, this is not a
4048
  // function-style cast.
4049
489
  if (CouldBeTemporaryObject) {
4050
33
    LookupResult Result(S, D.getIdentifier(), SourceLocation(),
4051
33
                        Sema::LookupOrdinaryName);
4052
33
    if (!S.LookupName(Result, S.getCurScope()))
4053
18
      CouldBeTemporaryObject = false;
4054
33
    Result.suppressDiagnostics();
4055
33
  }
4056
4057
489
  SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
4058
4059
489
  if (!CouldBeTemporaryObject) {
4060
    // If we have A (::B), the parentheses affect the meaning of the program.
4061
    // Suppress the warning in that case. Don't bother looking at the DeclSpec
4062
    // here: even (e.g.) "int ::x" is visually ambiguous even though it's
4063
    // formally unambiguous.
4064
474
    if (StartsWithDeclaratorId && 
D.getCXXScopeSpec().isValid()272
) {
4065
67
      for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS;
4066
53
           
NNS = NNS->getPrefix()41
) {
4067
53
        if (NNS->getKind() == NestedNameSpecifier::Global)
4068
12
          return;
4069
53
      }
4070
26
    }
4071
4072
462
    S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
4073
462
        << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
4074
462
        << FixItHint::CreateRemoval(Paren.EndLoc);
4075
462
    return;
4076
474
  }
4077
4078
15
  S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
4079
15
      << ParenRange << D.getIdentifier();
4080
15
  auto *RD = T->getAsCXXRecordDecl();
4081
15
  if (!RD || 
!RD->hasDefinition()14
||
RD->hasNonTrivialDestructor()14
)
4082
7
    S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
4083
7
        << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
4084
7
        << D.getIdentifier();
4085
  // FIXME: A cast to void is probably a better suggestion in cases where it's
4086
  // valid (when there is no initializer and we're not in a condition).
4087
15
  S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses)
4088
15
      << FixItHint::CreateInsertion(D.getBeginLoc(), "(")
4089
15
      << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getEndLoc()), ")");
4090
15
  S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
4091
15
      << FixItHint::CreateRemoval(Paren.Loc)
4092
15
      << FixItHint::CreateRemoval(Paren.EndLoc);
4093
15
}
4094
4095
/// Helper for figuring out the default CC for a function declarator type.  If
4096
/// this is the outermost chunk, then we can determine the CC from the
4097
/// declarator context.  If not, then this could be either a member function
4098
/// type or normal function type.
4099
static CallingConv getCCForDeclaratorChunk(
4100
    Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
4101
36.9M
    const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
4102
36.9M
  assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
4103
4104
  // Check for an explicit CC attribute.
4105
36.9M
  for (const ParsedAttr &AL : AttrList) {
4106
1.31M
    switch (AL.getKind()) {
4107
40.6k
    
CALLING_CONV_ATTRS_CASELIST393
: {
4108
      // Ignore attributes that don't validate or can't apply to the
4109
      // function type.  We'll diagnose the failure to apply them in
4110
      // handleFunctionTypeAttr.
4111
40.6k
      CallingConv CC;
4112
40.6k
      if (!S.CheckCallingConvAttr(AL, CC, /*FunctionDecl=*/nullptr,
4113
2.95k
                                  S.IdentifyCUDATarget(D.getAttributes())) &&
4114
2.95k
          
(2.91k
!FTI.isVariadic2.91k
||
supportsVariadicCall(CC)86
)) {
4115
2.88k
        return CC;
4116
2.88k
      }
4117
65
      break;
4118
40.6k
    }
4119
4120
1.30M
    default:
4121
1.30M
      break;
4122
1.31M
    }
4123
1.31M
  }
4124
4125
36.9M
  bool IsCXXInstanceMethod = false;
4126
4127
36.9M
  if (S.getLangOpts().CPlusPlus) {
4128
    // Look inwards through parentheses to see if this chunk will form a
4129
    // member pointer type or if we're the declarator.  Any type attributes
4130
    // between here and there will override the CC we choose here.
4131
16.3M
    unsigned I = ChunkIndex;
4132
16.3M
    bool FoundNonParen = false;
4133
16.6M
    while (I && 
!FoundNonParen248k
) {
4134
247k
      --I;
4135
247k
      if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
4136
116k
        FoundNonParen = true;
4137
247k
    }
4138
4139
16.3M
    if (FoundNonParen) {
4140
      // If we're not the declarator, we're a regular function type unless we're
4141
      // in a member pointer.
4142
116k
      IsCXXInstanceMethod =
4143
116k
          D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
4144
16.2M
    } else if (D.getContext() == DeclaratorContext::LambdaExpr) {
4145
      // This can only be a call operator for a lambda, which is an instance
4146
      // method, unless explicitly specified as 'static'.
4147
7.73k
      IsCXXInstanceMethod =
4148
7.73k
          D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static;
4149
16.2M
    } else {
4150
      // We're the innermost decl chunk, so must be a function declarator.
4151
16.2M
      assert(D.isFunctionDeclarator());
4152
4153
      // If we're inside a record, we're declaring a method, but it could be
4154
      // explicitly or implicitly static.
4155
16.2M
      IsCXXInstanceMethod =
4156
16.2M
          D.isFirstDeclarationOfMember() &&
4157
16.2M
          
D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef1.67M
&&
4158
16.2M
          
!D.isStaticMember()1.66M
;
4159
16.2M
    }
4160
16.3M
  }
4161
4162
36.9M
  CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
4163
36.9M
                                                         IsCXXInstanceMethod);
4164
4165
  // Attribute AT_OpenCLKernel affects the calling convention for SPIR
4166
  // and AMDGPU targets, hence it cannot be treated as a calling
4167
  // convention attribute. This is the simplest place to infer
4168
  // calling convention for OpenCL kernels.
4169
36.9M
  if (S.getLangOpts().OpenCL) {
4170
518k
    for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
4171
518k
      if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) {
4172
1.27k
        CC = CC_OpenCLKernel;
4173
1.27k
        break;
4174
1.27k
      }
4175
518k
    }
4176
36.6M
  } else if (S.getLangOpts().CUDA) {
4177
    // If we're compiling CUDA/HIP code and targeting SPIR-V we need to make
4178
    // sure the kernels will be marked with the right calling convention so that
4179
    // they will be visible by the APIs that ingest SPIR-V.
4180
18.1k
    llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
4181
18.1k
    if (Triple.getArch() == llvm::Triple::spirv32 ||
4182
18.1k
        
Triple.getArch() == llvm::Triple::spirv6418.1k
) {
4183
29
      for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
4184
29
        if (AL.getKind() == ParsedAttr::AT_CUDAGlobal) {
4185
7
          CC = CC_OpenCLKernel;
4186
7
          break;
4187
7
        }
4188
29
      }
4189
21
    }
4190
18.1k
  }
4191
4192
36.9M
  return CC;
4193
36.9M
}
4194
4195
namespace {
4196
  /// A simple notion of pointer kinds, which matches up with the various
4197
  /// pointer declarators.
4198
  enum class SimplePointerKind {
4199
    Pointer,
4200
    BlockPointer,
4201
    MemberPointer,
4202
    Array,
4203
  };
4204
} // end anonymous namespace
4205
4206
2.57M
IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
4207
2.57M
  switch (nullability) {
4208
2.11M
  case NullabilityKind::NonNull:
4209
2.11M
    if (!Ident__Nonnull)
4210
1.02k
      Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
4211
2.11M
    return Ident__Nonnull;
4212
4213
449k
  case NullabilityKind::Nullable:
4214
449k
    if (!Ident__Nullable)
4215
431
      Ident__Nullable = PP.getIdentifierInfo("_Nullable");
4216
449k
    return Ident__Nullable;
4217
4218
0
  case NullabilityKind::NullableResult:
4219
0
    if (!Ident__Nullable_result)
4220
0
      Ident__Nullable_result = PP.getIdentifierInfo("_Nullable_result");
4221
0
    return Ident__Nullable_result;
4222
4223
14.9k
  case NullabilityKind::Unspecified:
4224
14.9k
    if (!Ident__Null_unspecified)
4225
233
      Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
4226
14.9k
    return Ident__Null_unspecified;
4227
2.57M
  }
4228
0
  llvm_unreachable("Unknown nullability kind.");
4229
0
}
4230
4231
/// Retrieve the identifier "NSError".
4232
1.12M
IdentifierInfo *Sema::getNSErrorIdent() {
4233
1.12M
  if (!Ident_NSError)
4234
2.62k
    Ident_NSError = PP.getIdentifierInfo("NSError");
4235
4236
1.12M
  return Ident_NSError;
4237
1.12M
}
4238
4239
/// Check whether there is a nullability attribute of any kind in the given
4240
/// attribute list.
4241
12.7M
static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
4242
12.7M
  for (const ParsedAttr &AL : attrs) {
4243
890k
    if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
4244
890k
        
AL.getKind() == ParsedAttr::AT_TypeNullable821k
||
4245
890k
        
AL.getKind() == ParsedAttr::AT_TypeNullableResult370k
||
4246
890k
        
AL.getKind() == ParsedAttr::AT_TypeNullUnspecified370k
)
4247
543k
      return true;
4248
890k
  }
4249
4250
12.2M
  return false;
4251
12.7M
}
4252
4253
namespace {
4254
  /// Describes the kind of a pointer a declarator describes.
4255
  enum class PointerDeclaratorKind {
4256
    // Not a pointer.
4257
    NonPointer,
4258
    // Single-level pointer.
4259
    SingleLevelPointer,
4260
    // Multi-level pointer (of any pointer kind).
4261
    MultiLevelPointer,
4262
    // CFFooRef*
4263
    MaybePointerToCFRef,
4264
    // CFErrorRef*
4265
    CFErrorRefPointer,
4266
    // NSError**
4267
    NSErrorPointerPointer,
4268
  };
4269
4270
  /// Describes a declarator chunk wrapping a pointer that marks inference as
4271
  /// unexpected.
4272
  // These values must be kept in sync with diagnostics.
4273
  enum class PointerWrappingDeclaratorKind {
4274
    /// Pointer is top-level.
4275
    None = -1,
4276
    /// Pointer is an array element.
4277
    Array = 0,
4278
    /// Pointer is the referent type of a C++ reference.
4279
    Reference = 1
4280
  };
4281
} // end anonymous namespace
4282
4283
/// Classify the given declarator, whose type-specified is \c type, based on
4284
/// what kind of pointer it refers to.
4285
///
4286
/// This is used to determine the default nullability.
4287
static PointerDeclaratorKind
4288
classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator,
4289
137M
                          PointerWrappingDeclaratorKind &wrappingKind) {
4290
137M
  unsigned numNormalPointers = 0;
4291
4292
  // For any dependent type, we consider it a non-pointer.
4293
137M
  if (type->isDependentType())
4294
3.77M
    return PointerDeclaratorKind::NonPointer;
4295
4296
  // Look through the declarator chunks to identify pointers.
4297
179M
  
for (unsigned i = 0, n = declarator.getNumTypeObjects(); 133M
i != n;
++i45.1M
) {
4298
45.2M
    DeclaratorChunk &chunk = declarator.getTypeObject(i);
4299
45.2M
    switch (chunk.Kind) {
4300
255k
    case DeclaratorChunk::Array:
4301
255k
      if (numNormalPointers == 0)
4302
254k
        wrappingKind = PointerWrappingDeclaratorKind::Array;
4303
255k
      break;
4304
4305
35.7M
    case DeclaratorChunk::Function:
4306
35.7M
    case DeclaratorChunk::Pipe:
4307
35.7M
      break;
4308
4309
49.4k
    case DeclaratorChunk::BlockPointer:
4310
51.8k
    case DeclaratorChunk::MemberPointer:
4311
51.8k
      return numNormalPointers > 0 ? 
PointerDeclaratorKind::MultiLevelPointer60
4312
51.8k
                                   : 
PointerDeclaratorKind::SingleLevelPointer51.7k
;
4313
4314
113k
    case DeclaratorChunk::Paren:
4315
113k
      break;
4316
4317
462k
    case DeclaratorChunk::Reference:
4318
462k
      if (numNormalPointers == 0)
4319
462k
        wrappingKind = PointerWrappingDeclaratorKind::Reference;
4320
462k
      break;
4321
4322
8.56M
    case DeclaratorChunk::Pointer:
4323
8.56M
      ++numNormalPointers;
4324
8.56M
      if (numNormalPointers > 2)
4325
519
        return PointerDeclaratorKind::MultiLevelPointer;
4326
8.56M
      break;
4327
45.2M
    }
4328
45.2M
  }
4329
4330
  // Then, dig into the type specifier itself.
4331
133M
  unsigned numTypeSpecifierPointers = 0;
4332
136M
  do {
4333
    // Decompose normal pointers.
4334
136M
    if (auto ptrType = type->getAs<PointerType>()) {
4335
2.40M
      ++numNormalPointers;
4336
4337
2.40M
      if (numNormalPointers > 2)
4338
4.81k
        return PointerDeclaratorKind::MultiLevelPointer;
4339
4340
2.39M
      type = ptrType->getPointeeType();
4341
2.39M
      ++numTypeSpecifierPointers;
4342
2.39M
      continue;
4343
2.40M
    }
4344
4345
    // Decompose block pointers.
4346
133M
    if (type->getAs<BlockPointerType>()) {
4347
22.6k
      return numNormalPointers > 0 ? 
PointerDeclaratorKind::MultiLevelPointer17
4348
22.6k
                                   : 
PointerDeclaratorKind::SingleLevelPointer22.6k
;
4349
22.6k
    }
4350
4351
    // Decompose member pointers.
4352
133M
    if (type->getAs<MemberPointerType>()) {
4353
896
      return numNormalPointers > 0 ? 
PointerDeclaratorKind::MultiLevelPointer11
4354
896
                                   : 
PointerDeclaratorKind::SingleLevelPointer885
;
4355
896
    }
4356
4357
    // Look at Objective-C object pointers.
4358
133M
    if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
4359
506k
      ++numNormalPointers;
4360
506k
      ++numTypeSpecifierPointers;
4361
4362
      // If this is NSError**, report that.
4363
506k
      if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
4364
215k
        if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
4365
215k
            
numNormalPointers == 22
&&
numTypeSpecifierPointers < 22
) {
4366
1
          return PointerDeclaratorKind::NSErrorPointerPointer;
4367
1
        }
4368
215k
      }
4369
4370
506k
      break;
4371
506k
    }
4372
4373
    // Look at Objective-C class types.
4374
133M
    if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
4375
900k
      if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
4376
46.9k
        if (numNormalPointers == 2 && 
numTypeSpecifierPointers < 231.5k
)
4377
31.5k
          return PointerDeclaratorKind::NSErrorPointerPointer;
4378
46.9k
      }
4379
4380
869k
      break;
4381
900k
    }
4382
4383
    // If at this point we haven't seen a pointer, we won't see one.
4384
132M
    if (numNormalPointers == 0)
4385
122M
      return PointerDeclaratorKind::NonPointer;
4386
4387
9.73M
    if (auto recordType = type->getAs<RecordType>()) {
4388
2.64M
      RecordDecl *recordDecl = recordType->getDecl();
4389
4390
      // If this is CFErrorRef*, report it as such.
4391
2.64M
      if (numNormalPointers == 2 && 
numTypeSpecifierPointers < 2136k
&&
4392
2.64M
          
S.isCFError(recordDecl)130k
) {
4393
18.8k
        return PointerDeclaratorKind::CFErrorRefPointer;
4394
18.8k
      }
4395
2.62M
      break;
4396
2.64M
    }
4397
4398
7.09M
    break;
4399
9.73M
  } while (
true2.39M
);
4400
4401
11.0M
  switch (numNormalPointers) {
4402
42
  case 0:
4403
42
    return PointerDeclaratorKind::NonPointer;
4404
4405
10.8M
  case 1:
4406
10.8M
    return PointerDeclaratorKind::SingleLevelPointer;
4407
4408
265k
  case 2:
4409
265k
    return PointerDeclaratorKind::MaybePointerToCFRef;
4410
4411
11
  default:
4412
11
    return PointerDeclaratorKind::MultiLevelPointer;
4413
11.0M
  }
4414
11.0M
}
4415
4416
130k
bool Sema::isCFError(RecordDecl *RD) {
4417
  // If we already know about CFError, test it directly.
4418
130k
  if (CFError)
4419
121k
    return CFError == RD;
4420
4421
  // Check whether this is CFError, which we identify based on its bridge to
4422
  // NSError. CFErrorRef used to be declared with "objc_bridge" but is now
4423
  // declared with "objc_bridge_mutable", so look for either one of the two
4424
  // attributes.
4425
8.30k
  if (RD->getTagKind() == TagTypeKind::Struct) {
4426
8.23k
    IdentifierInfo *bridgedType = nullptr;
4427
8.23k
    if (auto bridgeAttr = RD->getAttr<ObjCBridgeAttr>())
4428
1.06k
      bridgedType = bridgeAttr->getBridgedType();
4429
7.17k
    else if (auto bridgeAttr = RD->getAttr<ObjCBridgeMutableAttr>())
4430
220
      bridgedType = bridgeAttr->getBridgedType();
4431
4432
8.23k
    if (bridgedType == getNSErrorIdent()) {
4433
244
      CFError = RD;
4434
244
      return true;
4435
244
    }
4436
8.23k
  }
4437
4438
8.05k
  return false;
4439
8.30k
}
4440
4441
static FileID getNullabilityCompletenessCheckFileID(Sema &S,
4442
15.7M
                                                    SourceLocation loc) {
4443
  // If we're anywhere in a function, method, or closure context, don't perform
4444
  // completeness checks.
4445
21.3M
  for (DeclContext *ctx = S.CurContext; ctx; 
ctx = ctx->getParent()5.56M
) {
4446
21.3M
    if (ctx->isFunctionOrMethod())
4447
31.6k
      return FileID();
4448
4449
21.3M
    if (ctx->isFileContext())
4450
15.7M
      break;
4451
21.3M
  }
4452
4453
  // We only care about the expansion location.
4454
15.7M
  loc = S.SourceMgr.getExpansionLoc(loc);
4455
15.7M
  FileID file = S.SourceMgr.getFileID(loc);
4456
15.7M
  if (file.isInvalid())
4457
548
    return FileID();
4458
4459
  // Retrieve file information.
4460
15.7M
  bool invalid = false;
4461
15.7M
  const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
4462
15.7M
  if (invalid || !sloc.isFile())
4463
0
    return FileID();
4464
4465
  // We don't want to perform completeness checks on the main file or in
4466
  // system headers.
4467
15.7M
  const SrcMgr::FileInfo &fileInfo = sloc.getFile();
4468
15.7M
  if (fileInfo.getIncludeLoc().isInvalid())
4469
190k
    return FileID();
4470
15.5M
  if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
4471
15.5M
      
S.Diags.getSuppressSystemWarnings()15.5M
) {
4472
15.5M
    return FileID();
4473
15.5M
  }
4474
4475
49.9k
  return file;
4476
15.5M
}
4477
4478
/// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
4479
/// taking into account whitespace before and after.
4480
template <typename DiagBuilderT>
4481
static void fixItNullability(Sema &S, DiagBuilderT &Diag,
4482
                             SourceLocation PointerLoc,
4483
884
                             NullabilityKind Nullability) {
4484
884
  assert(PointerLoc.isValid());
4485
884
  if (PointerLoc.isMacroID())
4486
2
    return;
4487
4488
882
  SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
4489
882
  if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
4490
0
    return;
4491
4492
882
  const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
4493
882
  if (!NextChar)
4494
0
    return;
4495
4496
882
  SmallString<32> InsertionTextBuf{" "};
4497
882
  InsertionTextBuf += getNullabilitySpelling(Nullability);
4498
882
  InsertionTextBuf += " ";
4499
882
  StringRef InsertionText = InsertionTextBuf.str();
4500
4501
882
  if (isWhitespace(*NextChar)) {
4502
146
    InsertionText = InsertionText.drop_back();
4503
736
  } else if (NextChar[-1] == '[') {
4504
152
    if (NextChar[0] == ']')
4505
120
      InsertionText = InsertionText.drop_back().drop_front();
4506
32
    else
4507
32
      InsertionText = InsertionText.drop_front();
4508
584
  } else if (!isAsciiIdentifierContinue(NextChar[0], /*allow dollar*/ true) &&
4509
584
             
!isAsciiIdentifierContinue(NextChar[-1], /*allow dollar*/ true)428
) {
4510
188
    InsertionText = InsertionText.drop_back().drop_front();
4511
188
  }
4512
4513
882
  Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
4514
882
}
4515
4516
static void emitNullabilityConsistencyWarning(Sema &S,
4517
                                              SimplePointerKind PointerKind,
4518
                                              SourceLocation PointerLoc,
4519
425
                                              SourceLocation PointerEndLoc) {
4520
425
  assert(PointerLoc.isValid());
4521
4522
425
  if (PointerKind == SimplePointerKind::Array) {
4523
82
    S.Diag(PointerLoc, diag::warn_nullability_missing_array);
4524
343
  } else {
4525
343
    S.Diag(PointerLoc, diag::warn_nullability_missing)
4526
343
      << static_cast<unsigned>(PointerKind);
4527
343
  }
4528
4529
425
  auto FixItLoc = PointerEndLoc.isValid() ? 
PointerEndLoc194
:
PointerLoc231
;
4530
425
  if (FixItLoc.isMacroID())
4531
6
    return;
4532
4533
838
  
auto addFixIt = [&](NullabilityKind Nullability) 419
{
4534
838
    auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
4535
838
    Diag << static_cast<unsigned>(Nullability);
4536
838
    Diag << static_cast<unsigned>(PointerKind);
4537
838
    fixItNullability(S, Diag, FixItLoc, Nullability);
4538
838
  };
4539
419
  addFixIt(NullabilityKind::Nullable);
4540
419
  addFixIt(NullabilityKind::NonNull);
4541
419
}
4542
4543
/// Complains about missing nullability if the file containing \p pointerLoc
4544
/// has other uses of nullability (either the keywords or the \c assume_nonnull
4545
/// pragma).
4546
///
4547
/// If the file has \e not seen other uses of nullability, this particular
4548
/// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
4549
static void
4550
checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
4551
                            SourceLocation pointerLoc,
4552
8.68M
                            SourceLocation pointerEndLoc = SourceLocation()) {
4553
  // Determine which file we're performing consistency checking for.
4554
8.68M
  FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
4555
8.68M
  if (file.isInvalid())
4556
8.63M
    return;
4557
4558
  // If we haven't seen any type nullability in this file, we won't warn now
4559
  // about anything.
4560
49.0k
  FileNullability &fileNullability = S.NullabilityMap[file];
4561
49.0k
  if (!fileNullability.SawTypeNullability) {
4562
    // If this is the first pointer declarator in the file, and the appropriate
4563
    // warning is on, record it in case we need to diagnose it retroactively.
4564
48.6k
    diag::kind diagKind;
4565
48.6k
    if (pointerKind == SimplePointerKind::Array)
4566
562
      diagKind = diag::warn_nullability_missing_array;
4567
48.0k
    else
4568
48.0k
      diagKind = diag::warn_nullability_missing;
4569
4570
48.6k
    if (fileNullability.PointerLoc.isInvalid() &&
4571
48.6k
        
!S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)25.5k
) {
4572
4.93k
      fileNullability.PointerLoc = pointerLoc;
4573
4.93k
      fileNullability.PointerEndLoc = pointerEndLoc;
4574
4.93k
      fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
4575
4.93k
    }
4576
4577
48.6k
    return;
4578
48.6k
  }
4579
4580
  // Complain about missing nullability.
4581
407
  emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
4582
407
}
4583
4584
/// Marks that a nullability feature has been used in the file containing
4585
/// \p loc.
4586
///
4587
/// If this file already had pointer types in it that were missing nullability,
4588
/// the first such instance is retroactively diagnosed.
4589
///
4590
/// \sa checkNullabilityConsistency
4591
7.10M
static void recordNullabilitySeen(Sema &S, SourceLocation loc) {
4592
7.10M
  FileID file = getNullabilityCompletenessCheckFileID(S, loc);
4593
7.10M
  if (file.isInvalid())
4594
7.10M
    return;
4595
4596
961
  FileNullability &fileNullability = S.NullabilityMap[file];
4597
961
  if (fileNullability.SawTypeNullability)
4598
910
    return;
4599
51
  fileNullability.SawTypeNullability = true;
4600
4601
  // If we haven't seen any type nullability before, now we have. Retroactively
4602
  // diagnose the first unannotated pointer, if there was one.
4603
51
  if (fileNullability.PointerLoc.isInvalid())
4604
33
    return;
4605
4606
18
  auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
4607
18
  emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc,
4608
18
                                    fileNullability.PointerEndLoc);
4609
18
}
4610
4611
/// Returns true if any of the declarator chunks before \p endIndex include a
4612
/// level of indirection: array, pointer, reference, or pointer-to-member.
4613
///
4614
/// Because declarator chunks are stored in outer-to-inner order, testing
4615
/// every chunk before \p endIndex is testing all chunks that embed the current
4616
/// chunk as part of their type.
4617
///
4618
/// It is legal to pass the result of Declarator::getNumTypeObjects() as the
4619
/// end index, in which case all chunks are tested.
4620
1.63M
static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
4621
1.63M
  unsigned i = endIndex;
4622
1.64M
  while (i != 0) {
4623
    // Walk outwards along the declarator chunks.
4624
104k
    --i;
4625
104k
    const DeclaratorChunk &DC = D.getTypeObject(i);
4626
104k
    switch (DC.Kind) {
4627
6.71k
    case DeclaratorChunk::Paren:
4628
6.71k
      break;
4629
5.16k
    case DeclaratorChunk::Array:
4630
90.3k
    case DeclaratorChunk::Pointer:
4631
94.4k
    case DeclaratorChunk::Reference:
4632
94.4k
    case DeclaratorChunk::MemberPointer:
4633
94.4k
      return true;
4634
2.34k
    case DeclaratorChunk::Function:
4635
3.67k
    case DeclaratorChunk::BlockPointer:
4636
3.67k
    case DeclaratorChunk::Pipe:
4637
      // These are invalid anyway, so just ignore.
4638
3.67k
      break;
4639
104k
    }
4640
104k
  }
4641
1.54M
  return false;
4642
1.63M
}
4643
4644
86
static bool IsNoDerefableChunk(const DeclaratorChunk &Chunk) {
4645
86
  return (Chunk.Kind == DeclaratorChunk::Pointer ||
4646
86
          
Chunk.Kind == DeclaratorChunk::Array14
);
4647
86
}
4648
4649
template<typename AttrT>
4650
3.27M
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
3.27M
  AL.setUsedAsTypeAttr();
4652
3.27M
  return ::new (Ctx) AttrT(Ctx, AL);
4653
3.27M
}
SemaType.cpp:clang::ObjCInertUnsafeUnretainedAttr* createSimpleAttr<clang::ObjCInertUnsafeUnretainedAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
2.24k
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
2.24k
  AL.setUsedAsTypeAttr();
4652
2.24k
  return ::new (Ctx) AttrT(Ctx, AL);
4653
2.24k
}
SemaType.cpp:clang::ArmMveStrictPolymorphismAttr* createSimpleAttr<clang::ArmMveStrictPolymorphismAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
1.58k
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
1.58k
  AL.setUsedAsTypeAttr();
4652
1.58k
  return ::new (Ctx) AttrT(Ctx, AL);
4653
1.58k
}
SemaType.cpp:clang::LifetimeBoundAttr* createSimpleAttr<clang::LifetimeBoundAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
8
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
8
  AL.setUsedAsTypeAttr();
4652
8
  return ::new (Ctx) AttrT(Ctx, AL);
4653
8
}
SemaType.cpp:clang::NoDerefAttr* createSimpleAttr<clang::NoDerefAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
99
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
99
  AL.setUsedAsTypeAttr();
4652
99
  return ::new (Ctx) AttrT(Ctx, AL);
4653
99
}
SemaType.cpp:clang::WebAssemblyFuncrefAttr* createSimpleAttr<clang::WebAssemblyFuncrefAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
10
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
10
  AL.setUsedAsTypeAttr();
4652
10
  return ::new (Ctx) AttrT(Ctx, AL);
4653
10
}
SemaType.cpp:clang::Ptr32Attr* createSimpleAttr<clang::Ptr32Attr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
67
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
67
  AL.setUsedAsTypeAttr();
4652
67
  return ::new (Ctx) AttrT(Ctx, AL);
4653
67
}
SemaType.cpp:clang::Ptr64Attr* createSimpleAttr<clang::Ptr64Attr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
38
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
38
  AL.setUsedAsTypeAttr();
4652
38
  return ::new (Ctx) AttrT(Ctx, AL);
4653
38
}
SemaType.cpp:clang::SPtrAttr* createSimpleAttr<clang::SPtrAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
24
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
24
  AL.setUsedAsTypeAttr();
4652
24
  return ::new (Ctx) AttrT(Ctx, AL);
4653
24
}
SemaType.cpp:clang::UPtrAttr* createSimpleAttr<clang::UPtrAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
18
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
18
  AL.setUsedAsTypeAttr();
4652
18
  return ::new (Ctx) AttrT(Ctx, AL);
4653
18
}
SemaType.cpp:clang::TypeNonNullAttr* createSimpleAttr<clang::TypeNonNullAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
2.21M
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
2.21M
  AL.setUsedAsTypeAttr();
4652
2.21M
  return ::new (Ctx) AttrT(Ctx, AL);
4653
2.21M
}
SemaType.cpp:clang::TypeNullableAttr* createSimpleAttr<clang::TypeNullableAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
989k
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
989k
  AL.setUsedAsTypeAttr();
4652
989k
  return ::new (Ctx) AttrT(Ctx, AL);
4653
989k
}
SemaType.cpp:clang::TypeNullableResultAttr* createSimpleAttr<clang::TypeNullableResultAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
18
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
18
  AL.setUsedAsTypeAttr();
4652
18
  return ::new (Ctx) AttrT(Ctx, AL);
4653
18
}
SemaType.cpp:clang::TypeNullUnspecifiedAttr* createSimpleAttr<clang::TypeNullUnspecifiedAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
43.7k
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
43.7k
  AL.setUsedAsTypeAttr();
4652
43.7k
  return ::new (Ctx) AttrT(Ctx, AL);
4653
43.7k
}
SemaType.cpp:clang::ObjCKindOfAttr* createSimpleAttr<clang::ObjCKindOfAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
1.84k
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
1.84k
  AL.setUsedAsTypeAttr();
4652
1.84k
  return ::new (Ctx) AttrT(Ctx, AL);
4653
1.84k
}
SemaType.cpp:clang::NSReturnsRetainedAttr* createSimpleAttr<clang::NSReturnsRetainedAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
13.5k
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
13.5k
  AL.setUsedAsTypeAttr();
4652
13.5k
  return ::new (Ctx) AttrT(Ctx, AL);
4653
13.5k
}
SemaType.cpp:clang::CDeclAttr* createSimpleAttr<clang::CDeclAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
474
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
474
  AL.setUsedAsTypeAttr();
4652
474
  return ::new (Ctx) AttrT(Ctx, AL);
4653
474
}
SemaType.cpp:clang::FastCallAttr* createSimpleAttr<clang::FastCallAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
233
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
233
  AL.setUsedAsTypeAttr();
4652
233
  return ::new (Ctx) AttrT(Ctx, AL);
4653
233
}
SemaType.cpp:clang::StdCallAttr* createSimpleAttr<clang::StdCallAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
285
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
285
  AL.setUsedAsTypeAttr();
4652
285
  return ::new (Ctx) AttrT(Ctx, AL);
4653
285
}
SemaType.cpp:clang::ThisCallAttr* createSimpleAttr<clang::ThisCallAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
79
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
79
  AL.setUsedAsTypeAttr();
4652
79
  return ::new (Ctx) AttrT(Ctx, AL);
4653
79
}
SemaType.cpp:clang::RegCallAttr* createSimpleAttr<clang::RegCallAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
247
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
247
  AL.setUsedAsTypeAttr();
4652
247
  return ::new (Ctx) AttrT(Ctx, AL);
4653
247
}
SemaType.cpp:clang::PascalAttr* createSimpleAttr<clang::PascalAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
23
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
23
  AL.setUsedAsTypeAttr();
4652
23
  return ::new (Ctx) AttrT(Ctx, AL);
4653
23
}
SemaType.cpp:clang::SwiftCallAttr* createSimpleAttr<clang::SwiftCallAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
1.22k
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
1.22k
  AL.setUsedAsTypeAttr();
4652
1.22k
  return ::new (Ctx) AttrT(Ctx, AL);
4653
1.22k
}
SemaType.cpp:clang::SwiftAsyncCallAttr* createSimpleAttr<clang::SwiftAsyncCallAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
173
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
173
  AL.setUsedAsTypeAttr();
4652
173
  return ::new (Ctx) AttrT(Ctx, AL);
4653
173
}
SemaType.cpp:clang::VectorCallAttr* createSimpleAttr<clang::VectorCallAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
214
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
214
  AL.setUsedAsTypeAttr();
4652
214
  return ::new (Ctx) AttrT(Ctx, AL);
4653
214
}
SemaType.cpp:clang::AArch64VectorPcsAttr* createSimpleAttr<clang::AArch64VectorPcsAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
13
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
13
  AL.setUsedAsTypeAttr();
4652
13
  return ::new (Ctx) AttrT(Ctx, AL);
4653
13
}
SemaType.cpp:clang::AArch64SVEPcsAttr* createSimpleAttr<clang::AArch64SVEPcsAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
12
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
12
  AL.setUsedAsTypeAttr();
4652
12
  return ::new (Ctx) AttrT(Ctx, AL);
4653
12
}
Unexecuted instantiation: SemaType.cpp:clang::ArmStreamingAttr* createSimpleAttr<clang::ArmStreamingAttr>(clang::ASTContext&, clang::ParsedAttr&)
SemaType.cpp:clang::AMDGPUKernelCallAttr* createSimpleAttr<clang::AMDGPUKernelCallAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
12
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
12
  AL.setUsedAsTypeAttr();
4652
12
  return ::new (Ctx) AttrT(Ctx, AL);
4653
12
}
SemaType.cpp:clang::IntelOclBiccAttr* createSimpleAttr<clang::IntelOclBiccAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
8
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
8
  AL.setUsedAsTypeAttr();
4652
8
  return ::new (Ctx) AttrT(Ctx, AL);
4653
8
}
SemaType.cpp:clang::MSABIAttr* createSimpleAttr<clang::MSABIAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
50
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
50
  AL.setUsedAsTypeAttr();
4652
50
  return ::new (Ctx) AttrT(Ctx, AL);
4653
50
}
SemaType.cpp:clang::SysVABIAttr* createSimpleAttr<clang::SysVABIAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
37
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
37
  AL.setUsedAsTypeAttr();
4652
37
  return ::new (Ctx) AttrT(Ctx, AL);
4653
37
}
SemaType.cpp:clang::PreserveMostAttr* createSimpleAttr<clang::PreserveMostAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
36
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
36
  AL.setUsedAsTypeAttr();
4652
36
  return ::new (Ctx) AttrT(Ctx, AL);
4653
36
}
SemaType.cpp:clang::PreserveAllAttr* createSimpleAttr<clang::PreserveAllAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
27
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
27
  AL.setUsedAsTypeAttr();
4652
27
  return ::new (Ctx) AttrT(Ctx, AL);
4653
27
}
SemaType.cpp:clang::M68kRTDAttr* createSimpleAttr<clang::M68kRTDAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4650
27
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651
27
  AL.setUsedAsTypeAttr();
4652
27
  return ::new (Ctx) AttrT(Ctx, AL);
4653
27
}
4654
4655
static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr,
4656
3.24M
                                   NullabilityKind NK) {
4657
3.24M
  switch (NK) {
4658
2.21M
  case NullabilityKind::NonNull:
4659
2.21M
    return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr);
4660
4661
989k
  case NullabilityKind::Nullable:
4662
989k
    return createSimpleAttr<TypeNullableAttr>(Ctx, Attr);
4663
4664
18
  case NullabilityKind::NullableResult:
4665
18
    return createSimpleAttr<TypeNullableResultAttr>(Ctx, Attr);
4666
4667
43.7k
  case NullabilityKind::Unspecified:
4668
43.7k
    return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr);
4669
3.24M
  }
4670
0
  llvm_unreachable("unknown NullabilityKind");
4671
0
}
4672
4673
// Diagnose whether this is a case with the multiple addr spaces.
4674
// Returns true if this is an invalid case.
4675
// ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
4676
// by qualifiers for two or more different address spaces."
4677
static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld,
4678
                                                LangAS ASNew,
4679
43.2k
                                                SourceLocation AttrLoc) {
4680
43.2k
  if (ASOld != LangAS::Default) {
4681
76
    if (ASOld != ASNew) {
4682
50
      S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
4683
50
      return true;
4684
50
    }
4685
    // Emit a warning if they are identical; it's likely unintended.
4686
26
    S.Diag(AttrLoc,
4687
26
           diag::warn_attribute_address_multiple_identical_qualifiers);
4688
26
  }
4689
43.2k
  return false;
4690
43.2k
}
4691
4692
static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
4693
                                                QualType declSpecType,
4694
155M
                                                TypeSourceInfo *TInfo) {
4695
  // The TypeSourceInfo that this function returns will not be a null type.
4696
  // If there is an error, this function will fill in a dummy type as fallback.
4697
155M
  QualType T = declSpecType;
4698
155M
  Declarator &D = state.getDeclarator();
4699
155M
  Sema &S = state.getSema();
4700
155M
  ASTContext &Context = S.Context;
4701
155M
  const LangOptions &LangOpts = S.getLangOpts();
4702
4703
  // The name we're declaring, if any.
4704
155M
  DeclarationName Name;
4705
155M
  if (D.getIdentifier())
4706
58.3M
    Name = D.getIdentifier();
4707
4708
  // Does this declaration declare a typedef-name?
4709
155M
  bool IsTypedefName =
4710
155M
      D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
4711
155M
      
D.getContext() == DeclaratorContext::AliasDecl153M
||
4712
155M
      
D.getContext() == DeclaratorContext::AliasTemplate153M
;
4713
4714
  // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
4715
155M
  bool IsQualifiedFunction = T->isFunctionProtoType() &&
4716
155M
      
(2.01k
!T->castAs<FunctionProtoType>()->getMethodQuals().empty()2.01k
||
4717
2.01k
       
T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None1.96k
);
4718
4719
  // If T is 'decltype(auto)', the only declarators we can have are parens
4720
  // and at most one function declarator if this is a function declaration.
4721
  // If T is a deduced class template specialization type, we can have no
4722
  // declarator chunks at all.
4723
155M
  if (auto *DT = T->getAs<DeducedType>()) {
4724
98.5k
    const AutoType *AT = T->getAs<AutoType>();
4725
98.5k
    bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
4726
98.5k
    if ((AT && 
AT->isDecltypeAuto()96.3k
) ||
IsClassTemplateDeduction97.6k
) {
4727
3.78k
      for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; 
++I670
) {
4728
719
        unsigned Index = E - I - 1;
4729
719
        DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
4730
719
        unsigned DiagId = IsClassTemplateDeduction
4731
719
                              ? 
diag::err_deduced_class_template_compound_type14
4732
719
                              : 
diag::err_decltype_auto_compound_type705
;
4733
719
        unsigned DiagKind = 0;
4734
719
        switch (DeclChunk.Kind) {
4735
38
        case DeclaratorChunk::Paren:
4736
          // FIXME: Rejecting this is a little silly.
4737
38
          if (IsClassTemplateDeduction) {
4738
2
            DiagKind = 4;
4739
2
            break;
4740
2
          }
4741
36
          continue;
4742
645
        case DeclaratorChunk::Function: {
4743
645
          if (IsClassTemplateDeduction) {
4744
2
            DiagKind = 3;
4745
2
            break;
4746
2
          }
4747
643
          unsigned FnIndex;
4748
643
          if (D.isFunctionDeclarationContext() &&
4749
643
              D.isFunctionDeclarator(FnIndex) && 
FnIndex == Index637
)
4750
634
            continue;
4751
9
          DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
4752
9
          break;
4753
643
        }
4754
16
        case DeclaratorChunk::Pointer:
4755
16
        case DeclaratorChunk::BlockPointer:
4756
18
        case DeclaratorChunk::MemberPointer:
4757
18
          DiagKind = 0;
4758
18
          break;
4759
10
        case DeclaratorChunk::Reference:
4760
10
          DiagKind = 1;
4761
10
          break;
4762
8
        case DeclaratorChunk::Array:
4763
8
          DiagKind = 2;
4764
8
          break;
4765
0
        case DeclaratorChunk::Pipe:
4766
0
          break;
4767
719
        }
4768
4769
49
        S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
4770
49
        D.setInvalidType(true);
4771
49
        break;
4772
719
      }
4773
3.11k
    }
4774
98.5k
  }
4775
4776
  // Determine whether we should infer _Nonnull on pointer types.
4777
155M
  std::optional<NullabilityKind> inferNullability;
4778
155M
  bool inferNullabilityCS = false;
4779
155M
  bool inferNullabilityInnerOnly = false;
4780
155M
  bool inferNullabilityInnerOnlyComplete = false;
4781
4782
  // Are we in an assume-nonnull region?
4783
155M
  bool inAssumeNonNullRegion = false;
4784
155M
  SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4785
155M
  if (assumeNonNullLoc.isValid()) {
4786
5.06M
    inAssumeNonNullRegion = true;
4787
5.06M
    recordNullabilitySeen(S, assumeNonNullLoc);
4788
5.06M
  }
4789
4790
  // Whether to complain about missing nullability specifiers or not.
4791
155M
  enum {
4792
    /// Never complain.
4793
155M
    CAMN_No,
4794
    /// Complain on the inner pointers (but not the outermost
4795
    /// pointer).
4796
155M
    CAMN_InnerPointers,
4797
    /// Complain about any pointers that don't have nullability
4798
    /// specified or inferred.
4799
155M
    CAMN_Yes
4800
155M
  } complainAboutMissingNullability = CAMN_No;
4801
155M
  unsigned NumPointersRemaining = 0;
4802
155M
  auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4803
4804
155M
  if (IsTypedefName) {
4805
    // For typedefs, we do not infer any nullability (the default),
4806
    // and we only complain about missing nullability specifiers on
4807
    // inner pointers.
4808
2.41M
    complainAboutMissingNullability = CAMN_InnerPointers;
4809
4810
2.41M
    if (T->canHaveNullability(/*ResultIfUnknown*/ false) &&
4811
2.41M
        
!T->getNullability()59.0k
) {
4812
      // Note that we allow but don't require nullability on dependent types.
4813
57.2k
      ++NumPointersRemaining;
4814
57.2k
    }
4815
4816
2.97M
    for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; 
++i564k
) {
4817
564k
      DeclaratorChunk &chunk = D.getTypeObject(i);
4818
564k
      switch (chunk.Kind) {
4819
18.2k
      case DeclaratorChunk::Array:
4820
117k
      case DeclaratorChunk::Function:
4821
117k
      case DeclaratorChunk::Pipe:
4822
117k
        break;
4823
4824
10.4k
      case DeclaratorChunk::BlockPointer:
4825
10.7k
      case DeclaratorChunk::MemberPointer:
4826
10.7k
        ++NumPointersRemaining;
4827
10.7k
        break;
4828
4829
97.2k
      case DeclaratorChunk::Paren:
4830
129k
      case DeclaratorChunk::Reference:
4831
129k
        continue;
4832
4833
307k
      case DeclaratorChunk::Pointer:
4834
307k
        ++NumPointersRemaining;
4835
307k
        continue;
4836
564k
      }
4837
564k
    }
4838
153M
  } else {
4839
153M
    bool isFunctionOrMethod = false;
4840
153M
    switch (auto context = state.getDeclarator().getContext()) {
4841
976k
    case DeclaratorContext::ObjCParameter:
4842
1.63M
    case DeclaratorContext::ObjCResult:
4843
96.3M
    case DeclaratorContext::Prototype:
4844
96.3M
    case DeclaratorContext::TrailingReturn:
4845
96.3M
    case DeclaratorContext::TrailingReturnVar:
4846
96.3M
      isFunctionOrMethod = true;
4847
96.3M
      [[fallthrough]];
4848
4849
101M
    case DeclaratorContext::Member:
4850
101M
      if (state.getDeclarator().isObjCIvar() && 
!isFunctionOrMethod120k
) {
4851
120k
        complainAboutMissingNullability = CAMN_No;
4852
120k
        break;
4853
120k
      }
4854
4855
      // Weak properties are inferred to be nullable.
4856
101M
      if (state.getDeclarator().isObjCWeakProperty()) {
4857
        // Weak properties cannot be nonnull, and should not complain about
4858
        // missing nullable attributes during completeness checks.
4859
1.04k
        complainAboutMissingNullability = CAMN_No;
4860
1.04k
        if (inAssumeNonNullRegion) {
4861
907
          inferNullability = NullabilityKind::Nullable;
4862
907
        }
4863
1.04k
        break;
4864
1.04k
      }
4865
4866
101M
      
[[fallthrough]];101M
4867
4868
137M
    case DeclaratorContext::File:
4869
137M
    case DeclaratorContext::KNRTypeList: {
4870
137M
      complainAboutMissingNullability = CAMN_Yes;
4871
4872
      // Nullability inference depends on the type and declarator.
4873
137M
      auto wrappingKind = PointerWrappingDeclaratorKind::None;
4874
137M
      switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4875
126M
      case PointerDeclaratorKind::NonPointer:
4876
126M
      case PointerDeclaratorKind::MultiLevelPointer:
4877
        // Cannot infer nullability.
4878
126M
        break;
4879
4880
10.9M
      case PointerDeclaratorKind::SingleLevelPointer:
4881
        // Infer _Nonnull if we are in an assumes-nonnull region.
4882
10.9M
        if (inAssumeNonNullRegion) {
4883
2.89M
          complainAboutInferringWithinChunk = wrappingKind;
4884
2.89M
          inferNullability = NullabilityKind::NonNull;
4885
2.89M
          inferNullabilityCS = (context == DeclaratorContext::ObjCParameter ||
4886
2.89M
                                
context == DeclaratorContext::ObjCResult2.22M
);
4887
2.89M
        }
4888
10.9M
        break;
4889
4890
18.8k
      case PointerDeclaratorKind::CFErrorRefPointer:
4891
50.3k
      case PointerDeclaratorKind::NSErrorPointerPointer:
4892
        // Within a function or method signature, infer _Nullable at both
4893
        // levels.
4894
50.3k
        if (isFunctionOrMethod && 
inAssumeNonNullRegion50.3k
)
4895
45.2k
          inferNullability = NullabilityKind::Nullable;
4896
50.3k
        break;
4897
4898
265k
      case PointerDeclaratorKind::MaybePointerToCFRef:
4899
265k
        if (isFunctionOrMethod) {
4900
          // On pointer-to-pointer parameters marked cf_returns_retained or
4901
          // cf_returns_not_retained, if the outer pointer is explicit then
4902
          // infer the inner pointer as _Nullable.
4903
238k
          auto hasCFReturnsAttr =
4904
839k
              [](const ParsedAttributesView &AttrList) -> bool {
4905
839k
            return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
4906
839k
                   
AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained)811k
;
4907
839k
          };
4908
238k
          if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4909
217k
            if (hasCFReturnsAttr(D.getDeclarationAttributes()) ||
4910
217k
                hasCFReturnsAttr(D.getAttributes()) ||
4911
217k
                
hasCFReturnsAttr(InnermostChunk->getAttrs())215k
||
4912
217k
                
hasCFReturnsAttr(D.getDeclSpec().getAttributes())189k
) {
4913
28.1k
              inferNullability = NullabilityKind::Nullable;
4914
28.1k
              inferNullabilityInnerOnly = true;
4915
28.1k
            }
4916
217k
          }
4917
238k
        }
4918
265k
        break;
4919
137M
      }
4920
137M
      break;
4921
137M
    }
4922
4923
137M
    case DeclaratorContext::ConversionId:
4924
17.5k
      complainAboutMissingNullability = CAMN_Yes;
4925
17.5k
      break;
4926
4927
0
    case DeclaratorContext::AliasDecl:
4928
0
    case DeclaratorContext::AliasTemplate:
4929
1.54M
    case DeclaratorContext::Block:
4930
1.55M
    case DeclaratorContext::BlockLiteral:
4931
1.55M
    case DeclaratorContext::Condition:
4932
1.55M
    case DeclaratorContext::CXXCatch:
4933
1.58M
    case DeclaratorContext::CXXNew:
4934
1.76M
    case DeclaratorContext::ForInit:
4935
1.76M
    case DeclaratorContext::SelectionInit:
4936
1.77M
    case DeclaratorContext::LambdaExpr:
4937
1.78M
    case DeclaratorContext::LambdaExprParameter:
4938
1.78M
    case DeclaratorContext::ObjCCatch:
4939
2.19M
    case DeclaratorContext::TemplateParam:
4940
7.94M
    case DeclaratorContext::TemplateArg:
4941
8.11M
    case DeclaratorContext::TemplateTypeArg:
4942
15.2M
    case DeclaratorContext::TypeName:
4943
15.7M
    case DeclaratorContext::FunctionalCast:
4944
15.7M
    case DeclaratorContext::RequiresExpr:
4945
15.7M
    case DeclaratorContext::Association:
4946
      // Don't infer in these contexts.
4947
15.7M
      break;
4948
153M
    }
4949
153M
  }
4950
4951
  // Local function that returns true if its argument looks like a va_list.
4952
155M
  auto isVaList = [&S](QualType T) -> bool {
4953
2.68M
    auto *typedefTy = T->getAs<TypedefType>();
4954
2.68M
    if (!typedefTy)
4955
78.6k
      return false;
4956
2.60M
    TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4957
2.89M
    do {
4958
2.89M
      if (typedefTy->getDecl() == vaListTypedef)
4959
5.96k
        return true;
4960
2.89M
      if (auto *name = typedefTy->getDecl()->getIdentifier())
4961
2.89M
        if (name->isStr("va_list"))
4962
24.2k
          return true;
4963
2.86M
      typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4964
2.86M
    } while (typedefTy);
4965
2.57M
    return false;
4966
2.60M
  };
4967
4968
  // Local function that checks the nullability for a given pointer declarator.
4969
  // Returns true if _Nonnull was inferred.
4970
155M
  auto inferPointerNullability =
4971
155M
      [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4972
155M
          SourceLocation pointerEndLoc,
4973
155M
          ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * {
4974
    // We've seen a pointer.
4975
12.5M
    if (NumPointersRemaining > 0)
4976
375k
      --NumPointersRemaining;
4977
4978
    // If a nullability attribute is present, there's nothing to do.
4979
12.5M
    if (hasNullabilityAttr(attrs))
4980
530k
      return nullptr;
4981
4982
    // If we're supposed to infer nullability, do so now.
4983
11.9M
    if (inferNullability && 
!inferNullabilityInnerOnlyComplete2.21M
) {
4984
2.21M
      ParsedAttr::Form form =
4985
2.21M
          inferNullabilityCS
4986
2.21M
              ? 
ParsedAttr::Form::ContextSensitiveKeyword()728k
4987
2.21M
              : ParsedAttr::Form::Keyword(false /*IsAlignAs*/,
4988
1.49M
                                          false /*IsRegularKeywordAttribute*/);
4989
2.21M
      ParsedAttr *nullabilityAttr = Pool.create(
4990
2.21M
          S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
4991
2.21M
          nullptr, SourceLocation(), nullptr, 0, form);
4992
4993
2.21M
      attrs.addAtEnd(nullabilityAttr);
4994
4995
2.21M
      if (inferNullabilityCS) {
4996
728k
        state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4997
728k
          ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4998
728k
      }
4999
5000
2.21M
      if (pointerLoc.isValid() &&
5001
2.21M
          complainAboutInferringWithinChunk !=
5002
2.21M
            PointerWrappingDeclaratorKind::None) {
5003
46
        auto Diag =
5004
46
            S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
5005
46
        Diag << static_cast<int>(complainAboutInferringWithinChunk);
5006
46
        fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull);
5007
46
      }
5008
5009
2.21M
      if (inferNullabilityInnerOnly)
5010
23.8k
        inferNullabilityInnerOnlyComplete = true;
5011
2.21M
      return nullabilityAttr;
5012
2.21M
    }
5013
5014
    // If we're supposed to complain about missing nullability, do so
5015
    // now if it's truly missing.
5016
9.77M
    switch (complainAboutMissingNullability) {
5017
779k
    case CAMN_No:
5018
779k
      break;
5019
5020
375k
    case CAMN_InnerPointers:
5021
375k
      if (NumPointersRemaining == 0)
5022
351k
        break;
5023
375k
      
[[fallthrough]];23.3k
5024
5025
8.63M
    case CAMN_Yes:
5026
8.63M
      checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
5027
9.77M
    }
5028
9.77M
    return nullptr;
5029
9.77M
  };
5030
5031
  // If the type itself could have nullability but does not, infer pointer
5032
  // nullability and perform consistency checking.
5033
155M
  if (S.CodeSynthesisContexts.empty()) {
5034
155M
    if (T->canHaveNullability(/*ResultIfUnknown*/ false) &&
5035
155M
        
!T->getNullability()3.10M
) {
5036
2.62M
      if (isVaList(T)) {
5037
        // Record that we've seen a pointer, but do nothing else.
5038
544
        if (NumPointersRemaining > 0)
5039
112
          --NumPointersRemaining;
5040
2.61M
      } else {
5041
2.61M
        SimplePointerKind pointerKind = SimplePointerKind::Pointer;
5042
2.61M
        if (T->isBlockPointerType())
5043
20.7k
          pointerKind = SimplePointerKind::BlockPointer;
5044
2.59M
        else if (T->isMemberPointerType())
5045
1.23k
          pointerKind = SimplePointerKind::MemberPointer;
5046
5047
2.61M
        if (auto *attr = inferPointerNullability(
5048
2.61M
                pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
5049
2.61M
                D.getDeclSpec().getEndLoc(),
5050
2.61M
                D.getMutableDeclSpec().getAttributes(),
5051
2.61M
                D.getMutableDeclSpec().getAttributePool())) {
5052
1.20M
          T = state.getAttributedType(
5053
1.20M
              createNullabilityAttr(Context, *attr, *inferNullability), T, T);
5054
1.20M
        }
5055
2.61M
      }
5056
2.62M
    }
5057
5058
155M
    if (complainAboutMissingNullability == CAMN_Yes && 
T->isArrayType()137M
&&
5059
155M
        
!T->getNullability()63.8k
&&
!isVaList(T)62.7k
&&
D.isPrototypeContext()33.0k
&&
5060
155M
        
!hasOuterPointerLikeChunk(D, D.getNumTypeObjects())20.7k
) {
5061
18.8k
      checkNullabilityConsistency(S, SimplePointerKind::Array,
5062
18.8k
                                  D.getDeclSpec().getTypeSpecTypeLoc());
5063
18.8k
    }
5064
155M
  }
5065
5066
155M
  bool ExpectNoDerefChunk =
5067
155M
      state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref);
5068
5069
  // Walk the DeclTypeInfo, building the recursive type as we go.
5070
  // DeclTypeInfos are ordered from the identifier out, which is
5071
  // opposite of what we want :).
5072
5073
  // Track if the produced type matches the structure of the declarator.
5074
  // This is used later to decide if we can fill `TypeLoc` from
5075
  // `DeclaratorChunk`s. E.g. it must be false if Clang recovers from
5076
  // an error by replacing the type with `int`.
5077
155M
  bool AreDeclaratorChunksValid = true;
5078
205M
  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; 
++i49.5M
) {
5079
49.5M
    unsigned chunkIndex = e - i - 1;
5080
49.5M
    state.setCurrentChunkIndex(chunkIndex);
5081
49.5M
    DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
5082
49.5M
    IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
5083
49.5M
    switch (DeclType.Kind) {
5084
315k
    case DeclaratorChunk::Paren:
5085
315k
      if (i == 0)
5086
489
        warnAboutRedundantParens(S, D, T);
5087
315k
      T = S.BuildParenType(T);
5088
315k
      break;
5089
61.4k
    case DeclaratorChunk::BlockPointer:
5090
      // If blocks are disabled, emit an error.
5091
61.4k
      if (!LangOpts.Blocks)
5092
7
        S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
5093
5094
      // Handle pointer nullability.
5095
61.4k
      inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
5096
61.4k
                              DeclType.EndLoc, DeclType.getAttrs(),
5097
61.4k
                              state.getDeclarator().getAttributePool());
5098
5099
61.4k
      T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
5100
61.4k
      if (DeclType.Cls.TypeQuals || 
LangOpts.OpenCL61.3k
) {
5101
        // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
5102
        // qualified with const.
5103
175
        if (LangOpts.OpenCL)
5104
163
          DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
5105
175
        T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
5106
175
      }
5107
61.4k
      break;
5108
9.80M
    case DeclaratorChunk::Pointer:
5109
      // Verify that we're not building a pointer to pointer to function with
5110
      // exception specification.
5111
9.80M
      if (LangOpts.CPlusPlus && 
S.CheckDistantExceptionSpec(T)4.23M
) {
5112
7
        S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
5113
7
        D.setInvalidType(true);
5114
        // Build the type anyway.
5115
7
      }
5116
5117
      // Handle pointer nullability
5118
9.80M
      inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
5119
9.80M
                              DeclType.EndLoc, DeclType.getAttrs(),
5120
9.80M
                              state.getDeclarator().getAttributePool());
5121
5122
9.80M
      if (LangOpts.ObjC && 
T->getAs<ObjCObjectType>()3.01M
) {
5123
1.16M
        T = Context.getObjCObjectPointerType(T);
5124
1.16M
        if (DeclType.Ptr.TypeQuals)
5125
66.4k
          T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
5126
1.16M
        break;
5127
1.16M
      }
5128
5129
      // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
5130
      // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
5131
      // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
5132
8.64M
      if (LangOpts.OpenCL) {
5133
48.3k
        if (T->isImageType() || 
T->isSamplerT()48.3k
||
T->isPipeType()48.3k
||
5134
48.3k
            
T->isBlockPointerType()48.3k
) {
5135
14
          S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
5136
14
          D.setInvalidType(true);
5137
14
        }
5138
48.3k
      }
5139
5140
8.64M
      T = S.BuildPointerType(T, DeclType.Loc, Name);
5141
8.64M
      if (DeclType.Ptr.TypeQuals)
5142
83.4k
        T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
5143
8.64M
      break;
5144
2.03M
    case DeclaratorChunk::Reference: {
5145
      // Verify that we're not building a reference to pointer to function with
5146
      // exception specification.
5147
2.03M
      if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
5148
0
        S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
5149
0
        D.setInvalidType(true);
5150
        // Build the type anyway.
5151
0
      }
5152
2.03M
      T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
5153
5154
2.03M
      if (DeclType.Ref.HasRestrict)
5155
15
        T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
5156
2.03M
      break;
5157
9.80M
    }
5158
352k
    case DeclaratorChunk::Array: {
5159
      // Verify that we're not building an array of pointers to function with
5160
      // exception specification.
5161
352k
      if (LangOpts.CPlusPlus && 
S.CheckDistantExceptionSpec(T)174k
) {
5162
0
        S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
5163
0
        D.setInvalidType(true);
5164
        // Build the type anyway.
5165
0
      }
5166
352k
      DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
5167
352k
      Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
5168
352k
      ArraySizeModifier ASM;
5169
5170
      // Microsoft property fields can have multiple sizeless array chunks
5171
      // (i.e. int x[][][]). Skip all of these except one to avoid creating
5172
      // bad incomplete array types.
5173
352k
      if (chunkIndex != 0 && 
!ArraySize12.9k
&&
5174
352k
          
D.getDeclSpec().getAttributes().hasMSPropertyAttr()3.13k
) {
5175
        // This is a sizeless chunk. If the next is also, skip this one.
5176
20
        DeclaratorChunk &NextDeclType = D.getTypeObject(chunkIndex - 1);
5177
20
        if (NextDeclType.Kind == DeclaratorChunk::Array &&
5178
20
            !NextDeclType.Arr.NumElts)
5179
20
          break;
5180
20
      }
5181
5182
352k
      if (ATI.isStar)
5183
40
        ASM = ArraySizeModifier::Star;
5184
352k
      else if (ATI.hasStatic)
5185
58
        ASM = ArraySizeModifier::Static;
5186
352k
      else
5187
352k
        ASM = ArraySizeModifier::Normal;
5188
352k
      if (ASM == ArraySizeModifier::Star && 
!D.isPrototypeContext()40
) {
5189
        // FIXME: This check isn't quite right: it allows star in prototypes
5190
        // for function definitions, and disallows some edge cases detailed
5191
        // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
5192
6
        S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
5193
6
        ASM = ArraySizeModifier::Normal;
5194
6
        D.setInvalidType(true);
5195
6
      }
5196
5197
      // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
5198
      // shall appear only in a declaration of a function parameter with an
5199
      // array type, ...
5200
352k
      if (ASM == ArraySizeModifier::Static || 
ATI.TypeQuals352k
) {
5201
103
        if (!(D.isPrototypeContext() ||
5202
103
              
D.getContext() == DeclaratorContext::KNRTypeList7
)) {
5203
6
          S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype)
5204
6
              << (ASM == ArraySizeModifier::Static ? 
"'static'"3
5205
6
                                                   : 
"type qualifier"3
);
5206
          // Remove the 'static' and the type qualifiers.
5207
6
          if (ASM == ArraySizeModifier::Static)
5208
3
            ASM = ArraySizeModifier::Normal;
5209
6
          ATI.TypeQuals = 0;
5210
6
          D.setInvalidType(true);
5211
6
        }
5212
5213
        // C99 6.7.5.2p1: ... and then only in the outermost array type
5214
        // derivation.
5215
103
        if (hasOuterPointerLikeChunk(D, chunkIndex)) {
5216
3
          S.Diag(DeclType.Loc, diag::err_array_static_not_outermost)
5217
3
              << (ASM == ArraySizeModifier::Static ? 
"'static'"2
5218
3
                                                   : 
"type qualifier"1
);
5219
3
          if (ASM == ArraySizeModifier::Static)
5220
2
            ASM = ArraySizeModifier::Normal;
5221
3
          ATI.TypeQuals = 0;
5222
3
          D.setInvalidType(true);
5223
3
        }
5224
103
      }
5225
5226
      // Array parameters can be marked nullable as well, although it's not
5227
      // necessary if they're marked 'static'.
5228
352k
      if (complainAboutMissingNullability == CAMN_Yes &&
5229
352k
          
!hasNullabilityAttr(DeclType.getAttrs())262k
&&
5230
352k
          
ASM != ArraySizeModifier::Static250k
&&
D.isPrototypeContext()250k
&&
5231
352k
          
!hasOuterPointerLikeChunk(D, chunkIndex)31.8k
) {
5232
27.3k
        checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
5233
27.3k
      }
5234
5235
352k
      T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
5236
352k
                           SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
5237
352k
      break;
5238
352k
    }
5239
36.9M
    case DeclaratorChunk::Function: {
5240
      // If the function declarator has a prototype (i.e. it is not () and
5241
      // does not have a K&R-style identifier list), then the arguments are part
5242
      // of the type, otherwise the argument list is ().
5243
36.9M
      DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5244
36.9M
      IsQualifiedFunction =
5245
36.9M
          FTI.hasMethodTypeQualifiers() || 
FTI.hasRefQualifier()36.4M
;
5246
5247
      // Check for auto functions and trailing return type and adjust the
5248
      // return type accordingly.
5249
36.9M
      if (!D.isInvalidType()) {
5250
        // trailing-return-type is only required if we're declaring a function,
5251
        // and not, for instance, a pointer to a function.
5252
36.9M
        if (D.getDeclSpec().hasAutoTypeSpec() &&
5253
36.9M
            
!FTI.hasTrailingReturnType()14.7k
&&
chunkIndex == 03.96k
) {
5254
3.88k
          if (!S.getLangOpts().CPlusPlus14) {
5255
4
            S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
5256
4
                   D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
5257
4
                       ? 
diag::err_auto_missing_trailing_return3
5258
4
                       : 
diag::err_deduced_return_type1
);
5259
4
            T = Context.IntTy;
5260
4
            D.setInvalidType(true);
5261
4
            AreDeclaratorChunksValid = false;
5262
3.88k
          } else {
5263
3.88k
            S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
5264
3.88k
                   diag::warn_cxx11_compat_deduced_return_type);
5265
3.88k
          }
5266
36.9M
        } else if (FTI.hasTrailingReturnType()) {
5267
          // T must be exactly 'auto' at this point. See CWG issue 681.
5268
13.6k
          if (isa<ParenType>(T)) {
5269
3
            S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens)
5270
3
                << T << D.getSourceRange();
5271
3
            D.setInvalidType(true);
5272
            // FIXME: recover and fill decls in `TypeLoc`s.
5273
3
            AreDeclaratorChunksValid = false;
5274
13.6k
          } else if (D.getName().getKind() ==
5275
13.6k
                     UnqualifiedIdKind::IK_DeductionGuideName) {
5276
1.60k
            if (T != Context.DependentTy) {
5277
4
              S.Diag(D.getDeclSpec().getBeginLoc(),
5278
4
                     diag::err_deduction_guide_with_complex_decl)
5279
4
                  << D.getSourceRange();
5280
4
              D.setInvalidType(true);
5281
              // FIXME: recover and fill decls in `TypeLoc`s.
5282
4
              AreDeclaratorChunksValid = false;
5283
4
            }
5284
12.0k
          } else if (D.getContext() != DeclaratorContext::LambdaExpr &&
5285
12.0k
                     
(10.7k
T.hasQualifiers()10.7k
||
!isa<AutoType>(T)10.7k
||
5286
10.7k
                      cast<AutoType>(T)->getKeyword() !=
5287
10.7k
                          AutoTypeKeyword::Auto ||
5288
10.7k
                      
cast<AutoType>(T)->isConstrained()10.7k
)) {
5289
14
            S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
5290
14
                   diag::err_trailing_return_without_auto)
5291
14
                << T << D.getDeclSpec().getSourceRange();
5292
14
            D.setInvalidType(true);
5293
            // FIXME: recover and fill decls in `TypeLoc`s.
5294
14
            AreDeclaratorChunksValid = false;
5295
14
          }
5296
13.6k
          T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
5297
13.6k
          if (T.isNull()) {
5298
            // An error occurred parsing the trailing return type.
5299
70
            T = Context.IntTy;
5300
70
            D.setInvalidType(true);
5301
13.5k
          } else if (AutoType *Auto = T->getContainedAutoType()) {
5302
            // If the trailing return type contains an `auto`, we may need to
5303
            // invent a template parameter for it, for cases like
5304
            // `auto f() -> C auto` or `[](auto (*p) -> auto) {}`.
5305
253
            InventedTemplateParameterInfo *InventedParamInfo = nullptr;
5306
253
            if (D.getContext() == DeclaratorContext::Prototype)
5307
0
              InventedParamInfo = &S.InventedParameterInfos.back();
5308
253
            else if (D.getContext() == DeclaratorContext::LambdaExprParameter)
5309
8
              InventedParamInfo = S.getCurLambda();
5310
253
            if (InventedParamInfo) {
5311
8
              std::tie(T, TInfo) = InventTemplateParameter(
5312
8
                  state, T, TInfo, Auto, *InventedParamInfo);
5313
8
            }
5314
253
          }
5315
36.9M
        } else {
5316
          // This function type is not the type of the entity being declared,
5317
          // so checking the 'auto' is not the responsibility of this chunk.
5318
36.9M
        }
5319
36.9M
      }
5320
5321
      // C99 6.7.5.3p1: The return type may not be a function or array type.
5322
      // For conversion functions, we'll diagnose this particular error later.
5323
36.9M
      if (!D.isInvalidType() && 
(36.9M
T->isArrayType()36.9M
||
T->isFunctionType()36.9M
) &&
5324
36.9M
          (D.getName().getKind() !=
5325
66
           UnqualifiedIdKind::IK_ConversionFunctionId)) {
5326
29
        unsigned diagID = diag::err_func_returning_array_function;
5327
        // Last processing chunk in block context means this function chunk
5328
        // represents the block.
5329
29
        if (chunkIndex == 0 &&
5330
29
            
D.getContext() == DeclaratorContext::BlockLiteral28
)
5331
1
          diagID = diag::err_block_returning_array_function;
5332
29
        S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
5333
29
        T = Context.IntTy;
5334
29
        D.setInvalidType(true);
5335
29
        AreDeclaratorChunksValid = false;
5336
29
      }
5337
5338
      // Do not allow returning half FP value.
5339
      // FIXME: This really should be in BuildFunctionType.
5340
36.9M
      if (T->isHalfType()) {
5341
53.1k
        if (S.getLangOpts().OpenCL) {
5342
4.81k
          if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5343
4.81k
                                                      S.getLangOpts())) {
5344
3
            S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5345
3
                << T << 0 /*pointer hint*/;
5346
3
            D.setInvalidType(true);
5347
3
          }
5348
48.3k
        } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5349
48.3k
                   
!S.Context.getTargetInfo().allowHalfArgsAndReturns()47.9k
) {
5350
4
          S.Diag(D.getIdentifierLoc(),
5351
4
            diag::err_parameters_retval_cannot_have_fp16_type) << 1;
5352
4
          D.setInvalidType(true);
5353
4
        }
5354
53.1k
      }
5355
5356
36.9M
      if (LangOpts.OpenCL) {
5357
        // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
5358
        // function.
5359
306k
        if (T->isBlockPointerType() || 
T->isImageType()306k
||
T->isSamplerT()306k
||
5360
306k
            
T->isPipeType()306k
) {
5361
20
          S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5362
20
              << T << 1 /*hint off*/;
5363
20
          D.setInvalidType(true);
5364
20
        }
5365
        // OpenCL doesn't support variadic functions and blocks
5366
        // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
5367
        // We also allow here any toolchain reserved identifiers.
5368
306k
        if (FTI.isVariadic &&
5369
306k
            !S.getOpenCLOptions().isAvailableOption(
5370
111
                "__cl_clang_variadic_functions", S.getLangOpts()) &&
5371
306k
            
!(104
D.getIdentifier()104
&&
5372
104
              
(102
(102
D.getIdentifier()->getName() == "printf"102
&&
5373
102
                
LangOpts.getOpenCLCompatibleVersion() >= 12092
) ||
5374
102
               
D.getIdentifier()->getName().startswith("__")12
))) {
5375
12
          S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
5376
12
          D.setInvalidType(true);
5377
12
        }
5378
306k
      }
5379
5380
      // Methods cannot return interface types. All ObjC objects are
5381
      // passed by reference.
5382
36.9M
      if (T->isObjCObjectType()) {
5383
11
        SourceLocation DiagLoc, FixitLoc;
5384
11
        if (TInfo) {
5385
2
          DiagLoc = TInfo->getTypeLoc().getBeginLoc();
5386
2
          FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc());
5387
9
        } else {
5388
9
          DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
5389
9
          FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc());
5390
9
        }
5391
11
        S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
5392
11
          << 0 << T
5393
11
          << FixItHint::CreateInsertion(FixitLoc, "*");
5394
5395
11
        T = Context.getObjCObjectPointerType(T);
5396
11
        if (TInfo) {
5397
2
          TypeLocBuilder TLB;
5398
2
          TLB.pushFullCopy(TInfo->getTypeLoc());
5399
2
          ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
5400
2
          TLoc.setStarLoc(FixitLoc);
5401
2
          TInfo = TLB.getTypeSourceInfo(Context, T);
5402
9
        } else {
5403
9
          AreDeclaratorChunksValid = false;
5404
9
        }
5405
5406
11
        D.setInvalidType(true);
5407
11
      }
5408
5409
      // cv-qualifiers on return types are pointless except when the type is a
5410
      // class type in C++.
5411
36.9M
      if ((T.getCVRQualifiers() || 
T->isAtomicType()36.9M
) &&
5412
36.9M
          
!(462
S.getLangOpts().CPlusPlus462
&&
5413
462
            
(366
T->isDependentType()366
||
T->isRecordType()357
))) {
5414
389
        if (T->isVoidType() && 
!S.getLangOpts().CPlusPlus34
&&
5415
389
            D.getFunctionDefinitionKind() ==
5416
15
                FunctionDefinitionKind::Definition) {
5417
          // [6.9.1/3] qualified void return is invalid on a C
5418
          // function definition.  Apparently ok on declarations and
5419
          // in C++ though (!)
5420
12
          S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
5421
12
        } else
5422
377
          diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
5423
5424
        // C++2a [dcl.fct]p12:
5425
        //   A volatile-qualified return type is deprecated
5426
389
        if (T.isVolatileQualified() && 
S.getLangOpts().CPlusPlus2089
)
5427
6
          S.Diag(DeclType.Loc, diag::warn_deprecated_volatile_return) << T;
5428
389
      }
5429
5430
      // Objective-C ARC ownership qualifiers are ignored on the function
5431
      // return type (by type canonicalization). Complain if this attribute
5432
      // was written here.
5433
36.9M
      if (T.getQualifiers().hasObjCLifetime()) {
5434
19
        SourceLocation AttrLoc;
5435
19
        if (chunkIndex + 1 < D.getNumTypeObjects()) {
5436
6
          DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
5437
6
          for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) {
5438
6
            if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5439
6
              AttrLoc = AL.getLoc();
5440
6
              break;
5441
6
            }
5442
6
          }
5443
6
        }
5444
19
        if (AttrLoc.isInvalid()) {
5445
13
          for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
5446
9
            if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5447
9
              AttrLoc = AL.getLoc();
5448
9
              break;
5449
9
            }
5450
9
          }
5451
13
        }
5452
5453
19
        if (AttrLoc.isValid()) {
5454
          // The ownership attributes are almost always written via
5455
          // the predefined
5456
          // __strong/__weak/__autoreleasing/__unsafe_unretained.
5457
15
          if (AttrLoc.isMacroID())
5458
15
            AttrLoc =
5459
15
                S.SourceMgr.getImmediateExpansionRange(AttrLoc).getBegin();
5460
5461
15
          S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
5462
15
            << T.getQualifiers().getObjCLifetime();
5463
15
        }
5464
19
      }
5465
5466
36.9M
      if (LangOpts.CPlusPlus && 
D.getDeclSpec().hasTagDefinition()16.3M
) {
5467
        // C++ [dcl.fct]p6:
5468
        //   Types shall not be defined in return or parameter types.
5469
2
        TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
5470
2
        S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
5471
2
          << Context.getTypeDeclType(Tag);
5472
2
      }
5473
5474
      // Exception specs are not allowed in typedefs. Complain, but add it
5475
      // anyway.
5476
36.9M
      if (IsTypedefName && 
FTI.getExceptionSpecType()98.7k
&&
!LangOpts.CPlusPlus1722
)
5477
4
        S.Diag(FTI.getExceptionSpecLocBeg(),
5478
4
               diag::err_exception_spec_in_typedef)
5479
4
            << (D.getContext() == DeclaratorContext::AliasDecl ||
5480
4
                
D.getContext() == DeclaratorContext::AliasTemplate3
);
5481
5482
      // If we see "T var();" or "T var(T());" at block scope, it is probably
5483
      // an attempt to initialize a variable, not a function declaration.
5484
36.9M
      if (FTI.isAmbiguous)
5485
18.8k
        warnAboutAmbiguousFunction(S, D, DeclType, T);
5486
5487
36.9M
      FunctionType::ExtInfo EI(
5488
36.9M
          getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex));
5489
5490
      // OpenCL disallows functions without a prototype, but it doesn't enforce
5491
      // strict prototypes as in C23 because it allows a function definition to
5492
      // have an identifier list. See OpenCL 3.0 6.11/g for more details.
5493
36.9M
      if (!FTI.NumParams && 
!FTI.isVariadic801k
&&
5494
36.9M
          
!LangOpts.requiresStrictPrototypes()789k
&&
!LangOpts.OpenCL11.0k
) {
5495
        // Simple void foo(), where the incoming T is the result type.
5496
10.2k
        T = Context.getFunctionNoProtoType(T, EI);
5497
36.9M
      } else {
5498
        // We allow a zero-parameter variadic function in C if the
5499
        // function is marked with the "overloadable" attribute. Scan
5500
        // for this attribute now. We also allow it in C23 per WG14 N2975.
5501
36.9M
        if (!FTI.NumParams && 
FTI.isVariadic791k
&&
!LangOpts.CPlusPlus12.0k
) {
5502
18
          if (LangOpts.C23)
5503
2
            S.Diag(FTI.getEllipsisLoc(),
5504
2
                   diag::warn_c17_compat_ellipsis_only_parameter);
5505
16
          else if (!D.getDeclarationAttributes().hasAttribute(
5506
16
                       ParsedAttr::AT_Overloadable) &&
5507
16
                   !D.getAttributes().hasAttribute(
5508
15
                       ParsedAttr::AT_Overloadable) &&
5509
16
                   !D.getDeclSpec().getAttributes().hasAttribute(
5510
4
                       ParsedAttr::AT_Overloadable))
5511
3
            S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
5512
18
        }
5513
5514
36.9M
        if (FTI.NumParams && 
FTI.Params[0].Param == nullptr36.1M
) {
5515
          // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
5516
          // definition.
5517
3
          S.Diag(FTI.Params[0].IdentLoc,
5518
3
                 diag::err_ident_list_in_fn_declaration);
5519
3
          D.setInvalidType(true);
5520
          // Recover by creating a K&R-style function type, if possible.
5521
3
          T = (!LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL)
5522
3
                  ? Context.getFunctionNoProtoType(T, EI)
5523
3
                  : 
Context.IntTy0
;
5524
3
          AreDeclaratorChunksValid = false;
5525
3
          break;
5526
3
        }
5527
5528
36.9M
        FunctionProtoType::ExtProtoInfo EPI;
5529
36.9M
        EPI.ExtInfo = EI;
5530
36.9M
        EPI.Variadic = FTI.isVariadic;
5531
36.9M
        EPI.EllipsisLoc = FTI.getEllipsisLoc();
5532
36.9M
        EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
5533
36.9M
        EPI.TypeQuals.addCVRUQualifiers(
5534
36.9M
            FTI.MethodQualifiers ? 
FTI.MethodQualifiers->getTypeQualifiers()584k
5535
36.9M
                                 : 
036.3M
);
5536
36.9M
        EPI.RefQualifier = !FTI.hasRefQualifier()? 
RQ_None36.9M
5537
36.9M
                    : 
FTI.RefQualifierIsLValueRef21.3k
?
RQ_LValue10.7k
5538
21.3k
                    : 
RQ_RValue10.6k
;
5539
5540
        // Otherwise, we have a function with a parameter list that is
5541
        // potentially variadic.
5542
36.9M
        SmallVector<QualType, 16> ParamTys;
5543
36.9M
        ParamTys.reserve(FTI.NumParams);
5544
5545
36.9M
        SmallVector<FunctionProtoType::ExtParameterInfo, 16>
5546
36.9M
          ExtParameterInfos(FTI.NumParams);
5547
36.9M
        bool HasAnyInterestingExtParameterInfos = false;
5548
5549
131M
        for (unsigned i = 0, e = FTI.NumParams; i != e; 
++i94.3M
) {
5550
94.7M
          ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5551
94.7M
          QualType ParamTy = Param->getType();
5552
94.7M
          assert(!ParamTy.isNull() && "Couldn't parse type?");
5553
5554
          // Look for 'void'.  void is allowed only as a single parameter to a
5555
          // function with no other parameters (C99 6.7.5.3p10).  We record
5556
          // int(void) as a FunctionProtoType with an empty parameter list.
5557
94.7M
          if (ParamTy->isVoidType()) {
5558
            // If this is something like 'float(int, void)', reject it.  'void'
5559
            // is an incomplete type (C99 6.2.5p19) and function decls cannot
5560
            // have parameters of incomplete type.
5561
319k
            if (FTI.NumParams != 1 || 
FTI.isVariadic319k
) {
5562
18
              S.Diag(FTI.Params[i].IdentLoc, diag::err_void_only_param);
5563
18
              ParamTy = Context.IntTy;
5564
18
              Param->setType(ParamTy);
5565
319k
            } else if (FTI.Params[i].Ident) {
5566
              // Reject, but continue to parse 'int(void abc)'.
5567
12
              S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
5568
12
              ParamTy = Context.IntTy;
5569
12
              Param->setType(ParamTy);
5570
319k
            } else {
5571
              // Reject, but continue to parse 'float(const void)'.
5572
319k
              if (ParamTy.hasQualifiers())
5573
37
                S.Diag(DeclType.Loc, diag::err_void_param_qualified);
5574
5575
              // Do not add 'void' to the list.
5576
319k
              break;
5577
319k
            }
5578
94.3M
          } else if (ParamTy->isHalfType()) {
5579
            // Disallow half FP parameters.
5580
            // FIXME: This really should be in BuildFunctionType.
5581
419k
            if (S.getLangOpts().OpenCL) {
5582
8.38k
              if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5583
8.38k
                                                          S.getLangOpts())) {
5584
7
                S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5585
7
                    << ParamTy << 0;
5586
7
                D.setInvalidType();
5587
7
                Param->setInvalidDecl();
5588
7
              }
5589
411k
            } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5590
411k
                       
!S.Context.getTargetInfo().allowHalfArgsAndReturns()410k
) {
5591
5
              S.Diag(Param->getLocation(),
5592
5
                diag::err_parameters_retval_cannot_have_fp16_type) << 0;
5593
5
              D.setInvalidType();
5594
5
            }
5595
93.9M
          } else if (!FTI.hasPrototype) {
5596
192
            if (Context.isPromotableIntegerType(ParamTy)) {
5597
26
              ParamTy = Context.getPromotedIntegerType(ParamTy);
5598
26
              Param->setKNRPromoted(true);
5599
166
            } else if (const BuiltinType *BTy = ParamTy->getAs<BuiltinType>()) {
5600
137
              if (BTy->getKind() == BuiltinType::Float) {
5601
16
                ParamTy = Context.DoubleTy;
5602
16
                Param->setKNRPromoted(true);
5603
16
              }
5604
137
            }
5605
93.9M
          } else if (S.getLangOpts().OpenCL && 
ParamTy->isBlockPointerType()460k
) {
5606
            // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function.
5607
7
            S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5608
7
                << ParamTy << 1 /*hint off*/;
5609
7
            D.setInvalidType();
5610
7
          }
5611
5612
94.3M
          if (LangOpts.ObjCAutoRefCount && 
Param->hasAttr<NSConsumedAttr>()117k
) {
5613
78
            ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
5614
78
            HasAnyInterestingExtParameterInfos = true;
5615
78
          }
5616
5617
94.3M
          if (auto attr = Param->getAttr<ParameterABIAttr>()) {
5618
324
            ExtParameterInfos[i] =
5619
324
              ExtParameterInfos[i].withABI(attr->getABI());
5620
324
            HasAnyInterestingExtParameterInfos = true;
5621
324
          }
5622
5623
94.3M
          if (Param->hasAttr<PassObjectSizeAttr>()) {
5624
128
            ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
5625
128
            HasAnyInterestingExtParameterInfos = true;
5626
128
          }
5627
5628
94.3M
          if (Param->hasAttr<NoEscapeAttr>()) {
5629
8.42k
            ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
5630
8.42k
            HasAnyInterestingExtParameterInfos = true;
5631
8.42k
          }
5632
5633
94.3M
          ParamTys.push_back(ParamTy);
5634
94.3M
        }
5635
5636
36.9M
        if (HasAnyInterestingExtParameterInfos) {
5637
8.86k
          EPI.ExtParameterInfos = ExtParameterInfos.data();
5638
8.86k
          checkExtParameterInfos(S, ParamTys, EPI,
5639
8.86k
              [&](unsigned i) 
{ return FTI.Params[i].Param->getLocation(); }18
);
5640
8.86k
        }
5641
5642
36.9M
        SmallVector<QualType, 4> Exceptions;
5643
36.9M
        SmallVector<ParsedType, 2> DynamicExceptions;
5644
36.9M
        SmallVector<SourceRange, 2> DynamicExceptionRanges;
5645
36.9M
        Expr *NoexceptExpr = nullptr;
5646
5647
36.9M
        if (FTI.getExceptionSpecType() == EST_Dynamic) {
5648
          // FIXME: It's rather inefficient to have to split into two vectors
5649
          // here.
5650
320
          unsigned N = FTI.getNumExceptions();
5651
320
          DynamicExceptions.reserve(N);
5652
320
          DynamicExceptionRanges.reserve(N);
5653
703
          for (unsigned I = 0; I != N; 
++I383
) {
5654
383
            DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
5655
383
            DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
5656
383
          }
5657
36.9M
        } else if (isComputedNoexcept(FTI.getExceptionSpecType())) {
5658
23.5k
          NoexceptExpr = FTI.NoexceptExpr;
5659
23.5k
        }
5660
5661
36.9M
        S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
5662
36.9M
                                      FTI.getExceptionSpecType(),
5663
36.9M
                                      DynamicExceptions,
5664
36.9M
                                      DynamicExceptionRanges,
5665
36.9M
                                      NoexceptExpr,
5666
36.9M
                                      Exceptions,
5667
36.9M
                                      EPI.ExceptionSpec);
5668
5669
        // FIXME: Set address space from attrs for C++ mode here.
5670
        // OpenCLCPlusPlus: A class member function has an address space.
5671
36.9M
        auto IsClassMember = [&]() {
5672
27.4k
          return (!state.getDeclarator().getCXXScopeSpec().isEmpty() &&
5673
27.4k
                  state.getDeclarator()
5674
10
                          .getCXXScopeSpec()
5675
10
                          .getScopeRep()
5676
10
                          ->getKind() == NestedNameSpecifier::TypeSpec) ||
5677
27.4k
                 state.getDeclarator().getContext() ==
5678
27.4k
                     DeclaratorContext::Member ||
5679
27.4k
                 state.getDeclarator().getContext() ==
5680
27.2k
                     DeclaratorContext::LambdaExpr;
5681
27.4k
        };
5682
5683
36.9M
        if (state.getSema().getLangOpts().OpenCLCPlusPlus && 
IsClassMember()27.4k
) {
5684
160
          LangAS ASIdx = LangAS::Default;
5685
          // Take address space attr if any and mark as invalid to avoid adding
5686
          // them later while creating QualType.
5687
160
          if (FTI.MethodQualifiers)
5688
73
            for (ParsedAttr &attr : FTI.MethodQualifiers->getAttributes()) {
5689
61
              LangAS ASIdxNew = attr.asOpenCLLangAS();
5690
61
              if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew,
5691
61
                                                      attr.getLoc()))
5692
2
                D.setInvalidType(true);
5693
59
              else
5694
59
                ASIdx = ASIdxNew;
5695
61
            }
5696
          // If a class member function's address space is not set, set it to
5697
          // __generic.
5698
160
          LangAS AS =
5699
160
              (ASIdx == LangAS::Default ? 
S.getDefaultCXXMethodAddrSpace()102
5700
160
                                        : 
ASIdx58
);
5701
160
          EPI.TypeQuals.addAddressSpace(AS);
5702
160
        }
5703
36.9M
        T = Context.getFunctionType(T, ParamTys, EPI);
5704
36.9M
      }
5705
36.9M
      break;
5706
36.9M
    }
5707
36.9M
    case DeclaratorChunk::MemberPointer: {
5708
      // The scope spec must refer to a class, or be dependent.
5709
32.6k
      CXXScopeSpec &SS = DeclType.Mem.Scope();
5710
32.6k
      QualType ClsType;
5711
5712
      // Handle pointer nullability.
5713
32.6k
      inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
5714
32.6k
                              DeclType.EndLoc, DeclType.getAttrs(),
5715
32.6k
                              state.getDeclarator().getAttributePool());
5716
5717
32.6k
      if (SS.isInvalid()) {
5718
        // Avoid emitting extra errors if we already errored on the scope.
5719
1
        D.setInvalidType(true);
5720
32.6k
      } else if (S.isDependentScopeSpecifier(SS) ||
5721
32.6k
                 
isa_and_nonnull<CXXRecordDecl>(S.computeDeclContext(SS))3.94k
) {
5722
32.6k
        NestedNameSpecifier *NNS = SS.getScopeRep();
5723
32.6k
        NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
5724
32.6k
        switch (NNS->getKind()) {
5725
6
        case NestedNameSpecifier::Identifier:
5726
6
          ClsType = Context.getDependentNameType(
5727
6
              ElaboratedTypeKeyword::None, NNSPrefix, NNS->getAsIdentifier());
5728
6
          break;
5729
5730
0
        case NestedNameSpecifier::Namespace:
5731
0
        case NestedNameSpecifier::NamespaceAlias:
5732
0
        case NestedNameSpecifier::Global:
5733
0
        case NestedNameSpecifier::Super:
5734
0
          llvm_unreachable("Nested-name-specifier must name a type");
5735
5736
32.5k
        case NestedNameSpecifier::TypeSpec:
5737
32.5k
        case NestedNameSpecifier::TypeSpecWithTemplate:
5738
32.5k
          ClsType = QualType(NNS->getAsType(), 0);
5739
          // Note: if the NNS has a prefix and ClsType is a nondependent
5740
          // TemplateSpecializationType, then the NNS prefix is NOT included
5741
          // in ClsType; hence we wrap ClsType into an ElaboratedType.
5742
          // NOTE: in particular, no wrap occurs if ClsType already is an
5743
          // Elaborated, DependentName, or DependentTemplateSpecialization.
5744
32.5k
          if (isa<TemplateSpecializationType>(NNS->getAsType()))
5745
479
            ClsType = Context.getElaboratedType(ElaboratedTypeKeyword::None,
5746
479
                                                NNSPrefix, ClsType);
5747
32.5k
          break;
5748
32.6k
        }
5749
32.6k
      } else {
5750
6
        S.Diag(DeclType.Mem.Scope().getBeginLoc(),
5751
6
             diag::err_illegal_decl_mempointer_in_nonclass)
5752
6
          << (D.getIdentifier() ? D.getIdentifier()->getName() : 
"type name"0
)
5753
6
          << DeclType.Mem.Scope().getRange();
5754
6
        D.setInvalidType(true);
5755
6
      }
5756
5757
32.6k
      if (!ClsType.isNull())
5758
32.6k
        T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
5759
32.6k
                                     D.getIdentifier());
5760
7
      else
5761
7
        AreDeclaratorChunksValid = false;
5762
5763
32.6k
      if (T.isNull()) {
5764
7
        T = Context.IntTy;
5765
7
        D.setInvalidType(true);
5766
7
        AreDeclaratorChunksValid = false;
5767
32.6k
      } else if (DeclType.Mem.TypeQuals) {
5768
218
        T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
5769
218
      }
5770
32.6k
      break;
5771
32.6k
    }
5772
5773
249
    case DeclaratorChunk::Pipe: {
5774
249
      T = S.BuildReadPipeType(T, DeclType.Loc);
5775
249
      processTypeAttrs(state, T, TAL_DeclSpec,
5776
249
                       D.getMutableDeclSpec().getAttributes());
5777
249
      break;
5778
32.6k
    }
5779
49.5M
    }
5780
5781
49.5M
    if (T.isNull()) {
5782
355
      D.setInvalidType(true);
5783
355
      T = Context.IntTy;
5784
355
      AreDeclaratorChunksValid = false;
5785
355
    }
5786
5787
    // See if there are any attributes on this declarator chunk.
5788
49.5M
    processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs(),
5789
49.5M
                     S.IdentifyCUDATarget(D.getAttributes()));
5790
5791
49.5M
    if (DeclType.Kind != DeclaratorChunk::Paren) {
5792
49.2M
      if (ExpectNoDerefChunk && 
!IsNoDerefableChunk(DeclType)86
)
5793
6
        S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array);
5794
5795
49.2M
      ExpectNoDerefChunk = state.didParseNoDeref();
5796
49.2M
    }
5797
49.5M
  }
5798
5799
155M
  if (ExpectNoDerefChunk)
5800
10
    S.Diag(state.getDeclarator().getBeginLoc(),
5801
10
           diag::warn_noderef_on_non_pointer_or_array);
5802
5803
  // GNU warning -Wstrict-prototypes
5804
  //   Warn if a function declaration or definition is without a prototype.
5805
  //   This warning is issued for all kinds of unprototyped function
5806
  //   declarations (i.e. function type typedef, function pointer etc.)
5807
  //   C99 6.7.5.3p14:
5808
  //   The empty list in a function declarator that is not part of a definition
5809
  //   of that function specifies that no information about the number or types
5810
  //   of the parameters is supplied.
5811
  // See ActOnFinishFunctionBody() and MergeFunctionDecl() for handling of
5812
  // function declarations whose behavior changes in C23.
5813
155M
  if (!LangOpts.requiresStrictPrototypes()) {
5814
86.8M
    bool IsBlock = false;
5815
86.8M
    for (const DeclaratorChunk &DeclType : D.type_objects()) {
5816
26.5M
      switch (DeclType.Kind) {
5817
49.0k
      case DeclaratorChunk::BlockPointer:
5818
49.0k
        IsBlock = true;
5819
49.0k
        break;
5820
20.6M
      case DeclaratorChunk::Function: {
5821
20.6M
        const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5822
        // We suppress the warning when there's no LParen location, as this
5823
        // indicates the declaration was an implicit declaration, which gets
5824
        // warned about separately via -Wimplicit-function-declaration. We also
5825
        // suppress the warning when we know the function has a prototype.
5826
20.6M
        if (!FTI.hasPrototype && 
FTI.NumParams == 09.40k
&&
!FTI.isVariadic9.25k
&&
5827
20.6M
            
FTI.getLParenLoc().isValid()9.24k
)
5828
8.80k
          S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
5829
8.80k
              << IsBlock
5830
8.80k
              << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
5831
20.6M
        IsBlock = false;
5832
20.6M
        break;
5833
0
      }
5834
5.92M
      default:
5835
5.92M
        break;
5836
26.5M
      }
5837
26.5M
    }
5838
86.8M
  }
5839
5840
155M
  assert(!T.isNull() && "T must not be null after this point");
5841
5842
155M
  if (LangOpts.CPlusPlus && 
T->isFunctionType()69.1M
) {
5843
16.2M
    const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
5844
16.2M
    assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
5845
5846
    // C++ 8.3.5p4:
5847
    //   A cv-qualifier-seq shall only be part of the function type
5848
    //   for a nonstatic member function, the function type to which a pointer
5849
    //   to member refers, or the top-level function type of a function typedef
5850
    //   declaration.
5851
    //
5852
    // Core issue 547 also allows cv-qualifiers on function types that are
5853
    // top-level template type arguments.
5854
16.2M
    enum {
5855
16.2M
      NonMember,
5856
16.2M
      Member,
5857
16.2M
      ExplicitObjectMember,
5858
16.2M
      DeductionGuide
5859
16.2M
    } Kind = NonMember;
5860
16.2M
    if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
5861
1.61k
      Kind = DeductionGuide;
5862
16.2M
    else if (!D.getCXXScopeSpec().isSet()) {
5863
15.9M
      if ((D.getContext() == DeclaratorContext::Member ||
5864
15.9M
           
D.getContext() == DeclaratorContext::LambdaExpr14.2M
) &&
5865
15.9M
          
!D.getDeclSpec().isFriendSpecified()1.72M
)
5866
1.68M
        Kind = Member;
5867
15.9M
    } else {
5868
320k
      DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
5869
320k
      if (!DC || 
DC->isRecord()318k
)
5870
319k
        Kind = Member;
5871
320k
    }
5872
5873
16.2M
    if (Kind == Member) {
5874
2.00M
      unsigned I;
5875
2.00M
      if (D.isFunctionDeclarator(I)) {
5876
2.00M
        const DeclaratorChunk &Chunk = D.getTypeObject(I);
5877
2.00M
        if (Chunk.Fun.NumParams) {
5878
1.32M
          auto *P = dyn_cast_or_null<ParmVarDecl>(Chunk.Fun.Params->Param);
5879
1.32M
          if (P && P->isExplicitObjectParameter())
5880
209
            Kind = ExplicitObjectMember;
5881
1.32M
        }
5882
2.00M
      }
5883
2.00M
    }
5884
5885
    // C++11 [dcl.fct]p6 (w/DR1417):
5886
    // An attempt to specify a function type with a cv-qualifier-seq or a
5887
    // ref-qualifier (including by typedef-name) is ill-formed unless it is:
5888
    //  - the function type for a non-static member function,
5889
    //  - the function type to which a pointer to member refers,
5890
    //  - the top-level function type of a function typedef declaration or
5891
    //    alias-declaration,
5892
    //  - the type-id in the default argument of a type-parameter, or
5893
    //  - the type-id of a template-argument for a type-parameter
5894
    //
5895
    // FIXME: Checking this here is insufficient. We accept-invalid on:
5896
    //
5897
    //   template<typename T> struct S { void f(T); };
5898
    //   S<int() const> s;
5899
    //
5900
    // ... for instance.
5901
16.2M
    if (IsQualifiedFunction &&
5902
16.2M
        
!(573k
Kind == Member573k
&&
!D.isExplicitObjectMemberFunction()573k
&&
5903
573k
          
D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static573k
) &&
5904
16.2M
        
!IsTypedefName287
&&
D.getContext() != DeclaratorContext::TemplateArg240
&&
5905
16.2M
        
D.getContext() != DeclaratorContext::TemplateTypeArg59
) {
5906
57
      SourceLocation Loc = D.getBeginLoc();
5907
57
      SourceRange RemovalRange;
5908
57
      unsigned I;
5909
57
      if (D.isFunctionDeclarator(I)) {
5910
48
        SmallVector<SourceLocation, 4> RemovalLocs;
5911
48
        const DeclaratorChunk &Chunk = D.getTypeObject(I);
5912
48
        assert(Chunk.Kind == DeclaratorChunk::Function);
5913
5914
48
        if (Chunk.Fun.hasRefQualifier())
5915
14
          RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
5916
5917
48
        if (Chunk.Fun.hasMethodTypeQualifiers())
5918
36
          Chunk.Fun.MethodQualifiers->forEachQualifier(
5919
36
              [&](DeclSpec::TQ TypeQual, StringRef QualName,
5920
42
                  SourceLocation SL) { RemovalLocs.push_back(SL); });
5921
5922
48
        if (!RemovalLocs.empty()) {
5923
47
          llvm::sort(RemovalLocs,
5924
47
                     BeforeThanCompare<SourceLocation>(S.getSourceManager()));
5925
47
          RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
5926
47
          Loc = RemovalLocs.front();
5927
47
        }
5928
48
      }
5929
5930
57
      S.Diag(Loc, diag::err_invalid_qualified_function_type)
5931
57
        << Kind << D.isFunctionDeclarator() << T
5932
57
        << getFunctionQualifiersAsString(FnTy)
5933
57
        << FixItHint::CreateRemoval(RemovalRange);
5934
5935
      // Strip the cv-qualifiers and ref-qualifiers from the type.
5936
57
      FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
5937
57
      EPI.TypeQuals.removeCVRQualifiers();
5938
57
      EPI.RefQualifier = RQ_None;
5939
5940
57
      T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
5941
57
                                  EPI);
5942
      // Rebuild any parens around the identifier in the function type.
5943
58
      for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; 
++i1
) {
5944
49
        if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
5945
48
          break;
5946
1
        T = S.BuildParenType(T);
5947
1
      }
5948
57
    }
5949
16.2M
  }
5950
5951
  // Apply any undistributed attributes from the declaration or declarator.
5952
155M
  ParsedAttributesView NonSlidingAttrs;
5953
155M
  for (ParsedAttr &AL : D.getDeclarationAttributes()) {
5954
118k
    if (!AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
5955
118k
      NonSlidingAttrs.addAtEnd(&AL);
5956
118k
    }
5957
118k
  }
5958
155M
  processTypeAttrs(state, T, TAL_DeclName, NonSlidingAttrs);
5959
155M
  processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
5960
5961
  // Diagnose any ignored type attributes.
5962
155M
  state.diagnoseIgnoredTypeAttrs(T);
5963
5964
  // C++0x [dcl.constexpr]p9:
5965
  //  A constexpr specifier used in an object declaration declares the object
5966
  //  as const.
5967
155M
  if (D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr &&
5968
155M
      
T->isObjectType()474k
)
5969
202k
    T.addConst();
5970
5971
  // C++2a [dcl.fct]p4:
5972
  //   A parameter with volatile-qualified type is deprecated
5973
155M
  if (T.isVolatileQualified() && 
S.getLangOpts().CPlusPlus2043.6k
&&
5974
155M
      
(1.28k
D.getContext() == DeclaratorContext::Prototype1.28k
||
5975
1.28k
       
D.getContext() == DeclaratorContext::LambdaExprParameter1.26k
))
5976
21
    S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T;
5977
5978
  // If there was an ellipsis in the declarator, the declaration declares a
5979
  // parameter pack whose type may be a pack expansion type.
5980
155M
  if (D.hasEllipsis()) {
5981
    // C++0x [dcl.fct]p13:
5982
    //   A declarator-id or abstract-declarator containing an ellipsis shall
5983
    //   only be used in a parameter-declaration. Such a parameter-declaration
5984
    //   is a parameter pack (14.5.3). [...]
5985
116k
    switch (D.getContext()) {
5986
99.9k
    case DeclaratorContext::Prototype:
5987
100k
    case DeclaratorContext::LambdaExprParameter:
5988
100k
    case DeclaratorContext::RequiresExpr:
5989
      // C++0x [dcl.fct]p13:
5990
      //   [...] When it is part of a parameter-declaration-clause, the
5991
      //   parameter pack is a function parameter pack (14.5.3). The type T
5992
      //   of the declarator-id of the function parameter pack shall contain
5993
      //   a template parameter pack; each template parameter pack in T is
5994
      //   expanded by the function parameter pack.
5995
      //
5996
      // We represent function parameter packs as function parameters whose
5997
      // type is a pack expansion.
5998
100k
      if (!T->containsUnexpandedParameterPack() &&
5999
100k
          
(7
!LangOpts.CPlusPlus207
||
!T->getContainedAutoType()0
)) {
6000
7
        S.Diag(D.getEllipsisLoc(),
6001
7
             diag::err_function_parameter_pack_without_parameter_packs)
6002
7
          << T <<  D.getSourceRange();
6003
7
        D.setEllipsisLoc(SourceLocation());
6004
100k
      } else {
6005
100k
        T = Context.getPackExpansionType(T, std::nullopt,
6006
100k
                                         /*ExpectPackInType=*/false);
6007
100k
      }
6008
100k
      break;
6009
16.3k
    case DeclaratorContext::TemplateParam:
6010
      // C++0x [temp.param]p15:
6011
      //   If a template-parameter is a [...] is a parameter-declaration that
6012
      //   declares a parameter pack (8.3.5), then the template-parameter is a
6013
      //   template parameter pack (14.5.3).
6014
      //
6015
      // Note: core issue 778 clarifies that, if there are any unexpanded
6016
      // parameter packs in the type of the non-type template parameter, then
6017
      // it expands those parameter packs.
6018
16.3k
      if (T->containsUnexpandedParameterPack())
6019
48
        T = Context.getPackExpansionType(T, std::nullopt);
6020
16.3k
      else
6021
16.3k
        S.Diag(D.getEllipsisLoc(),
6022
16.3k
               LangOpts.CPlusPlus11
6023
16.3k
                 ? 
diag::warn_cxx98_compat_variadic_templates16.2k
6024
16.3k
                 : 
diag::ext_variadic_templates6
);
6025
16.3k
      break;
6026
6027
1
    case DeclaratorContext::File:
6028
1
    case DeclaratorContext::KNRTypeList:
6029
1
    case DeclaratorContext::ObjCParameter: // FIXME: special diagnostic here?
6030
1
    case DeclaratorContext::ObjCResult:    // FIXME: special diagnostic here?
6031
1
    case DeclaratorContext::TypeName:
6032
1
    case DeclaratorContext::FunctionalCast:
6033
1
    case DeclaratorContext::CXXNew:
6034
1
    case DeclaratorContext::AliasDecl:
6035
1
    case DeclaratorContext::AliasTemplate:
6036
2
    case DeclaratorContext::Member:
6037
3
    case DeclaratorContext::Block:
6038
4
    case DeclaratorContext::ForInit:
6039
4
    case DeclaratorContext::SelectionInit:
6040
5
    case DeclaratorContext::Condition:
6041
6
    case DeclaratorContext::CXXCatch:
6042
6
    case DeclaratorContext::ObjCCatch:
6043
6
    case DeclaratorContext::BlockLiteral:
6044
6
    case DeclaratorContext::LambdaExpr:
6045
6
    case DeclaratorContext::ConversionId:
6046
6
    case DeclaratorContext::TrailingReturn:
6047
6
    case DeclaratorContext::TrailingReturnVar:
6048
6
    case DeclaratorContext::TemplateArg:
6049
6
    case DeclaratorContext::TemplateTypeArg:
6050
6
    case DeclaratorContext::Association:
6051
      // FIXME: We may want to allow parameter packs in block-literal contexts
6052
      // in the future.
6053
6
      S.Diag(D.getEllipsisLoc(),
6054
6
             diag::err_ellipsis_in_declarator_not_parameter);
6055
6
      D.setEllipsisLoc(SourceLocation());
6056
6
      break;
6057
116k
    }
6058
116k
  }
6059
6060
155M
  assert(!T.isNull() && "T must not be null at the end of this function");
6061
155M
  if (!AreDeclaratorChunksValid)
6062
428
    return Context.getTrivialTypeSourceInfo(T);
6063
155M
  return GetTypeSourceInfoForDeclarator(state, T, TInfo);
6064
155M
}
6065
6066
/// GetTypeForDeclarator - Convert the type for the specified
6067
/// declarator to Type instances.
6068
///
6069
/// The result of this call will never be null, but the associated
6070
/// type may be a null type if there's an unrecoverable error.
6071
149M
TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
6072
  // Determine the type of the declarator. Not all forms of declarator
6073
  // have a type.
6074
6075
149M
  TypeProcessingState state(*this, D);
6076
6077
149M
  TypeSourceInfo *ReturnTypeInfo = nullptr;
6078
149M
  QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
6079
149M
  if (D.isPrototypeContext() && 
getLangOpts().ObjCAutoRefCount96.3M
)
6080
163k
    inferARCWriteback(state, T);
6081
6082
149M
  return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
6083
149M
}
6084
6085
static void transferARCOwnershipToDeclSpec(Sema &S,
6086
                                           QualType &declSpecTy,
6087
81
                                           Qualifiers::ObjCLifetime ownership) {
6088
81
  if (declSpecTy->isObjCRetainableType() &&
6089
81
      declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
6090
22
    Qualifiers qs;
6091
22
    qs.addObjCLifetime(ownership);
6092
22
    declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
6093
22
  }
6094
81
}
6095
6096
static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
6097
                                            Qualifiers::ObjCLifetime ownership,
6098
776
                                            unsigned chunkIndex) {
6099
776
  Sema &S = state.getSema();
6100
776
  Declarator &D = state.getDeclarator();
6101
6102
  // Look for an explicit lifetime attribute.
6103
776
  DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
6104
776
  if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership))
6105
17
    return;
6106
6107
759
  const char *attrStr = nullptr;
6108
759
  switch (ownership) {
6109
0
  case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
6110
0
  case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
6111
4
  case Qualifiers::OCL_Strong: attrStr = "strong"; break;
6112
2
  case Qualifiers::OCL_Weak: attrStr = "weak"; break;
6113
753
  case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
6114
759
  }
6115
6116
759
  IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
6117
759
  Arg->Ident = &S.Context.Idents.get(attrStr);
6118
759
  Arg->Loc = SourceLocation();
6119
6120
759
  ArgsUnion Args(Arg);
6121
6122
  // If there wasn't one, add one (with an invalid source location
6123
  // so that we don't make an AttributedType for it).
6124
759
  ParsedAttr *attr = D.getAttributePool().create(
6125
759
      &S.Context.Idents.get("objc_ownership"), SourceLocation(),
6126
759
      /*scope*/ nullptr, SourceLocation(),
6127
759
      /*args*/ &Args, 1, ParsedAttr::Form::GNU());
6128
759
  chunk.getAttrs().addAtEnd(attr);
6129
  // TODO: mark whether we did this inference?
6130
759
}
6131
6132
/// Used for transferring ownership in casts resulting in l-values.
6133
static void transferARCOwnership(TypeProcessingState &state,
6134
                                 QualType &declSpecTy,
6135
488
                                 Qualifiers::ObjCLifetime ownership) {
6136
488
  Sema &S = state.getSema();
6137
488
  Declarator &D = state.getDeclarator();
6138
6139
488
  int inner = -1;
6140
488
  bool hasIndirection = false;
6141
690
  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; 
++i202
) {
6142
202
    DeclaratorChunk &chunk = D.getTypeObject(i);
6143
202
    switch (chunk.Kind) {
6144
0
    case DeclaratorChunk::Paren:
6145
      // Ignore parens.
6146
0
      break;
6147
6148
0
    case DeclaratorChunk::Array:
6149
5
    case DeclaratorChunk::Reference:
6150
202
    case DeclaratorChunk::Pointer:
6151
202
      if (inner != -1)
6152
34
        hasIndirection = true;
6153
202
      inner = i;
6154
202
      break;
6155
6156
0
    case DeclaratorChunk::BlockPointer:
6157
0
      if (inner != -1)
6158
0
        transferARCOwnershipToDeclaratorChunk(state, ownership, i);
6159
0
      return;
6160
6161
0
    case DeclaratorChunk::Function:
6162
0
    case DeclaratorChunk::MemberPointer:
6163
0
    case DeclaratorChunk::Pipe:
6164
0
      return;
6165
202
    }
6166
202
  }
6167
6168
488
  if (inner == -1)
6169
320
    return;
6170
6171
168
  DeclaratorChunk &chunk = D.getTypeObject(inner);
6172
168
  if (chunk.Kind == DeclaratorChunk::Pointer) {
6173
165
    if (declSpecTy->isObjCRetainableType())
6174
78
      return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
6175
87
    if (declSpecTy->isObjCObjectType() && 
hasIndirection38
)
6176
23
      return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
6177
87
  } else {
6178
3
    assert(chunk.Kind == DeclaratorChunk::Array ||
6179
3
           chunk.Kind == DeclaratorChunk::Reference);
6180
3
    return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
6181
3
  }
6182
168
}
6183
6184
6.19M
TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
6185
6.19M
  TypeProcessingState state(*this, D);
6186
6187
6.19M
  TypeSourceInfo *ReturnTypeInfo = nullptr;
6188
6.19M
  QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
6189
6190
6.19M
  if (getLangOpts().ObjC) {
6191
362k
    Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
6192
362k
    if (ownership != Qualifiers::OCL_None)
6193
488
      transferARCOwnership(state, declSpecTy, ownership);
6194
362k
  }
6195
6196
6.19M
  return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
6197
6.19M
}
6198
6199
static void fillAttributedTypeLoc(AttributedTypeLoc TL,
6200
3.27M
                                  TypeProcessingState &State) {
6201
3.27M
  TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr()));
6202
3.27M
}
6203
6204
static void fillMatrixTypeLoc(MatrixTypeLoc MTL,
6205
0
                              const ParsedAttributesView &Attrs) {
6206
0
  for (const ParsedAttr &AL : Attrs) {
6207
0
    if (AL.getKind() == ParsedAttr::AT_MatrixType) {
6208
0
      MTL.setAttrNameLoc(AL.getLoc());
6209
0
      MTL.setAttrRowOperand(AL.getArgAsExpr(0));
6210
0
      MTL.setAttrColumnOperand(AL.getArgAsExpr(1));
6211
0
      MTL.setAttrOperandParensRange(SourceRange());
6212
0
      return;
6213
0
    }
6214
0
  }
6215
6216
0
  llvm_unreachable("no matrix_type attribute found at the expected location!");
6217
0
}
6218
6219
namespace {
6220
  class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
6221
    Sema &SemaRef;
6222
    ASTContext &Context;
6223
    TypeProcessingState &State;
6224
    const DeclSpec &DS;
6225
6226
  public:
6227
    TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State,
6228
                      const DeclSpec &DS)
6229
155M
        : SemaRef(S), Context(Context), State(State), DS(DS) {}
6230
6231
1.70M
    void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6232
1.70M
      Visit(TL.getModifiedLoc());
6233
1.70M
      fillAttributedTypeLoc(TL, State);
6234
1.70M
    }
6235
37
    void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6236
37
      Visit(TL.getWrappedLoc());
6237
37
    }
6238
140k
    void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6239
140k
      Visit(TL.getInnerLoc());
6240
140k
      TL.setExpansionLoc(
6241
140k
          State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
6242
140k
    }
6243
522k
    void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6244
522k
      Visit(TL.getUnqualifiedLoc());
6245
522k
    }
6246
    // Allow to fill pointee's type locations, e.g.,
6247
    //   int __attr * __attr * __attr *p;
6248
4
    void VisitPointerTypeLoc(PointerTypeLoc TL) { Visit(TL.getNextTypeLoc()); }
6249
130M
    void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6250
130M
      TL.setNameLoc(DS.getTypeSpecTypeLoc());
6251
130M
    }
6252
1.02M
    void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6253
1.02M
      TL.setNameLoc(DS.getTypeSpecTypeLoc());
6254
      // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
6255
      // addition field. What we have is good enough for display of location
6256
      // of 'fixit' on interface name.
6257
1.02M
      TL.setNameEndLoc(DS.getEndLoc());
6258
1.02M
    }
6259
134k
    void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6260
134k
      TypeSourceInfo *RepTInfo = nullptr;
6261
134k
      Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
6262
134k
      TL.copy(RepTInfo->getTypeLoc());
6263
134k
    }
6264
15.6k
    void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6265
15.6k
      TypeSourceInfo *RepTInfo = nullptr;
6266
15.6k
      Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
6267
15.6k
      TL.copy(RepTInfo->getTypeLoc());
6268
15.6k
    }
6269
0
    void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
6270
0
      TypeSourceInfo *TInfo = nullptr;
6271
0
      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6272
6273
      // If we got no declarator info from previous Sema routines,
6274
      // just fill with the typespec loc.
6275
0
      if (!TInfo) {
6276
0
        TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
6277
0
        return;
6278
0
      }
6279
6280
0
      TypeLoc OldTL = TInfo->getTypeLoc();
6281
0
      if (TInfo->getType()->getAs<ElaboratedType>()) {
6282
0
        ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
6283
0
        TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
6284
0
            .castAs<TemplateSpecializationTypeLoc>();
6285
0
        TL.copy(NamedTL);
6286
0
      } else {
6287
0
        TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
6288
0
        assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
6289
0
      }
6290
6291
0
    }
6292
3.25k
    void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6293
3.25k
      assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr ||
6294
3.25k
             DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualExpr);
6295
3.25k
      TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
6296
3.25k
      TL.setParensRange(DS.getTypeofParensRange());
6297
3.25k
    }
6298
157
    void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6299
157
      assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType ||
6300
157
             DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualType);
6301
157
      TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
6302
157
      TL.setParensRange(DS.getTypeofParensRange());
6303
157
      assert(DS.getRepAsType());
6304
157
      TypeSourceInfo *TInfo = nullptr;
6305
157
      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6306
157
      TL.setUnmodifiedTInfo(TInfo);
6307
157
    }
6308
62.1k
    void VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6309
62.1k
      assert(DS.getTypeSpecType() == DeclSpec::TST_decltype);
6310
62.1k
      TL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
6311
62.1k
      TL.setRParenLoc(DS.getTypeofParensRange().getEnd());
6312
62.1k
    }
6313
11.8k
    void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6314
11.8k
      assert(DS.isTransformTypeTrait(DS.getTypeSpecType()));
6315
11.8k
      TL.setKWLoc(DS.getTypeSpecTypeLoc());
6316
11.8k
      TL.setParensRange(DS.getTypeofParensRange());
6317
11.8k
      assert(DS.getRepAsType());
6318
11.8k
      TypeSourceInfo *TInfo = nullptr;
6319
11.8k
      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6320
11.8k
      TL.setUnderlyingTInfo(TInfo);
6321
11.8k
    }
6322
11.9M
    void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6323
      // By default, use the source location of the type specifier.
6324
11.9M
      TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
6325
11.9M
      if (TL.needsExtraLocalData()) {
6326
        // Set info for the written builtin specifiers.
6327
4.66M
        TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
6328
        // Try to have a meaningful source location.
6329
4.66M
        if (TL.getWrittenSignSpec() != TypeSpecifierSign::Unspecified)
6330
797k
          TL.expandBuiltinRange(DS.getTypeSpecSignLoc());
6331
4.66M
        if (TL.getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified)
6332
962k
          TL.expandBuiltinRange(DS.getTypeSpecWidthRange());
6333
4.66M
      }
6334
11.9M
    }
6335
135M
    void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
6336
135M
      if (DS.getTypeSpecType() == TST_typename) {
6337
134M
        TypeSourceInfo *TInfo = nullptr;
6338
134M
        Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6339
134M
        if (TInfo)
6340
2.09M
          if (auto ETL = TInfo->getTypeLoc().getAs<ElaboratedTypeLoc>()) {
6341
2.09M
            TL.copy(ETL);
6342
2.09M
            return;
6343
2.09M
          }
6344
134M
      }
6345
133M
      const ElaboratedType *T = TL.getTypePtr();
6346
133M
      TL.setElaboratedKeywordLoc(T->getKeyword() != ElaboratedTypeKeyword::None
6347
133M
                                     ? 
DS.getTypeSpecTypeLoc()1.40M
6348
133M
                                     : 
SourceLocation()132M
);
6349
133M
      const CXXScopeSpec& SS = DS.getTypeSpecScope();
6350
133M
      TL.setQualifierLoc(SS.getWithLocInContext(Context));
6351
133M
      Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
6352
133M
    }
6353
453k
    void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6354
453k
      assert(DS.getTypeSpecType() == TST_typename);
6355
453k
      TypeSourceInfo *TInfo = nullptr;
6356
453k
      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6357
453k
      assert(TInfo);
6358
453k
      TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
6359
453k
    }
6360
    void VisitDependentTemplateSpecializationTypeLoc(
6361
12.0k
                                 DependentTemplateSpecializationTypeLoc TL) {
6362
12.0k
      assert(DS.getTypeSpecType() == TST_typename);
6363
12.0k
      TypeSourceInfo *TInfo = nullptr;
6364
12.0k
      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6365
12.0k
      assert(TInfo);
6366
12.0k
      TL.copy(
6367
12.0k
          TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
6368
12.0k
    }
6369
84.4k
    void VisitAutoTypeLoc(AutoTypeLoc TL) {
6370
84.4k
      assert(DS.getTypeSpecType() == TST_auto ||
6371
84.4k
             DS.getTypeSpecType() == TST_decltype_auto ||
6372
84.4k
             DS.getTypeSpecType() == TST_auto_type ||
6373
84.4k
             DS.getTypeSpecType() == TST_unspecified);
6374
84.4k
      TL.setNameLoc(DS.getTypeSpecTypeLoc());
6375
84.4k
      if (DS.getTypeSpecType() == TST_decltype_auto)
6376
929
        TL.setRParenLoc(DS.getTypeofParensRange().getEnd());
6377
84.4k
      if (!DS.isConstrainedAuto())
6378
84.3k
        return;
6379
162
      TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId();
6380
162
      if (!TemplateId)
6381
8
        return;
6382
6383
154
      NestedNameSpecifierLoc NNS =
6384
154
          (DS.getTypeSpecScope().isNotEmpty()
6385
154
               ? 
DS.getTypeSpecScope().getWithLocInContext(Context)15
6386
154
               : 
NestedNameSpecifierLoc()139
);
6387
154
      TemplateArgumentListInfo TemplateArgsInfo(TemplateId->LAngleLoc,
6388
154
                                                TemplateId->RAngleLoc);
6389
154
      if (TemplateId->NumArgs > 0) {
6390
48
        ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6391
48
                                           TemplateId->NumArgs);
6392
48
        SemaRef.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
6393
48
      }
6394
154
      DeclarationNameInfo DNI = DeclarationNameInfo(
6395
154
          TL.getTypePtr()->getTypeConstraintConcept()->getDeclName(),
6396
154
          TemplateId->TemplateNameLoc);
6397
154
      auto *CR = ConceptReference::Create(
6398
154
          Context, NNS, TemplateId->TemplateKWLoc, DNI,
6399
154
          /*FoundDecl=*/nullptr,
6400
154
          /*NamedDecl=*/TL.getTypePtr()->getTypeConstraintConcept(),
6401
154
          ASTTemplateArgumentListInfo::Create(Context, TemplateArgsInfo));
6402
154
      TL.setConceptReference(CR);
6403
154
    }
6404
2.24M
    void VisitTagTypeLoc(TagTypeLoc TL) {
6405
2.24M
      TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
6406
2.24M
    }
6407
3.30k
    void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6408
      // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
6409
      // or an _Atomic qualifier.
6410
3.30k
      if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
6411
3.09k
        TL.setKWLoc(DS.getTypeSpecTypeLoc());
6412
3.09k
        TL.setParensRange(DS.getTypeofParensRange());
6413
6414
3.09k
        TypeSourceInfo *TInfo = nullptr;
6415
3.09k
        Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6416
3.09k
        assert(TInfo);
6417
3.09k
        TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
6418
3.09k
      } else {
6419
207
        TL.setKWLoc(DS.getAtomicSpecLoc());
6420
        // No parens, to indicate this was spelled as an _Atomic qualifier.
6421
207
        TL.setParensRange(SourceRange());
6422
207
        Visit(TL.getValueLoc());
6423
207
      }
6424
3.30k
    }
6425
6426
0
    void VisitPipeTypeLoc(PipeTypeLoc TL) {
6427
0
      TL.setKWLoc(DS.getTypeSpecTypeLoc());
6428
6429
0
      TypeSourceInfo *TInfo = nullptr;
6430
0
      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6431
0
      TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
6432
0
    }
6433
6434
0
    void VisitExtIntTypeLoc(BitIntTypeLoc TL) {
6435
0
      TL.setNameLoc(DS.getTypeSpecTypeLoc());
6436
0
    }
6437
6438
0
    void VisitDependentExtIntTypeLoc(DependentBitIntTypeLoc TL) {
6439
0
      TL.setNameLoc(DS.getTypeSpecTypeLoc());
6440
0
    }
6441
6442
7.12M
    void VisitTypeLoc(TypeLoc TL) {
6443
      // FIXME: add other typespec types and change this to an assert.
6444
7.12M
      TL.initialize(Context, DS.getTypeSpecTypeLoc());
6445
7.12M
    }
6446
  };
6447
6448
  class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
6449
    ASTContext &Context;
6450
    TypeProcessingState &State;
6451
    const DeclaratorChunk &Chunk;
6452
6453
  public:
6454
    DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State,
6455
                        const DeclaratorChunk &Chunk)
6456
49.5M
        : Context(Context), State(State), Chunk(Chunk) {}
6457
6458
0
    void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6459
0
      llvm_unreachable("qualified type locs not expected here!");
6460
0
    }
6461
0
    void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6462
0
      llvm_unreachable("decayed type locs not expected here!");
6463
0
    }
6464
6465
0
    void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6466
0
      fillAttributedTypeLoc(TL, State);
6467
0
    }
6468
0
    void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6469
      // nothing
6470
0
    }
6471
0
    void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6472
      // nothing
6473
0
    }
6474
61.4k
    void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6475
61.4k
      assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
6476
61.4k
      TL.setCaretLoc(Chunk.Loc);
6477
61.4k
    }
6478
8.64M
    void VisitPointerTypeLoc(PointerTypeLoc TL) {
6479
8.64M
      assert(Chunk.Kind == DeclaratorChunk::Pointer);
6480
8.64M
      TL.setStarLoc(Chunk.Loc);
6481
8.64M
    }
6482
1.16M
    void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6483
1.16M
      assert(Chunk.Kind == DeclaratorChunk::Pointer);
6484
1.16M
      TL.setStarLoc(Chunk.Loc);
6485
1.16M
    }
6486
32.5k
    void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6487
32.5k
      assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
6488
32.5k
      const CXXScopeSpec& SS = Chunk.Mem.Scope();
6489
32.5k
      NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
6490
6491
32.5k
      const Type* ClsTy = TL.getClass();
6492
32.5k
      QualType ClsQT = QualType(ClsTy, 0);
6493
32.5k
      TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
6494
      // Now copy source location info into the type loc component.
6495
32.5k
      TypeLoc ClsTL = ClsTInfo->getTypeLoc();
6496
32.5k
      switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
6497
6
      case NestedNameSpecifier::Identifier:
6498
6
        assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
6499
6
        {
6500
6
          DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
6501
6
          DNTLoc.setElaboratedKeywordLoc(SourceLocation());
6502
6
          DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
6503
6
          DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
6504
6
        }
6505
6
        break;
6506
6507
32.5k
      case NestedNameSpecifier::TypeSpec:
6508
32.5k
      case NestedNameSpecifier::TypeSpecWithTemplate:
6509
32.5k
        if (isa<ElaboratedType>(ClsTy)) {
6510
479
          ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
6511
479
          ETLoc.setElaboratedKeywordLoc(SourceLocation());
6512
479
          ETLoc.setQualifierLoc(NNSLoc.getPrefix());
6513
479
          TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
6514
479
          NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
6515
32.1k
        } else {
6516
32.1k
          ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
6517
32.1k
        }
6518
32.5k
        break;
6519
6520
0
      case NestedNameSpecifier::Namespace:
6521
0
      case NestedNameSpecifier::NamespaceAlias:
6522
0
      case NestedNameSpecifier::Global:
6523
0
      case NestedNameSpecifier::Super:
6524
0
        llvm_unreachable("Nested-name-specifier must name a type");
6525
32.5k
      }
6526
6527
      // Finally fill in MemberPointerLocInfo fields.
6528
32.5k
      TL.setStarLoc(Chunk.Mem.StarLoc);
6529
32.5k
      TL.setClassTInfo(ClsTInfo);
6530
32.5k
    }
6531
1.72M
    void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6532
1.72M
      assert(Chunk.Kind == DeclaratorChunk::Reference);
6533
      // 'Amp' is misleading: this might have been originally
6534
      /// spelled with AmpAmp.
6535
1.72M
      TL.setAmpLoc(Chunk.Loc);
6536
1.72M
    }
6537
310k
    void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6538
310k
      assert(Chunk.Kind == DeclaratorChunk::Reference);
6539
310k
      assert(!Chunk.Ref.LValueRef);
6540
310k
      TL.setAmpAmpLoc(Chunk.Loc);
6541
310k
    }
6542
352k
    void VisitArrayTypeLoc(ArrayTypeLoc TL) {
6543
352k
      assert(Chunk.Kind == DeclaratorChunk::Array);
6544
352k
      TL.setLBracketLoc(Chunk.Loc);
6545
352k
      TL.setRBracketLoc(Chunk.EndLoc);
6546
352k
      TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
6547
352k
    }
6548
36.9M
    void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6549
36.9M
      assert(Chunk.Kind == DeclaratorChunk::Function);
6550
36.9M
      TL.setLocalRangeBegin(Chunk.Loc);
6551
36.9M
      TL.setLocalRangeEnd(Chunk.EndLoc);
6552
6553
36.9M
      const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
6554
36.9M
      TL.setLParenLoc(FTI.getLParenLoc());
6555
36.9M
      TL.setRParenLoc(FTI.getRParenLoc());
6556
131M
      for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; 
++i94.3M
) {
6557
94.3M
        ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
6558
94.3M
        TL.setParam(tpi++, Param);
6559
94.3M
      }
6560
36.9M
      TL.setExceptionSpecRange(FTI.getExceptionSpecRange());
6561
36.9M
    }
6562
315k
    void VisitParenTypeLoc(ParenTypeLoc TL) {
6563
315k
      assert(Chunk.Kind == DeclaratorChunk::Paren);
6564
315k
      TL.setLParenLoc(Chunk.Loc);
6565
315k
      TL.setRParenLoc(Chunk.EndLoc);
6566
315k
    }
6567
249
    void VisitPipeTypeLoc(PipeTypeLoc TL) {
6568
249
      assert(Chunk.Kind == DeclaratorChunk::Pipe);
6569
249
      TL.setKWLoc(Chunk.Loc);
6570
249
    }
6571
0
    void VisitBitIntTypeLoc(BitIntTypeLoc TL) {
6572
0
      TL.setNameLoc(Chunk.Loc);
6573
0
    }
6574
0
    void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6575
0
      TL.setExpansionLoc(Chunk.Loc);
6576
0
    }
6577
6
    void VisitVectorTypeLoc(VectorTypeLoc TL) { TL.setNameLoc(Chunk.Loc); }
6578
18
    void VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL) {
6579
18
      TL.setNameLoc(Chunk.Loc);
6580
18
    }
6581
0
    void VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6582
0
      TL.setNameLoc(Chunk.Loc);
6583
0
    }
6584
    void
6585
0
    VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL) {
6586
0
      TL.setNameLoc(Chunk.Loc);
6587
0
    }
6588
0
    void VisitMatrixTypeLoc(MatrixTypeLoc TL) {
6589
0
      fillMatrixTypeLoc(TL, Chunk.getAttrs());
6590
0
    }
6591
6592
0
    void VisitTypeLoc(TypeLoc TL) {
6593
0
      llvm_unreachable("unsupported TypeLoc kind in declarator!");
6594
0
    }
6595
  };
6596
} // end anonymous namespace
6597
6598
18
static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
6599
18
  SourceLocation Loc;
6600
18
  switch (Chunk.Kind) {
6601
0
  case DeclaratorChunk::Function:
6602
0
  case DeclaratorChunk::Array:
6603
0
  case DeclaratorChunk::Paren:
6604
0
  case DeclaratorChunk::Pipe:
6605
0
    llvm_unreachable("cannot be _Atomic qualified");
6606
6607
16
  case DeclaratorChunk::Pointer:
6608
16
    Loc = Chunk.Ptr.AtomicQualLoc;
6609
16
    break;
6610
6611
0
  case DeclaratorChunk::BlockPointer:
6612
0
  case DeclaratorChunk::Reference:
6613
2
  case DeclaratorChunk::MemberPointer:
6614
    // FIXME: Provide a source location for the _Atomic keyword.
6615
2
    break;
6616
18
  }
6617
6618
18
  ATL.setKWLoc(Loc);
6619
18
  ATL.setParensRange(SourceRange());
6620
18
}
6621
6622
static void
6623
fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL,
6624
1
                                 const ParsedAttributesView &Attrs) {
6625
1
  for (const ParsedAttr &AL : Attrs) {
6626
1
    if (AL.getKind() == ParsedAttr::AT_AddressSpace) {
6627
1
      DASTL.setAttrNameLoc(AL.getLoc());
6628
1
      DASTL.setAttrExprOperand(AL.getArgAsExpr(0));
6629
1
      DASTL.setAttrOperandParensRange(SourceRange());
6630
1
      return;
6631
1
    }
6632
1
  }
6633
6634
0
  llvm_unreachable(
6635
0
      "no address_space attribute found at the expected location!");
6636
0
}
6637
6638
/// Create and instantiate a TypeSourceInfo with type source information.
6639
///
6640
/// \param T QualType referring to the type as written in source code.
6641
///
6642
/// \param ReturnTypeInfo For declarators whose return type does not show
6643
/// up in the normal place in the declaration specifiers (such as a C++
6644
/// conversion function), this pointer will refer to a type source information
6645
/// for that return type.
6646
static TypeSourceInfo *
6647
GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
6648
155M
                               QualType T, TypeSourceInfo *ReturnTypeInfo) {
6649
155M
  Sema &S = State.getSema();
6650
155M
  Declarator &D = State.getDeclarator();
6651
6652
155M
  TypeSourceInfo *TInfo = S.Context.CreateTypeSourceInfo(T);
6653
155M
  UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
6654
6655
  // Handle parameter packs whose type is a pack expansion.
6656
155M
  if (isa<PackExpansionType>(T)) {
6657
100k
    CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
6658
100k
    CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6659
100k
  }
6660
6661
205M
  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; 
++i49.5M
) {
6662
    // Microsoft property fields can have multiple sizeless array chunks
6663
    // (i.e. int x[][][]). Don't create more than one level of incomplete array.
6664
49.5M
    if (CurrTL.getTypeLocClass() == TypeLoc::IncompleteArray && 
e != 141.9k
&&
6665
49.5M
        
D.getDeclSpec().getAttributes().hasMSPropertyAttr()8.72k
)
6666
33
      continue;
6667
6668
    // An AtomicTypeLoc might be produced by an atomic qualifier in this
6669
    // declarator chunk.
6670
49.5M
    if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
6671
18
      fillAtomicQualLoc(ATL, D.getTypeObject(i));
6672
18
      CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
6673
18
    }
6674
6675
49.5M
    bool HasDesugaredTypeLoc = true;
6676
100M
    while (HasDesugaredTypeLoc) {
6677
51.2M
      switch (CurrTL.getTypeLocClass()) {
6678
97.8k
      case TypeLoc::MacroQualified: {
6679
97.8k
        auto TL = CurrTL.castAs<MacroQualifiedTypeLoc>();
6680
97.8k
        TL.setExpansionLoc(
6681
97.8k
            State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
6682
97.8k
        CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6683
97.8k
        break;
6684
0
      }
6685
6686
1.57M
      case TypeLoc::Attributed: {
6687
1.57M
        auto TL = CurrTL.castAs<AttributedTypeLoc>();
6688
1.57M
        fillAttributedTypeLoc(TL, State);
6689
1.57M
        CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6690
1.57M
        break;
6691
0
      }
6692
6693
0
      case TypeLoc::Adjusted:
6694
30
      case TypeLoc::BTFTagAttributed: {
6695
30
        CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6696
30
        break;
6697
0
      }
6698
6699
1
      case TypeLoc::DependentAddressSpace: {
6700
1
        auto TL = CurrTL.castAs<DependentAddressSpaceTypeLoc>();
6701
1
        fillDependentAddressSpaceTypeLoc(TL, D.getTypeObject(i).getAttrs());
6702
1
        CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc();
6703
1
        break;
6704
0
      }
6705
6706
49.5M
      default:
6707
49.5M
        HasDesugaredTypeLoc = false;
6708
49.5M
        break;
6709
51.2M
      }
6710
51.2M
    }
6711
6712
49.5M
    DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL);
6713
49.5M
    CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6714
49.5M
  }
6715
6716
  // If we have different source information for the return type, use
6717
  // that.  This really only applies to C++ conversion functions.
6718
155M
  if (ReturnTypeInfo) {
6719
30.7k
    TypeLoc TL = ReturnTypeInfo->getTypeLoc();
6720
30.7k
    assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
6721
30.7k
    memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
6722
155M
  } else {
6723
155M
    TypeSpecLocFiller(S, S.Context, State, D.getDeclSpec()).Visit(CurrTL);
6724
155M
  }
6725
6726
155M
  return TInfo;
6727
155M
}
6728
6729
/// Create a LocInfoType to hold the given QualType and TypeSourceInfo.
6730
18.6M
ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
6731
  // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
6732
  // and Sema during declaration parsing. Try deallocating/caching them when
6733
  // it's appropriate, instead of allocating them and keeping them around.
6734
18.6M
  LocInfoType *LocT = (LocInfoType *)BumpAlloc.Allocate(sizeof(LocInfoType),
6735
18.6M
                                                        alignof(LocInfoType));
6736
18.6M
  new (LocT) LocInfoType(T, TInfo);
6737
18.6M
  assert(LocT->getTypeClass() != T->getTypeClass() &&
6738
18.6M
         "LocInfoType's TypeClass conflicts with an existing Type class");
6739
18.6M
  return ParsedType::make(QualType(LocT, 0));
6740
18.6M
}
6741
6742
void LocInfoType::getAsStringInternal(std::string &Str,
6743
0
                                      const PrintingPolicy &Policy) const {
6744
0
  llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
6745
0
         " was used directly instead of getting the QualType through"
6746
0
         " GetTypeFromParser");
6747
0
}
6748
6749
9.28M
TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
6750
  // C99 6.7.6: Type names have no identifier.  This is already validated by
6751
  // the parser.
6752
9.28M
  assert(D.getIdentifier() == nullptr &&
6753
9.28M
         "Type name should have no identifier!");
6754
6755
9.28M
  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6756
9.28M
  QualType T = TInfo->getType();
6757
9.28M
  if (D.isInvalidType())
6758
485
    return true;
6759
6760
  // Make sure there are no unused decl attributes on the declarator.
6761
  // We don't want to do this for ObjC parameters because we're going
6762
  // to apply them to the actual parameter declaration.
6763
  // Likewise, we don't want to do this for alias declarations, because
6764
  // we are actually going to build a declaration from this eventually.
6765
9.28M
  if (D.getContext() != DeclaratorContext::ObjCParameter &&
6766
9.28M
      
D.getContext() != DeclaratorContext::AliasDecl8.31M
&&
6767
9.28M
      
D.getContext() != DeclaratorContext::AliasTemplate8.10M
)
6768
8.02M
    checkUnusedDeclAttributes(D);
6769
6770
9.28M
  if (getLangOpts().CPlusPlus) {
6771
    // Check that there are no default arguments (C++ only).
6772
7.45M
    CheckExtraCXXDefaultArguments(D);
6773
7.45M
  }
6774
6775
9.28M
  return CreateParsedType(T, TInfo);
6776
9.28M
}
6777
6778
112k
ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
6779
112k
  QualType T = Context.getObjCInstanceType();
6780
112k
  TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
6781
112k
  return CreateParsedType(T, TInfo);
6782
112k
}
6783
6784
//===----------------------------------------------------------------------===//
6785
// Type Attribute Processing
6786
//===----------------------------------------------------------------------===//
6787
6788
/// Build an AddressSpace index from a constant expression and diagnose any
6789
/// errors related to invalid address_spaces. Returns true on successfully
6790
/// building an AddressSpace index.
6791
static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx,
6792
                                   const Expr *AddrSpace,
6793
1.03k
                                   SourceLocation AttrLoc) {
6794
1.03k
  if (!AddrSpace->isValueDependent()) {
6795
986
    std::optional<llvm::APSInt> OptAddrSpace =
6796
986
        AddrSpace->getIntegerConstantExpr(S.Context);
6797
986
    if (!OptAddrSpace) {
6798
1
      S.Diag(AttrLoc, diag::err_attribute_argument_type)
6799
1
          << "'address_space'" << AANT_ArgumentIntegerConstant
6800
1
          << AddrSpace->getSourceRange();
6801
1
      return false;
6802
1
    }
6803
985
    llvm::APSInt &addrSpace = *OptAddrSpace;
6804
6805
    // Bounds checking.
6806
985
    if (addrSpace.isSigned()) {
6807
978
      if (addrSpace.isNegative()) {
6808
2
        S.Diag(AttrLoc, diag::err_attribute_address_space_negative)
6809
2
            << AddrSpace->getSourceRange();
6810
2
        return false;
6811
2
      }
6812
976
      addrSpace.setIsSigned(false);
6813
976
    }
6814
6815
983
    llvm::APSInt max(addrSpace.getBitWidth());
6816
983
    max =
6817
983
        Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace;
6818
6819
983
    if (addrSpace > max) {
6820
4
      S.Diag(AttrLoc, diag::err_attribute_address_space_too_high)
6821
4
          << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange();
6822
4
      return false;
6823
4
    }
6824
6825
979
    ASIdx =
6826
979
        getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue()));
6827
979
    return true;
6828
983
  }
6829
6830
  // Default value for DependentAddressSpaceTypes
6831
53
  ASIdx = LangAS::Default;
6832
53
  return true;
6833
1.03k
}
6834
6835
/// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression
6836
/// is uninstantiated. If instantiated it will apply the appropriate address
6837
/// space to the type. This function allows dependent template variables to be
6838
/// used in conjunction with the address_space attribute
6839
QualType Sema::BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
6840
1.03k
                                     SourceLocation AttrLoc) {
6841
1.03k
  if (!AddrSpace->isValueDependent()) {
6842
979
    if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx,
6843
979
                                            AttrLoc))
6844
2
      return QualType();
6845
6846
977
    return Context.getAddrSpaceQualType(T, ASIdx);
6847
979
  }
6848
6849
  // A check with similar intentions as checking if a type already has an
6850
  // address space except for on a dependent types, basically if the
6851
  // current type is already a DependentAddressSpaceType then its already
6852
  // lined up to have another address space on it and we can't have
6853
  // multiple address spaces on the one pointer indirection
6854
53
  if (T->getAs<DependentAddressSpaceType>()) {
6855
2
    Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
6856
2
    return QualType();
6857
2
  }
6858
6859
51
  return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc);
6860
53
}
6861
6862
QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
6863
26
                                     SourceLocation AttrLoc) {
6864
26
  LangAS ASIdx;
6865
26
  if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc))
6866
2
    return QualType();
6867
24
  return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc);
6868
26
}
6869
6870
static void HandleBTFTypeTagAttribute(QualType &Type, const ParsedAttr &Attr,
6871
68
                                      TypeProcessingState &State) {
6872
68
  Sema &S = State.getSema();
6873
6874
  // Check the number of attribute arguments.
6875
68
  if (Attr.getNumArgs() != 1) {
6876
1
    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6877
1
        << Attr << 1;
6878
1
    Attr.setInvalid();
6879
1
    return;
6880
1
  }
6881
6882
  // Ensure the argument is a string.
6883
67
  auto *StrLiteral = dyn_cast<StringLiteral>(Attr.getArgAsExpr(0));
6884
67
  if (!StrLiteral) {
6885
0
    S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6886
0
        << Attr << AANT_ArgumentString;
6887
0
    Attr.setInvalid();
6888
0
    return;
6889
0
  }
6890
6891
67
  ASTContext &Ctx = S.Context;
6892
67
  StringRef BTFTypeTag = StrLiteral->getString();
6893
67
  Type = State.getBTFTagAttributedType(
6894
67
      ::new (Ctx) BTFTypeTagAttr(Ctx, Attr, BTFTypeTag), Type);
6895
67
}
6896
6897
/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
6898
/// specified type.  The attribute contains 1 argument, the id of the address
6899
/// space for the type.
6900
static void HandleAddressSpaceTypeAttribute(QualType &Type,
6901
                                            const ParsedAttr &Attr,
6902
43.2k
                                            TypeProcessingState &State) {
6903
43.2k
  Sema &S = State.getSema();
6904
6905
  // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
6906
  // qualified by an address-space qualifier."
6907
43.2k
  if (Type->isFunctionType()) {
6908
4
    S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
6909
4
    Attr.setInvalid();
6910
4
    return;
6911
4
  }
6912
6913
43.2k
  LangAS ASIdx;
6914
43.2k
  if (Attr.getKind() == ParsedAttr::AT_AddressSpace) {
6915
6916
    // Check the attribute arguments.
6917
1.01k
    if (Attr.getNumArgs() != 1) {
6918
0
      S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
6919
0
                                                                        << 1;
6920
0
      Attr.setInvalid();
6921
0
      return;
6922
0
    }
6923
6924
1.01k
    Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6925
1.01k
    LangAS ASIdx;
6926
1.01k
    if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) {
6927
5
      Attr.setInvalid();
6928
5
      return;
6929
5
    }
6930
6931
1.00k
    ASTContext &Ctx = S.Context;
6932
1.00k
    auto *ASAttr =
6933
1.00k
        ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx));
6934
6935
    // If the expression is not value dependent (not templated), then we can
6936
    // apply the address space qualifiers just to the equivalent type.
6937
    // Otherwise, we make an AttributedType with the modified and equivalent
6938
    // type the same, and wrap it in a DependentAddressSpaceType. When this
6939
    // dependent type is resolved, the qualifier is added to the equivalent type
6940
    // later.
6941
1.00k
    QualType T;
6942
1.00k
    if (!ASArgExpr->isValueDependent()) {
6943
955
      QualType EquivType =
6944
955
          S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc());
6945
955
      if (EquivType.isNull()) {
6946
2
        Attr.setInvalid();
6947
2
        return;
6948
2
      }
6949
953
      T = State.getAttributedType(ASAttr, Type, EquivType);
6950
953
    } else {
6951
53
      T = State.getAttributedType(ASAttr, Type, Type);
6952
53
      T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc());
6953
53
    }
6954
6955
1.00k
    if (!T.isNull())
6956
1.00k
      Type = T;
6957
2
    else
6958
2
      Attr.setInvalid();
6959
42.2k
  } else {
6960
    // The keyword-based type attributes imply which address space to use.
6961
42.2k
    ASIdx = S.getLangOpts().SYCLIsDevice ? 
Attr.asSYCLLangAS()38
6962
42.2k
                                         : 
Attr.asOpenCLLangAS()42.1k
;
6963
42.2k
    if (S.getLangOpts().HLSL)
6964
40
      ASIdx = Attr.asHLSLLangAS();
6965
6966
42.2k
    if (ASIdx == LangAS::Default)
6967
0
      llvm_unreachable("Invalid address space");
6968
6969
42.2k
    if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx,
6970
42.2k
                                            Attr.getLoc())) {
6971
46
      Attr.setInvalid();
6972
46
      return;
6973
46
    }
6974
6975
42.1k
    Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
6976
42.1k
  }
6977
43.2k
}
6978
6979
/// handleObjCOwnershipTypeAttr - Process an objc_ownership
6980
/// attribute on the specified type.
6981
///
6982
/// Returns 'true' if the attribute was handled.
6983
static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
6984
7.94k
                                        ParsedAttr &attr, QualType &type) {
6985
7.94k
  bool NonObjCPointer = false;
6986
6987
7.94k
  if (!type->isDependentType() && 
!type->isUndeducedType()7.89k
) {
6988
7.89k
    if (const PointerType *ptr = type->getAs<PointerType>()) {
6989
25
      QualType pointee = ptr->getPointeeType();
6990
25
      if (pointee->isObjCRetainableType() || pointee->isPointerType())
6991
0
        return false;
6992
      // It is important not to lose the source info that there was an attribute
6993
      // applied to non-objc pointer. We will create an attributed type but
6994
      // its type will be the same as the original type.
6995
25
      NonObjCPointer = true;
6996
7.86k
    } else if (!type->isObjCRetainableType()) {
6997
1.54k
      return false;
6998
1.54k
    }
6999
7000
    // Don't accept an ownership attribute in the declspec if it would
7001
    // just be the return type of a block pointer.
7002
6.34k
    if (state.isProcessingDeclSpec()) {
7003
3.84k
      Declarator &D = state.getDeclarator();
7004
3.84k
      if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
7005
3.84k
                                  /*onlyBlockPointers=*/true))
7006
6
        return false;
7007
3.84k
    }
7008
6.34k
  }
7009
7010
6.39k
  Sema &S = state.getSema();
7011
6.39k
  SourceLocation AttrLoc = attr.getLoc();
7012
6.39k
  if (AttrLoc.isMacroID())
7013
5.61k
    AttrLoc =
7014
5.61k
        S.getSourceManager().getImmediateExpansionRange(AttrLoc).getBegin();
7015
7016
6.39k
  if (!attr.isArgIdent(0)) {
7017
0
    S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr
7018
0
                                                       << AANT_ArgumentString;
7019
0
    attr.setInvalid();
7020
0
    return true;
7021
0
  }
7022
7023
6.39k
  IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
7024
6.39k
  Qualifiers::ObjCLifetime lifetime;
7025
6.39k
  if (II->isStr("none"))
7026
2.62k
    lifetime = Qualifiers::OCL_ExplicitNone;
7027
3.76k
  else if (II->isStr("strong"))
7028
1.78k
    lifetime = Qualifiers::OCL_Strong;
7029
1.98k
  else if (II->isStr("weak"))
7030
878
    lifetime = Qualifiers::OCL_Weak;
7031
1.10k
  else if (II->isStr("autoreleasing"))
7032
1.10k
    lifetime = Qualifiers::OCL_Autoreleasing;
7033
1
  else {
7034
1
    S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II;
7035
1
    attr.setInvalid();
7036
1
    return true;
7037
1
  }
7038
7039
  // Just ignore lifetime attributes other than __weak and __unsafe_unretained
7040
  // outside of ARC mode.
7041
6.39k
  if (!S.getLangOpts().ObjCAutoRefCount &&
7042
6.39k
      
lifetime != Qualifiers::OCL_Weak3.63k
&&
7043
6.39k
      
lifetime != Qualifiers::OCL_ExplicitNone3.46k
) {
7044
1.21k
    return true;
7045
1.21k
  }
7046
7047
5.17k
  SplitQualType underlyingType = type.split();
7048
7049
  // Check for redundant/conflicting ownership qualifiers.
7050
5.17k
  if (Qualifiers::ObjCLifetime previousLifetime
7051
5.17k
        = type.getQualifiers().getObjCLifetime()) {
7052
    // If it's written directly, that's an error.
7053
26
    if (S.Context.hasDirectOwnershipQualifier(type)) {
7054
9
      S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
7055
9
        << type;
7056
9
      return true;
7057
9
    }
7058
7059
    // Otherwise, if the qualifiers actually conflict, pull sugar off
7060
    // and remove the ObjCLifetime qualifiers.
7061
17
    if (previousLifetime != lifetime) {
7062
      // It's possible to have multiple local ObjCLifetime qualifiers. We
7063
      // can't stop after we reach a type that is directly qualified.
7064
13
      const Type *prevTy = nullptr;
7065
64
      while (!prevTy || 
prevTy != underlyingType.Ty51
) {
7066
51
        prevTy = underlyingType.Ty;
7067
51
        underlyingType = underlyingType.getSingleStepDesugaredType();
7068
51
      }
7069
13
      underlyingType.Quals.removeObjCLifetime();
7070
13
    }
7071
17
  }
7072
7073
5.16k
  underlyingType.Quals.addObjCLifetime(lifetime);
7074
7075
5.16k
  if (NonObjCPointer) {
7076
25
    StringRef name = attr.getAttrName()->getName();
7077
25
    switch (lifetime) {
7078
0
    case Qualifiers::OCL_None:
7079
0
    case Qualifiers::OCL_ExplicitNone:
7080
0
      break;
7081
24
    case Qualifiers::OCL_Strong: name = "__strong"; break;
7082
1
    case Qualifiers::OCL_Weak: name = "__weak"; break;
7083
0
    case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
7084
25
    }
7085
25
    S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
7086
25
      << TDS_ObjCObjOrBlock << type;
7087
25
  }
7088
7089
  // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
7090
  // because having both 'T' and '__unsafe_unretained T' exist in the type
7091
  // system causes unfortunate widespread consistency problems.  (For example,
7092
  // they're not considered compatible types, and we mangle them identicially
7093
  // as template arguments.)  These problems are all individually fixable,
7094
  // but it's easier to just not add the qualifier and instead sniff it out
7095
  // in specific places using isObjCInertUnsafeUnretainedType().
7096
  //
7097
  // Doing this does means we miss some trivial consistency checks that
7098
  // would've triggered in ARC, but that's better than trying to solve all
7099
  // the coexistence problems with __unsafe_unretained.
7100
5.16k
  if (!S.getLangOpts().ObjCAutoRefCount &&
7101
5.16k
      
lifetime == Qualifiers::OCL_ExplicitNone2.41k
) {
7102
2.24k
    type = state.getAttributedType(
7103
2.24k
        createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(S.Context, attr),
7104
2.24k
        type, type);
7105
2.24k
    return true;
7106
2.24k
  }
7107
7108
2.91k
  QualType origType = type;
7109
2.91k
  if (!NonObjCPointer)
7110
2.89k
    type = S.Context.getQualifiedType(underlyingType);
7111
7112
  // If we have a valid source location for the attribute, use an
7113
  // AttributedType instead.
7114
2.91k
  if (AttrLoc.isValid()) {
7115
2.15k
    type = state.getAttributedType(::new (S.Context)
7116
2.15k
                                       ObjCOwnershipAttr(S.Context, attr, II),
7117
2.15k
                                   origType, type);
7118
2.15k
  }
7119
7120
2.91k
  auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
7121
2.91k
                            unsigned diagnostic, QualType type) {
7122
39
    if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
7123
39
      S.DelayedDiagnostics.add(
7124
39
          sema::DelayedDiagnostic::makeForbiddenType(
7125
39
              S.getSourceManager().getExpansionLoc(loc),
7126
39
              diagnostic, type, /*ignored*/ 0));
7127
39
    } else {
7128
0
      S.Diag(loc, diagnostic);
7129
0
    }
7130
39
  };
7131
7132
  // Sometimes, __weak isn't allowed.
7133
2.91k
  if (lifetime == Qualifiers::OCL_Weak &&
7134
2.91k
      
!S.getLangOpts().ObjCWeak878
&&
!NonObjCPointer40
) {
7135
7136
    // Use a specialized diagnostic if the runtime just doesn't support them.
7137
39
    unsigned diagnostic =
7138
39
      (S.getLangOpts().ObjCWeakRuntime ? 
diag::err_arc_weak_disabled28
7139
39
                                       : 
diag::err_arc_weak_no_runtime11
);
7140
7141
    // In any case, delay the diagnostic until we know what we're parsing.
7142
39
    diagnoseOrDelay(S, AttrLoc, diagnostic, type);
7143
7144
39
    attr.setInvalid();
7145
39
    return true;
7146
39
  }
7147
7148
  // Forbid __weak for class objects marked as
7149
  // objc_arc_weak_reference_unavailable
7150
2.87k
  if (lifetime == Qualifiers::OCL_Weak) {
7151
839
    if (const ObjCObjectPointerType *ObjT =
7152
839
          type->getAs<ObjCObjectPointerType>()) {
7153
810
      if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
7154
226
        if (Class->isArcWeakrefUnavailable()) {
7155
24
          S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
7156
24
          S.Diag(ObjT->getInterfaceDecl()->getLocation(),
7157
24
                 diag::note_class_declared);
7158
24
        }
7159
226
      }
7160
810
    }
7161
839
  }
7162
7163
2.87k
  return true;
7164
2.91k
}
7165
7166
/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
7167
/// attribute on the specified type.  Returns true to indicate that
7168
/// the attribute was handled, false to indicate that the type does
7169
/// not permit the attribute.
7170
static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
7171
294
                                 QualType &type) {
7172
294
  Sema &S = state.getSema();
7173
7174
  // Delay if this isn't some kind of pointer.
7175
294
  if (!type->isPointerType() &&
7176
294
      
!type->isObjCObjectPointerType()209
&&
7177
294
      
!type->isBlockPointerType()77
)
7178
75
    return false;
7179
7180
219
  if (type.getObjCGCAttr() != Qualifiers::GCNone) {
7181
0
    S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
7182
0
    attr.setInvalid();
7183
0
    return true;
7184
0
  }
7185
7186
  // Check the attribute arguments.
7187
219
  if (!attr.isArgIdent(0)) {
7188
2
    S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
7189
2
        << attr << AANT_ArgumentString;
7190
2
    attr.setInvalid();
7191
2
    return true;
7192
2
  }
7193
217
  Qualifiers::GC GCAttr;
7194
217
  if (attr.getNumArgs() > 1) {
7195
1
    S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr
7196
1
                                                                      << 1;
7197
1
    attr.setInvalid();
7198
1
    return true;
7199
1
  }
7200
7201
216
  IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
7202
216
  if (II->isStr("weak"))
7203
101
    GCAttr = Qualifiers::Weak;
7204
115
  else if (II->isStr("strong"))
7205
114
    GCAttr = Qualifiers::Strong;
7206
1
  else {
7207
1
    S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
7208
1
        << attr << II;
7209
1
    attr.setInvalid();
7210
1
    return true;
7211
1
  }
7212
7213
215
  QualType origType = type;
7214
215
  type = S.Context.getObjCGCQualType(origType, GCAttr);
7215
7216
  // Make an attributed type to preserve the source information.
7217
215
  if (attr.getLoc().isValid())
7218
215
    type = state.getAttributedType(
7219
215
        ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type);
7220
7221
215
  return true;
7222
216
}
7223
7224
namespace {
7225
  /// A helper class to unwrap a type down to a function for the
7226
  /// purposes of applying attributes there.
7227
  ///
7228
  /// Use:
7229
  ///   FunctionTypeUnwrapper unwrapped(SemaRef, T);
7230
  ///   if (unwrapped.isFunctionType()) {
7231
  ///     const FunctionType *fn = unwrapped.get();
7232
  ///     // change fn somehow
7233
  ///     T = unwrapped.wrap(fn);
7234
  ///   }
7235
  struct FunctionTypeUnwrapper {
7236
    enum WrapKind {
7237
      Desugar,
7238
      Attributed,
7239
      Parens,
7240
      Array,
7241
      Pointer,
7242
      BlockPointer,
7243
      Reference,
7244
      MemberPointer,
7245
      MacroQualified,
7246
    };
7247
7248
    QualType Original;
7249
    const FunctionType *Fn;
7250
    SmallVector<unsigned char /*WrapKind*/, 8> Stack;
7251
7252
3.00M
    FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
7253
3.03M
      while (true) {
7254
3.03M
        const Type *Ty = T.getTypePtr();
7255
3.03M
        if (isa<FunctionType>(Ty)) {
7256
3.00M
          Fn = cast<FunctionType>(Ty);
7257
3.00M
          return;
7258
3.00M
        } else 
if (29.8k
isa<ParenType>(Ty)29.8k
) {
7259
27.9k
          T = cast<ParenType>(Ty)->getInnerType();
7260
27.9k
          Stack.push_back(Parens);
7261
27.9k
        } else 
if (1.89k
isa<ConstantArrayType>(Ty)1.89k
||
isa<VariableArrayType>(Ty)1.86k
||
7262
1.89k
                   
isa<IncompleteArrayType>(Ty)1.86k
) {
7263
27
          T = cast<ArrayType>(Ty)->getElementType();
7264
27
          Stack.push_back(Array);
7265
1.86k
        } else if (isa<PointerType>(Ty)) {
7266
91
          T = cast<PointerType>(Ty)->getPointeeType();
7267
91
          Stack.push_back(Pointer);
7268
1.77k
        } else if (isa<BlockPointerType>(Ty)) {
7269
0
          T = cast<BlockPointerType>(Ty)->getPointeeType();
7270
0
          Stack.push_back(BlockPointer);
7271
1.77k
        } else if (isa<MemberPointerType>(Ty)) {
7272
0
          T = cast<MemberPointerType>(Ty)->getPointeeType();
7273
0
          Stack.push_back(MemberPointer);
7274
1.77k
        } else if (isa<ReferenceType>(Ty)) {
7275
10
          T = cast<ReferenceType>(Ty)->getPointeeType();
7276
10
          Stack.push_back(Reference);
7277
1.76k
        } else if (isa<AttributedType>(Ty)) {
7278
889
          T = cast<AttributedType>(Ty)->getEquivalentType();
7279
889
          Stack.push_back(Attributed);
7280
889
        } else 
if (874
isa<MacroQualifiedType>(Ty)874
) {
7281
551
          T = cast<MacroQualifiedType>(Ty)->getUnderlyingType();
7282
551
          Stack.push_back(MacroQualified);
7283
551
        } else {
7284
323
          const Type *DTy = Ty->getUnqualifiedDesugaredType();
7285
323
          if (Ty == DTy) {
7286
166
            Fn = nullptr;
7287
166
            return;
7288
166
          }
7289
7290
157
          T = QualType(DTy, 0);
7291
157
          Stack.push_back(Desugar);
7292
157
        }
7293
3.03M
      }
7294
3.00M
    }
7295
7296
1.31M
    bool isFunctionType() const { return (Fn != nullptr); }
7297
4.28M
    const FunctionType *get() const { return Fn; }
7298
7299
1.27M
    QualType wrap(Sema &S, const FunctionType *New) {
7300
      // If T wasn't modified from the unwrapped type, do nothing.
7301
1.27M
      if (New == get()) 
return Original28
;
7302
7303
1.27M
      Fn = New;
7304
1.27M
      return wrap(S.Context, Original, 0);
7305
1.27M
    }
7306
7307
  private:
7308
1.27M
    QualType wrap(ASTContext &C, QualType Old, unsigned I) {
7309
1.27M
      if (I == Stack.size())
7310
1.27M
        return C.getQualifiedType(Fn, Old.getQualifiers());
7311
7312
      // Build up the inner type, applying the qualifiers from the old
7313
      // type to the new type.
7314
1.29k
      SplitQualType SplitOld = Old.split();
7315
7316
      // As a special case, tail-recurse if there are no qualifiers.
7317
1.29k
      if (SplitOld.Quals.empty())
7318
1.29k
        return wrap(C, SplitOld.Ty, I);
7319
0
      return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
7320
1.29k
    }
7321
7322
1.33k
    QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
7323
1.33k
      if (I == Stack.size()) 
return QualType(Fn, 0)38
;
7324
7325
1.29k
      switch (static_cast<WrapKind>(Stack[I++])) {
7326
43
      case Desugar:
7327
        // This is the point at which we potentially lose source
7328
        // information.
7329
43
        return wrap(C, Old->getUnqualifiedDesugaredType(), I);
7330
7331
530
      case Attributed:
7332
530
        return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
7333
7334
157
      case Parens: {
7335
157
        QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
7336
157
        return C.getParenType(New);
7337
0
      }
7338
7339
522
      case MacroQualified:
7340
522
        return wrap(C, cast<MacroQualifiedType>(Old)->getUnderlyingType(), I);
7341
7342
3
      case Array: {
7343
3
        if (const auto *CAT = dyn_cast<ConstantArrayType>(Old)) {
7344
3
          QualType New = wrap(C, CAT->getElementType(), I);
7345
3
          return C.getConstantArrayType(New, CAT->getSize(), CAT->getSizeExpr(),
7346
3
                                        CAT->getSizeModifier(),
7347
3
                                        CAT->getIndexTypeCVRQualifiers());
7348
3
        }
7349
7350
0
        if (const auto *VAT = dyn_cast<VariableArrayType>(Old)) {
7351
0
          QualType New = wrap(C, VAT->getElementType(), I);
7352
0
          return C.getVariableArrayType(
7353
0
              New, VAT->getSizeExpr(), VAT->getSizeModifier(),
7354
0
              VAT->getIndexTypeCVRQualifiers(), VAT->getBracketsRange());
7355
0
        }
7356
7357
0
        const auto *IAT = cast<IncompleteArrayType>(Old);
7358
0
        QualType New = wrap(C, IAT->getElementType(), I);
7359
0
        return C.getIncompleteArrayType(New, IAT->getSizeModifier(),
7360
0
                                        IAT->getIndexTypeCVRQualifiers());
7361
0
      }
7362
7363
42
      case Pointer: {
7364
42
        QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
7365
42
        return C.getPointerType(New);
7366
0
      }
7367
7368
0
      case BlockPointer: {
7369
0
        QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
7370
0
        return C.getBlockPointerType(New);
7371
0
      }
7372
7373
0
      case MemberPointer: {
7374
0
        const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
7375
0
        QualType New = wrap(C, OldMPT->getPointeeType(), I);
7376
0
        return C.getMemberPointerType(New, OldMPT->getClass());
7377
0
      }
7378
7379
0
      case Reference: {
7380
0
        const ReferenceType *OldRef = cast<ReferenceType>(Old);
7381
0
        QualType New = wrap(C, OldRef->getPointeeType(), I);
7382
0
        if (isa<LValueReferenceType>(OldRef))
7383
0
          return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
7384
0
        else
7385
0
          return C.getRValueReferenceType(New);
7386
0
      }
7387
1.29k
      }
7388
7389
0
      llvm_unreachable("unknown wrapping kind");
7390
0
    }
7391
  };
7392
} // end anonymous namespace
7393
7394
static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
7395
147
                                             ParsedAttr &PAttr, QualType &Type) {
7396
147
  Sema &S = State.getSema();
7397
7398
147
  Attr *A;
7399
147
  switch (PAttr.getKind()) {
7400
0
  default: llvm_unreachable("Unknown attribute kind");
7401
67
  case ParsedAttr::AT_Ptr32:
7402
67
    A = createSimpleAttr<Ptr32Attr>(S.Context, PAttr);
7403
67
    break;
7404
38
  case ParsedAttr::AT_Ptr64:
7405
38
    A = createSimpleAttr<Ptr64Attr>(S.Context, PAttr);
7406
38
    break;
7407
24
  case ParsedAttr::AT_SPtr:
7408
24
    A = createSimpleAttr<SPtrAttr>(S.Context, PAttr);
7409
24
    break;
7410
18
  case ParsedAttr::AT_UPtr:
7411
18
    A = createSimpleAttr<UPtrAttr>(S.Context, PAttr);
7412
18
    break;
7413
147
  }
7414
7415
147
  std::bitset<attr::LastAttr> Attrs;
7416
147
  QualType Desugared = Type;
7417
205
  for (;;) {
7418
205
    if (const TypedefType *TT = dyn_cast<TypedefType>(Desugared)) {
7419
9
      Desugared = TT->desugar();
7420
9
      continue;
7421
196
    } else if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(Desugared)) {
7422
9
      Desugared = ET->desugar();
7423
9
      continue;
7424
9
    }
7425
187
    const AttributedType *AT = dyn_cast<AttributedType>(Desugared);
7426
187
    if (!AT)
7427
147
      break;
7428
40
    Attrs[AT->getAttrKind()] = true;
7429
40
    Desugared = AT->getModifiedType();
7430
40
  }
7431
7432
  // You cannot specify duplicate type attributes, so if the attribute has
7433
  // already been applied, flag it.
7434
147
  attr::Kind NewAttrKind = A->getKind();
7435
147
  if (Attrs[NewAttrKind]) {
7436
5
    S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7437
5
    return true;
7438
5
  }
7439
142
  Attrs[NewAttrKind] = true;
7440
7441
  // You cannot have both __sptr and __uptr on the same type, nor can you
7442
  // have __ptr32 and __ptr64.
7443
142
  if (Attrs[attr::Ptr32] && 
Attrs[attr::Ptr64]89
) {
7444
5
    S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7445
5
        << "'__ptr32'"
7446
5
        << "'__ptr64'" << /*isRegularKeyword=*/0;
7447
5
    return true;
7448
137
  } else if (Attrs[attr::SPtr] && 
Attrs[attr::UPtr]27
) {
7449
1
    S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7450
1
        << "'__sptr'"
7451
1
        << "'__uptr'" << /*isRegularKeyword=*/0;
7452
1
    return true;
7453
1
  }
7454
7455
  // Check the raw (i.e., desugared) Canonical type to see if it
7456
  // is a pointer type.
7457
136
  if (!isa<PointerType>(Desugared)) {
7458
    // Pointer type qualifiers can only operate on pointer types, but not
7459
    // pointer-to-member types.
7460
13
    if (Type->isMemberPointerType())
7461
1
      S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr;
7462
12
    else
7463
12
      S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0;
7464
13
    return true;
7465
13
  }
7466
7467
  // Add address space to type based on its attributes.
7468
123
  LangAS ASIdx = LangAS::Default;
7469
123
  uint64_t PtrWidth =
7470
123
      S.Context.getTargetInfo().getPointerWidth(LangAS::Default);
7471
123
  if (PtrWidth == 32) {
7472
65
    if (Attrs[attr::Ptr64])
7473
16
      ASIdx = LangAS::ptr64;
7474
49
    else if (Attrs[attr::UPtr])
7475
9
      ASIdx = LangAS::ptr32_uptr;
7476
65
  } else 
if (58
PtrWidth == 6458
&&
Attrs[attr::Ptr32]58
) {
7477
38
    if (Attrs[attr::UPtr])
7478
8
      ASIdx = LangAS::ptr32_uptr;
7479
30
    else
7480
30
      ASIdx = LangAS::ptr32_sptr;
7481
38
  }
7482
7483
123
  QualType Pointee = Type->getPointeeType();
7484
123
  if (ASIdx != LangAS::Default)
7485
63
    Pointee = S.Context.getAddrSpaceQualType(
7486
63
        S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7487
123
  Type = State.getAttributedType(A, Type, S.Context.getPointerType(Pointee));
7488
123
  return false;
7489
136
}
7490
7491
static bool HandleWebAssemblyFuncrefAttr(TypeProcessingState &State,
7492
10
                                         QualType &QT, ParsedAttr &PAttr) {
7493
10
  assert(PAttr.getKind() == ParsedAttr::AT_WebAssemblyFuncref);
7494
7495
10
  Sema &S = State.getSema();
7496
10
  Attr *A = createSimpleAttr<WebAssemblyFuncrefAttr>(S.Context, PAttr);
7497
7498
10
  std::bitset<attr::LastAttr> Attrs;
7499
10
  attr::Kind NewAttrKind = A->getKind();
7500
10
  const auto *AT = dyn_cast<AttributedType>(QT);
7501
12
  while (AT) {
7502
2
    Attrs[AT->getAttrKind()] = true;
7503
2
    AT = dyn_cast<AttributedType>(AT->getModifiedType());
7504
2
  }
7505
7506
  // You cannot specify duplicate type attributes, so if the attribute has
7507
  // already been applied, flag it.
7508
10
  if (Attrs[NewAttrKind]) {
7509
2
    S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7510
2
    return true;
7511
2
  }
7512
7513
  // Add address space to type based on its attributes.
7514
8
  LangAS ASIdx = LangAS::wasm_funcref;
7515
8
  QualType Pointee = QT->getPointeeType();
7516
8
  Pointee = S.Context.getAddrSpaceQualType(
7517
8
      S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7518
8
  QT = State.getAttributedType(A, QT, S.Context.getPointerType(Pointee));
7519
8
  return false;
7520
10
}
7521
7522
/// Map a nullability attribute kind to a nullability kind.
7523
2.04M
static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind) {
7524
2.04M
  switch (kind) {
7525
1.04M
  case ParsedAttr::AT_TypeNonNull:
7526
1.04M
    return NullabilityKind::NonNull;
7527
7528
952k
  case ParsedAttr::AT_TypeNullable:
7529
952k
    return NullabilityKind::Nullable;
7530
7531
21
  case ParsedAttr::AT_TypeNullableResult:
7532
21
    return NullabilityKind::NullableResult;
7533
7534
43.7k
  case ParsedAttr::AT_TypeNullUnspecified:
7535
43.7k
    return NullabilityKind::Unspecified;
7536
7537
0
  default:
7538
0
    llvm_unreachable("not a nullability attribute kind");
7539
2.04M
  }
7540
2.04M
}
7541
7542
/// Applies a nullability type specifier to the given type, if possible.
7543
///
7544
/// \param state The type processing state.
7545
///
7546
/// \param type The type to which the nullability specifier will be
7547
/// added. On success, this type will be updated appropriately.
7548
///
7549
/// \param attr The attribute as written on the type.
7550
///
7551
/// \param allowOnArrayType Whether to accept nullability specifiers on an
7552
/// array type (e.g., because it will decay to a pointer).
7553
///
7554
/// \returns true if a problem has been diagnosed, false on success.
7555
static bool checkNullabilityTypeSpecifier(TypeProcessingState &state,
7556
                                          QualType &type,
7557
                                          ParsedAttr &attr,
7558
2.04M
                                          bool allowOnArrayType) {
7559
2.04M
  Sema &S = state.getSema();
7560
7561
2.04M
  NullabilityKind nullability = mapNullabilityAttrKind(attr.getKind());
7562
2.04M
  SourceLocation nullabilityLoc = attr.getLoc();
7563
2.04M
  bool isContextSensitive = attr.isContextSensitiveKeywordAttribute();
7564
7565
2.04M
  recordNullabilitySeen(S, nullabilityLoc);
7566
7567
  // Check for existing nullability attributes on the type.
7568
2.04M
  QualType desugared = type;
7569
2.04M
  while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
7570
    // Check whether there is already a null
7571
1.18k
    if (auto existingNullability = attributed->getImmediateNullability()) {
7572
      // Duplicated nullability.
7573
16
      if (nullability == *existingNullability) {
7574
6
        S.Diag(nullabilityLoc, diag::warn_nullability_duplicate)
7575
6
          << DiagNullabilityKind(nullability, isContextSensitive)
7576
6
          << FixItHint::CreateRemoval(nullabilityLoc);
7577
7578
6
        break;
7579
6
      }
7580
7581
      // Conflicting nullability.
7582
10
      S.Diag(nullabilityLoc, diag::err_nullability_conflicting)
7583
10
        << DiagNullabilityKind(nullability, isContextSensitive)
7584
10
        << DiagNullabilityKind(*existingNullability, false);
7585
10
      return true;
7586
16
    }
7587
7588
1.16k
    desugared = attributed->getModifiedType();
7589
1.16k
  }
7590
7591
  // If there is already a different nullability specifier, complain.
7592
  // This (unlike the code above) looks through typedefs that might
7593
  // have nullability specifiers on them, which means we cannot
7594
  // provide a useful Fix-It.
7595
2.04M
  if (auto existingNullability = desugared->getNullability()) {
7596
14
    if (nullability != *existingNullability) {
7597
3
      S.Diag(nullabilityLoc, diag::err_nullability_conflicting)
7598
3
        << DiagNullabilityKind(nullability, isContextSensitive)
7599
3
        << DiagNullabilityKind(*existingNullability, false);
7600
7601
      // Try to find the typedef with the existing nullability specifier.
7602
3
      if (auto typedefType = desugared->getAs<TypedefType>()) {
7603
3
        TypedefNameDecl *typedefDecl = typedefType->getDecl();
7604
3
        QualType underlyingType = typedefDecl->getUnderlyingType();
7605
3
        if (auto typedefNullability
7606
3
              = AttributedType::stripOuterNullability(underlyingType)) {
7607
1
          if (*typedefNullability == *existingNullability) {
7608
1
            S.Diag(typedefDecl->getLocation(), diag::note_nullability_here)
7609
1
              << DiagNullabilityKind(*existingNullability, false);
7610
1
          }
7611
1
        }
7612
3
      }
7613
7614
3
      return true;
7615
3
    }
7616
14
  }
7617
7618
  // If this definitely isn't a pointer type, reject the specifier.
7619
2.04M
  if (!desugared->canHaveNullability() &&
7620
2.04M
      
!(13.6k
allowOnArrayType13.6k
&&
desugared->isArrayType()13.5k
)) {
7621
39
    S.Diag(nullabilityLoc, diag::err_nullability_nonpointer)
7622
39
      << DiagNullabilityKind(nullability, isContextSensitive) << type;
7623
39
    return true;
7624
39
  }
7625
7626
  // For the context-sensitive keywords/Objective-C property
7627
  // attributes, require that the type be a single-level pointer.
7628
2.04M
  if (isContextSensitive) {
7629
    // Make sure that the pointee isn't itself a pointer type.
7630
918k
    const Type *pointeeType = nullptr;
7631
918k
    if (desugared->isArrayType())
7632
3
      pointeeType = desugared->getArrayElementTypeNoTypeQual();
7633
918k
    else if (desugared->isAnyPointerType())
7634
884k
      pointeeType = desugared->getPointeeType().getTypePtr();
7635
7636
918k
    if (pointeeType && 
(884k
pointeeType->isAnyPointerType()884k
||
7637
884k
                        
pointeeType->isObjCObjectPointerType()884k
||
7638
884k
                        
pointeeType->isMemberPointerType()884k
)) {
7639
4
      S.Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
7640
4
        << DiagNullabilityKind(nullability, true)
7641
4
        << type;
7642
4
      S.Diag(nullabilityLoc, diag::note_nullability_type_specifier)
7643
4
        << DiagNullabilityKind(nullability, false)
7644
4
        << type
7645
4
        << FixItHint::CreateReplacement(nullabilityLoc,
7646
4
                                        getNullabilitySpelling(nullability));
7647
4
      return true;
7648
4
    }
7649
918k
  }
7650
7651
  // Form the attributed type.
7652
2.04M
  type = state.getAttributedType(
7653
2.04M
      createNullabilityAttr(S.Context, attr, nullability), type, type);
7654
2.04M
  return false;
7655
2.04M
}
7656
7657
/// Check the application of the Objective-C '__kindof' qualifier to
7658
/// the given type.
7659
static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type,
7660
1.84k
                                ParsedAttr &attr) {
7661
1.84k
  Sema &S = state.getSema();
7662
7663
1.84k
  if (isa<ObjCTypeParamType>(type)) {
7664
    // Build the attributed type to record where __kindof occurred.
7665
5
    type = state.getAttributedType(
7666
5
        createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, type);
7667
5
    return false;
7668
5
  }
7669
7670
  // Find out if it's an Objective-C object or object pointer type;
7671
1.84k
  const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
7672
1.84k
  const ObjCObjectType *objType = ptrType ? 
ptrType->getObjectType()707
7673
1.84k
                                          : 
type->getAs<ObjCObjectType>()1.13k
;
7674
7675
  // If not, we can't apply __kindof.
7676
1.84k
  if (!objType) {
7677
    // FIXME: Handle dependent types that aren't yet object types.
7678
2
    S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject)
7679
2
      << type;
7680
2
    return true;
7681
2
  }
7682
7683
  // Rebuild the "equivalent" type, which pushes __kindof down into
7684
  // the object type.
7685
  // There is no need to apply kindof on an unqualified id type.
7686
1.84k
  QualType equivType = S.Context.getObjCObjectType(
7687
1.84k
      objType->getBaseType(), objType->getTypeArgsAsWritten(),
7688
1.84k
      objType->getProtocols(),
7689
1.84k
      /*isKindOf=*/objType->isObjCUnqualifiedId() ? 
false4
:
true1.83k
);
7690
7691
  // If we started with an object pointer type, rebuild it.
7692
1.84k
  if (ptrType) {
7693
707
    equivType = S.Context.getObjCObjectPointerType(equivType);
7694
707
    if (auto nullability = type->getNullability()) {
7695
      // We create a nullability attribute from the __kindof attribute.
7696
      // Make sure that will make sense.
7697
219
      assert(attr.getAttributeSpellingListIndex() == 0 &&
7698
219
             "multiple spellings for __kindof?");
7699
219
      Attr *A = createNullabilityAttr(S.Context, attr, *nullability);
7700
219
      A->setImplicit(true);
7701
219
      equivType = state.getAttributedType(A, equivType, equivType);
7702
219
    }
7703
707
  }
7704
7705
  // Build the attributed type to record where __kindof occurred.
7706
1.84k
  type = state.getAttributedType(
7707
1.84k
      createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, equivType);
7708
1.84k
  return false;
7709
1.84k
}
7710
7711
/// Distribute a nullability type attribute that cannot be applied to
7712
/// the type specifier to a pointer, block pointer, or member pointer
7713
/// declarator, complaining if necessary.
7714
///
7715
/// \returns true if the nullability annotation was distributed, false
7716
/// otherwise.
7717
static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
7718
67
                                          QualType type, ParsedAttr &attr) {
7719
67
  Declarator &declarator = state.getDeclarator();
7720
7721
  /// Attempt to move the attribute to the specified chunk.
7722
67
  auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
7723
    // If there is already a nullability attribute there, don't add
7724
    // one.
7725
49
    if (hasNullabilityAttr(chunk.getAttrs()))
7726
2
      return false;
7727
7728
    // Complain about the nullability qualifier being in the wrong
7729
    // place.
7730
47
    enum {
7731
47
      PK_Pointer,
7732
47
      PK_BlockPointer,
7733
47
      PK_MemberPointer,
7734
47
      PK_FunctionPointer,
7735
47
      PK_MemberFunctionPointer,
7736
47
    } pointerKind
7737
47
      = chunk.Kind == DeclaratorChunk::Pointer ? 
(39
inFunction39
?
PK_FunctionPointer4
7738
39
                                                             : 
PK_Pointer35
)
7739
47
        : 
chunk.Kind == DeclaratorChunk::BlockPointer8
?
PK_BlockPointer4
7740
8
        : 
inFunction4
?
PK_MemberFunctionPointer2
:
PK_MemberPointer2
;
7741
7742
47
    auto diag = state.getSema().Diag(attr.getLoc(),
7743
47
                                     diag::warn_nullability_declspec)
7744
47
      << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
7745
47
                             attr.isContextSensitiveKeywordAttribute())
7746
47
      << type
7747
47
      << static_cast<unsigned>(pointerKind);
7748
7749
    // FIXME: MemberPointer chunks don't carry the location of the *.
7750
47
    if (chunk.Kind != DeclaratorChunk::MemberPointer) {
7751
43
      diag << FixItHint::CreateRemoval(attr.getLoc())
7752
43
           << FixItHint::CreateInsertion(
7753
43
                  state.getSema().getPreprocessor().getLocForEndOfToken(
7754
43
                      chunk.Loc),
7755
43
                  " " + attr.getAttrName()->getName().str() + " ");
7756
43
    }
7757
7758
47
    moveAttrFromListToList(attr, state.getCurrentAttributes(),
7759
47
                           chunk.getAttrs());
7760
47
    return true;
7761
49
  };
7762
7763
  // Move it to the outermost pointer, member pointer, or block
7764
  // pointer declarator.
7765
69
  for (unsigned i = state.getCurrentChunkIndex(); i != 0; 
--i2
) {
7766
52
    DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
7767
52
    switch (chunk.Kind) {
7768
37
    case DeclaratorChunk::Pointer:
7769
37
    case DeclaratorChunk::BlockPointer:
7770
39
    case DeclaratorChunk::MemberPointer:
7771
39
      return moveToChunk(chunk, false);
7772
7773
0
    case DeclaratorChunk::Paren:
7774
2
    case DeclaratorChunk::Array:
7775
2
      continue;
7776
7777
11
    case DeclaratorChunk::Function:
7778
      // Try to move past the return type to a function/block/member
7779
      // function pointer.
7780
11
      if (DeclaratorChunk *dest = maybeMovePastReturnType(
7781
11
                                    declarator, i,
7782
11
                                    /*onlyBlockPointers=*/false)) {
7783
10
        return moveToChunk(*dest, true);
7784
10
      }
7785
7786
1
      return false;
7787
7788
    // Don't walk through these.
7789
0
    case DeclaratorChunk::Reference:
7790
0
    case DeclaratorChunk::Pipe:
7791
0
      return false;
7792
52
    }
7793
52
  }
7794
7795
17
  return false;
7796
67
}
7797
7798
3.20k
static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) {
7799
3.20k
  assert(!Attr.isInvalid());
7800
3.20k
  switch (Attr.getKind()) {
7801
0
  default:
7802
0
    llvm_unreachable("not a calling convention attribute");
7803
474
  case ParsedAttr::AT_CDecl:
7804
474
    return createSimpleAttr<CDeclAttr>(Ctx, Attr);
7805
233
  case ParsedAttr::AT_FastCall:
7806
233
    return createSimpleAttr<FastCallAttr>(Ctx, Attr);
7807
285
  case ParsedAttr::AT_StdCall:
7808
285
    return createSimpleAttr<StdCallAttr>(Ctx, Attr);
7809
79
  case ParsedAttr::AT_ThisCall:
7810
79
    return createSimpleAttr<ThisCallAttr>(Ctx, Attr);
7811
247
  case ParsedAttr::AT_RegCall:
7812
247
    return createSimpleAttr<RegCallAttr>(Ctx, Attr);
7813
23
  case ParsedAttr::AT_Pascal:
7814
23
    return createSimpleAttr<PascalAttr>(Ctx, Attr);
7815
1.22k
  case ParsedAttr::AT_SwiftCall:
7816
1.22k
    return createSimpleAttr<SwiftCallAttr>(Ctx, Attr);
7817
173
  case ParsedAttr::AT_SwiftAsyncCall:
7818
173
    return createSimpleAttr<SwiftAsyncCallAttr>(Ctx, Attr);
7819
214
  case ParsedAttr::AT_VectorCall:
7820
214
    return createSimpleAttr<VectorCallAttr>(Ctx, Attr);
7821
13
  case ParsedAttr::AT_AArch64VectorPcs:
7822
13
    return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, Attr);
7823
12
  case ParsedAttr::AT_AArch64SVEPcs:
7824
12
    return createSimpleAttr<AArch64SVEPcsAttr>(Ctx, Attr);
7825
0
  case ParsedAttr::AT_ArmStreaming:
7826
0
    return createSimpleAttr<ArmStreamingAttr>(Ctx, Attr);
7827
12
  case ParsedAttr::AT_AMDGPUKernelCall:
7828
12
    return createSimpleAttr<AMDGPUKernelCallAttr>(Ctx, Attr);
7829
33
  case ParsedAttr::AT_Pcs: {
7830
    // The attribute may have had a fixit applied where we treated an
7831
    // identifier as a string literal.  The contents of the string are valid,
7832
    // but the form may not be.
7833
33
    StringRef Str;
7834
33
    if (Attr.isArgExpr(0))
7835
33
      Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
7836
0
    else
7837
0
      Str = Attr.getArgAsIdent(0)->Ident->getName();
7838
33
    PcsAttr::PCSType Type;
7839
33
    if (!PcsAttr::ConvertStrToPCSType(Str, Type))
7840
0
      llvm_unreachable("already validated the attribute");
7841
33
    return ::new (Ctx) PcsAttr(Ctx, Attr, Type);
7842
0
  }
7843
8
  case ParsedAttr::AT_IntelOclBicc:
7844
8
    return createSimpleAttr<IntelOclBiccAttr>(Ctx, Attr);
7845
50
  case ParsedAttr::AT_MSABI:
7846
50
    return createSimpleAttr<MSABIAttr>(Ctx, Attr);
7847
37
  case ParsedAttr::AT_SysVABI:
7848
37
    return createSimpleAttr<SysVABIAttr>(Ctx, Attr);
7849
36
  case ParsedAttr::AT_PreserveMost:
7850
36
    return createSimpleAttr<PreserveMostAttr>(Ctx, Attr);
7851
27
  case ParsedAttr::AT_PreserveAll:
7852
27
    return createSimpleAttr<PreserveAllAttr>(Ctx, Attr);
7853
27
  case ParsedAttr::AT_M68kRTD:
7854
27
    return createSimpleAttr<M68kRTDAttr>(Ctx, Attr);
7855
3.20k
  }
7856
0
  llvm_unreachable("unexpected attribute kind!");
7857
0
}
7858
7859
static bool checkMutualExclusion(TypeProcessingState &state,
7860
                                 const FunctionProtoType::ExtProtoInfo &EPI,
7861
                                 ParsedAttr &Attr,
7862
1.23M
                                 AttributeCommonInfo::Kind OtherKind) {
7863
1.23M
  auto OtherAttr = std::find_if(
7864
1.23M
      state.getCurrentAttributes().begin(), state.getCurrentAttributes().end(),
7865
1.23M
      [OtherKind](const ParsedAttr &A) { return A.getKind() == OtherKind; });
7866
1.23M
  if (OtherAttr == state.getCurrentAttributes().end() || 
OtherAttr->isInvalid()16
)
7867
1.23M
    return false;
7868
7869
8
  Sema &S = state.getSema();
7870
8
  S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
7871
8
      << *OtherAttr << Attr
7872
8
      << (OtherAttr->isRegularKeywordAttribute() ||
7873
8
          
Attr.isRegularKeywordAttribute()0
);
7874
8
  S.Diag(OtherAttr->getLoc(), diag::note_conflicting_attribute);
7875
8
  Attr.setInvalid();
7876
8
  return true;
7877
1.23M
}
7878
7879
/// Process an individual function attribute.  Returns true to
7880
/// indicate that the attribute was handled, false if it wasn't.
7881
static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
7882
                                   QualType &type,
7883
1.31M
                                   Sema::CUDAFunctionTarget CFT) {
7884
1.31M
  Sema &S = state.getSema();
7885
7886
1.31M
  FunctionTypeUnwrapper unwrapped(S, type);
7887
7888
1.31M
  if (attr.getKind() == ParsedAttr::AT_NoReturn) {
7889
6.94k
    if (S.CheckAttrNoArgs(attr))
7890
3
      return true;
7891
7892
    // Delay if this is not a function type.
7893
6.94k
    if (!unwrapped.isFunctionType())
7894
2
      return false;
7895
7896
    // Otherwise we can process right away.
7897
6.94k
    FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
7898
6.94k
    type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7899
6.94k
    return true;
7900
6.94k
  }
7901
7902
1.30M
  if (attr.getKind() == ParsedAttr::AT_CmseNSCall) {
7903
    // Delay if this is not a function type.
7904
85
    if (!unwrapped.isFunctionType())
7905
1
      return false;
7906
7907
    // Ignore if we don't have CMSE enabled.
7908
84
    if (!S.getLangOpts().Cmse) {
7909
7
      S.Diag(attr.getLoc(), diag::warn_attribute_ignored) << attr;
7910
7
      attr.setInvalid();
7911
7
      return true;
7912
7
    }
7913
7914
    // Otherwise we can process right away.
7915
77
    FunctionType::ExtInfo EI =
7916
77
        unwrapped.get()->getExtInfo().withCmseNSCall(true);
7917
77
    type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7918
77
    return true;
7919
84
  }
7920
7921
  // ns_returns_retained is not always a type attribute, but if we got
7922
  // here, we're treating it as one right now.
7923
1.30M
  if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) {
7924
13.5k
    if (attr.getNumArgs()) 
return true0
;
7925
7926
    // Delay if this is not a function type.
7927
13.5k
    if (!unwrapped.isFunctionType())
7928
5
      return false;
7929
7930
    // Check whether the return type is reasonable.
7931
13.5k
    if (S.checkNSReturnsRetainedReturnType(attr.getLoc(),
7932
13.5k
                                           unwrapped.get()->getReturnType()))
7933
4
      return true;
7934
7935
    // Only actually change the underlying type in ARC builds.
7936
13.5k
    QualType origType = type;
7937
13.5k
    if (state.getSema().getLangOpts().ObjCAutoRefCount) {
7938
404
      FunctionType::ExtInfo EI
7939
404
        = unwrapped.get()->getExtInfo().withProducesResult(true);
7940
404
      type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7941
404
    }
7942
13.5k
    type = state.getAttributedType(
7943
13.5k
        createSimpleAttr<NSReturnsRetainedAttr>(S.Context, attr),
7944
13.5k
        origType, type);
7945
13.5k
    return true;
7946
13.5k
  }
7947
7948
1.29M
  if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) {
7949
35
    if (S.CheckAttrTarget(attr) || 
S.CheckAttrNoArgs(attr)26
)
7950
10
      return true;
7951
7952
    // Delay if this is not a function type.
7953
25
    if (!unwrapped.isFunctionType())
7954
3
      return false;
7955
7956
22
    FunctionType::ExtInfo EI =
7957
22
        unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true);
7958
22
    type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7959
22
    return true;
7960
25
  }
7961
7962
1.28M
  if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) {
7963
14
    if (!S.getLangOpts().CFProtectionBranch) {
7964
1
      S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored);
7965
1
      attr.setInvalid();
7966
1
      return true;
7967
1
    }
7968
7969
13
    if (S.CheckAttrTarget(attr) || 
S.CheckAttrNoArgs(attr)11
)
7970
4
      return true;
7971
7972
    // If this is not a function type, warning will be asserted by subject
7973
    // check.
7974
9
    if (!unwrapped.isFunctionType())
7975
3
      return true;
7976
7977
6
    FunctionType::ExtInfo EI =
7978
6
      unwrapped.get()->getExtInfo().withNoCfCheck(true);
7979
6
    type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7980
6
    return true;
7981
9
  }
7982
7983
1.28M
  if (attr.getKind() == ParsedAttr::AT_Regparm) {
7984
79
    unsigned value;
7985
79
    if (S.CheckRegparmAttr(attr, value))
7986
6
      return true;
7987
7988
    // Delay if this is not a function type.
7989
73
    if (!unwrapped.isFunctionType())
7990
1
      return false;
7991
7992
    // Diagnose regparm with fastcall.
7993
72
    const FunctionType *fn = unwrapped.get();
7994
72
    CallingConv CC = fn->getCallConv();
7995
72
    if (CC == CC_X86FastCall) {
7996
2
      S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
7997
2
          << FunctionType::getNameForCallConv(CC) << "regparm"
7998
2
          << attr.isRegularKeywordAttribute();
7999
2
      attr.setInvalid();
8000
2
      return true;
8001
2
    }
8002
8003
70
    FunctionType::ExtInfo EI =
8004
70
      unwrapped.get()->getExtInfo().withRegParm(value);
8005
70
    type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8006
70
    return true;
8007
72
  }
8008
8009
1.28M
  if (attr.getKind() == ParsedAttr::AT_ArmStreaming ||
8010
1.28M
      
attr.getKind() == ParsedAttr::AT_ArmStreamingCompatible1.28M
||
8011
1.28M
      
attr.getKind() == ParsedAttr::AT_ArmSharedZA50.4k
||
8012
1.28M
      
attr.getKind() == ParsedAttr::AT_ArmPreservesZA50.1k
){
8013
1.23M
    if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
8014
0
      return true;
8015
8016
1.23M
    if (!unwrapped.isFunctionType())
8017
97
      return false;
8018
8019
1.23M
    const auto *FnTy = unwrapped.get()->getAs<FunctionProtoType>();
8020
1.23M
    if (!FnTy) {
8021
      // SME ACLE attributes are not supported on K&R-style unprototyped C
8022
      // functions.
8023
1
      S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type) <<
8024
1
        attr << attr.isRegularKeywordAttribute() << ExpectedFunctionWithProtoType;
8025
1
      attr.setInvalid();
8026
1
      return false;
8027
1
    }
8028
8029
1.23M
    FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
8030
1.23M
    switch (attr.getKind()) {
8031
909
    case ParsedAttr::AT_ArmStreaming:
8032
909
      if (checkMutualExclusion(state, EPI, attr,
8033
909
                               ParsedAttr::AT_ArmStreamingCompatible))
8034
6
        return true;
8035
903
      EPI.setArmSMEAttribute(FunctionType::SME_PStateSMEnabledMask);
8036
903
      break;
8037
1.23M
    case ParsedAttr::AT_ArmStreamingCompatible:
8038
1.23M
      if (checkMutualExclusion(state, EPI, attr, ParsedAttr::AT_ArmStreaming))
8039
2
        return true;
8040
1.23M
      EPI.setArmSMEAttribute(FunctionType::SME_PStateSMCompatibleMask);
8041
1.23M
      break;
8042
341
    case ParsedAttr::AT_ArmSharedZA:
8043
341
      EPI.setArmSMEAttribute(FunctionType::SME_PStateZASharedMask);
8044
341
      break;
8045
40
    case ParsedAttr::AT_ArmPreservesZA:
8046
40
      EPI.setArmSMEAttribute(FunctionType::SME_PStateZAPreservedMask);
8047
40
      break;
8048
0
    default:
8049
0
      llvm_unreachable("Unsupported attribute");
8050
1.23M
    }
8051
8052
1.23M
    QualType newtype = S.Context.getFunctionType(FnTy->getReturnType(),
8053
1.23M
                                                 FnTy->getParamTypes(), EPI);
8054
1.23M
    type = unwrapped.wrap(S, newtype->getAs<FunctionType>());
8055
1.23M
    return true;
8056
1.23M
  }
8057
8058
50.0k
  if (attr.getKind() == ParsedAttr::AT_NoThrow) {
8059
    // Delay if this is not a function type.
8060
46.8k
    if (!unwrapped.isFunctionType())
8061
0
      return false;
8062
8063
46.8k
    if (S.CheckAttrNoArgs(attr)) {
8064
0
      attr.setInvalid();
8065
0
      return true;
8066
0
    }
8067
8068
    // Otherwise we can process right away.
8069
46.8k
    auto *Proto = unwrapped.get()->castAs<FunctionProtoType>();
8070
8071
    // MSVC ignores nothrow if it is in conflict with an explicit exception
8072
    // specification.
8073
46.8k
    if (Proto->hasExceptionSpec()) {
8074
17.9k
      switch (Proto->getExceptionSpecType()) {
8075
0
      case EST_None:
8076
0
        llvm_unreachable("This doesn't have an exception spec!");
8077
8078
2
      case EST_DynamicNone:
8079
6
      case EST_BasicNoexcept:
8080
14
      case EST_NoexceptTrue:
8081
17.8k
      case EST_NoThrow:
8082
        // Exception spec doesn't conflict with nothrow, so don't warn.
8083
17.8k
        [[fallthrough]];
8084
17.8k
      case EST_Unparsed:
8085
17.8k
      case EST_Uninstantiated:
8086
17.9k
      case EST_DependentNoexcept:
8087
17.9k
      case EST_Unevaluated:
8088
        // We don't have enough information to properly determine if there is a
8089
        // conflict, so suppress the warning.
8090
17.9k
        break;
8091
1
      case EST_Dynamic:
8092
1
      case EST_MSAny:
8093
7
      case EST_NoexceptFalse:
8094
7
        S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored);
8095
7
        break;
8096
17.9k
      }
8097
17.9k
      return true;
8098
17.9k
    }
8099
8100
28.9k
    type = unwrapped.wrap(
8101
28.9k
        S, S.Context
8102
28.9k
               .getFunctionTypeWithExceptionSpec(
8103
28.9k
                   QualType{Proto, 0},
8104
28.9k
                   FunctionProtoType::ExceptionSpecInfo{EST_NoThrow})
8105
28.9k
               ->getAs<FunctionType>());
8106
28.9k
    return true;
8107
46.8k
  }
8108
8109
  // Delay if the type didn't work out to a function.
8110
3.25k
  if (!unwrapped.isFunctionType()) 
return false51
;
8111
8112
  // Otherwise, a calling convention.
8113
3.20k
  CallingConv CC;
8114
3.20k
  if (S.CheckCallingConvAttr(attr, CC, /*FunctionDecl=*/nullptr, CFT))
8115
0
    return true;
8116
8117
3.20k
  const FunctionType *fn = unwrapped.get();
8118
3.20k
  CallingConv CCOld = fn->getCallConv();
8119
3.20k
  Attr *CCAttr = getCCTypeAttr(S.Context, attr);
8120
8121
3.20k
  if (CCOld != CC) {
8122
    // Error out on when there's already an attribute on the type
8123
    // and the CCs don't match.
8124
187
    if (S.getCallingConvAttributedType(type)) {
8125
26
      S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8126
26
          << FunctionType::getNameForCallConv(CC)
8127
26
          << FunctionType::getNameForCallConv(CCOld)
8128
26
          << attr.isRegularKeywordAttribute();
8129
26
      attr.setInvalid();
8130
26
      return true;
8131
26
    }
8132
187
  }
8133
8134
  // Diagnose use of variadic functions with calling conventions that
8135
  // don't support them (e.g. because they're callee-cleanup).
8136
  // We delay warning about this on unprototyped function declarations
8137
  // until after redeclaration checking, just in case we pick up a
8138
  // prototype that way.  And apparently we also "delay" warning about
8139
  // unprototyped function types in general, despite not necessarily having
8140
  // much ability to diagnose it later.
8141
3.18k
  if (!supportsVariadicCall(CC)) {
8142
2.33k
    const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
8143
2.33k
    if (FnP && 
FnP->isVariadic()2.29k
) {
8144
      // stdcall and fastcall are ignored with a warning for GCC and MS
8145
      // compatibility.
8146
27
      if (CC == CC_X86StdCall || 
CC == CC_X86FastCall18
)
8147
14
        return S.Diag(attr.getLoc(), diag::warn_cconv_unsupported)
8148
14
               << FunctionType::getNameForCallConv(CC)
8149
14
               << (int)Sema::CallingConventionIgnoredReason::VariadicFunction;
8150
8151
13
      attr.setInvalid();
8152
13
      return S.Diag(attr.getLoc(), diag::err_cconv_varargs)
8153
13
             << FunctionType::getNameForCallConv(CC);
8154
27
    }
8155
2.33k
  }
8156
8157
  // Also diagnose fastcall with regparm.
8158
3.15k
  if (CC == CC_X86FastCall && 
fn->getHasRegParm()160
) {
8159
0
    S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8160
0
        << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall)
8161
0
        << attr.isRegularKeywordAttribute();
8162
0
    attr.setInvalid();
8163
0
    return true;
8164
0
  }
8165
8166
  // Modify the CC from the wrapped function type, wrap it all back, and then
8167
  // wrap the whole thing in an AttributedType as written.  The modified type
8168
  // might have a different CC if we ignored the attribute.
8169
3.15k
  QualType Equivalent;
8170
3.15k
  if (CCOld == CC) {
8171
3.01k
    Equivalent = type;
8172
3.01k
  } else {
8173
134
    auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
8174
134
    Equivalent =
8175
134
      unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8176
134
  }
8177
3.15k
  type = state.getAttributedType(CCAttr, type, Equivalent);
8178
3.15k
  return true;
8179
3.15k
}
8180
8181
12.8k
bool Sema::hasExplicitCallingConv(QualType T) {
8182
12.8k
  const AttributedType *AT;
8183
8184
  // Stop if we'd be stripping off a typedef sugar node to reach the
8185
  // AttributedType.
8186
12.8k
  while ((AT = T->getAs<AttributedType>()) &&
8187
12.8k
         
AT->getAs<TypedefType>() == T->getAs<TypedefType>()50
) {
8188
42
    if (AT->isCallingConv())
8189
42
      return true;
8190
0
    T = AT->getModifiedType();
8191
0
  }
8192
12.8k
  return false;
8193
12.8k
}
8194
8195
void Sema::adjustMemberFunctionCC(QualType &T, bool HasThisPointer,
8196
1.69M
                                  bool IsCtorOrDtor, SourceLocation Loc) {
8197
1.69M
  FunctionTypeUnwrapper Unwrapped(*this, T);
8198
1.69M
  const FunctionType *FT = Unwrapped.get();
8199
1.69M
  bool IsVariadic = (isa<FunctionProtoType>(FT) &&
8200
1.69M
                     cast<FunctionProtoType>(FT)->isVariadic());
8201
1.69M
  CallingConv CurCC = FT->getCallConv();
8202
1.69M
  CallingConv ToCC =
8203
1.69M
      Context.getDefaultCallingConvention(IsVariadic, HasThisPointer);
8204
8205
1.69M
  if (CurCC == ToCC)
8206
1.69M
    return;
8207
8208
  // MS compiler ignores explicit calling convention attributes on structors. We
8209
  // should do the same.
8210
218
  if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 
IsCtorOrDtor124
) {
8211
    // Issue a warning on ignored calling convention -- except of __stdcall.
8212
    // Again, this is what MS compiler does.
8213
4
    if (CurCC != CC_X86StdCall)
8214
2
      Diag(Loc, diag::warn_cconv_unsupported)
8215
2
          << FunctionType::getNameForCallConv(CurCC)
8216
2
          << (int)Sema::CallingConventionIgnoredReason::ConstructorDestructor;
8217
  // Default adjustment.
8218
214
  } else {
8219
    // Only adjust types with the default convention.  For example, on Windows
8220
    // we should adjust a __cdecl type to __thiscall for instance methods, and a
8221
    // __thiscall type to __cdecl for static methods.
8222
214
    CallingConv DefaultCC =
8223
214
        Context.getDefaultCallingConvention(IsVariadic, !HasThisPointer);
8224
8225
214
    if (CurCC != DefaultCC)
8226
146
      return;
8227
8228
68
    if (hasExplicitCallingConv(T))
8229
35
      return;
8230
68
  }
8231
8232
37
  FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
8233
37
  QualType Wrapped = Unwrapped.wrap(*this, FT);
8234
37
  T = Context.getAdjustedType(T, Wrapped);
8235
37
}
8236
8237
/// HandleVectorSizeAttribute - this attribute is only applicable to integral
8238
/// and float scalars, although arrays, pointers, and function return values are
8239
/// allowed in conjunction with this construct. Aggregates with this attribute
8240
/// are invalid, even if they are of the same size as a corresponding scalar.
8241
/// The raw attribute should contain precisely 1 argument, the vector size for
8242
/// the variable, measured in bytes. If curType and rawAttr are well formed,
8243
/// this routine will return a new vector type.
8244
static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr,
8245
36.0k
                                 Sema &S) {
8246
  // Check the attribute arguments.
8247
36.0k
  if (Attr.getNumArgs() != 1) {
8248
0
    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
8249
0
                                                                      << 1;
8250
0
    Attr.setInvalid();
8251
0
    return;
8252
0
  }
8253
8254
36.0k
  Expr *SizeExpr = Attr.getArgAsExpr(0);
8255
36.0k
  QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc());
8256
36.0k
  if (!T.isNull())
8257
35.9k
    CurType = T;
8258
60
  else
8259
60
    Attr.setInvalid();
8260
36.0k
}
8261
8262
/// Process the OpenCL-like ext_vector_type attribute when it occurs on
8263
/// a type.
8264
static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8265
5.47k
                                    Sema &S) {
8266
  // check the attribute arguments.
8267
5.47k
  if (Attr.getNumArgs() != 1) {
8268
0
    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
8269
0
                                                                      << 1;
8270
0
    return;
8271
0
  }
8272
8273
5.47k
  Expr *SizeExpr = Attr.getArgAsExpr(0);
8274
5.47k
  QualType T = S.BuildExtVectorType(CurType, SizeExpr, Attr.getLoc());
8275
5.47k
  if (!T.isNull())
8276
5.44k
    CurType = T;
8277
5.47k
}
8278
8279
7.65k
static bool isPermittedNeonBaseType(QualType &Ty, VectorKind VecKind, Sema &S) {
8280
7.65k
  const BuiltinType *BTy = Ty->getAs<BuiltinType>();
8281
7.65k
  if (!BTy)
8282
7
    return false;
8283
8284
7.64k
  llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
8285
8286
  // Signed poly is mathematically wrong, but has been baked into some ABIs by
8287
  // now.
8288
7.64k
  bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
8289
7.64k
                        
Triple.getArch() == llvm::Triple::aarch64_323.73k
||
8290
7.64k
                        
Triple.getArch() == llvm::Triple::aarch64_be3.71k
;
8291
7.64k
  if (VecKind == VectorKind::NeonPoly) {
8292
1.24k
    if (IsPolyUnsigned) {
8293
      // AArch64 polynomial vectors are unsigned.
8294
871
      return BTy->getKind() == BuiltinType::UChar ||
8295
871
             
BTy->getKind() == BuiltinType::UShort581
||
8296
871
             
BTy->getKind() == BuiltinType::ULong293
||
8297
871
             
BTy->getKind() == BuiltinType::ULongLong47
;
8298
871
    } else {
8299
      // AArch32 polynomial vectors are signed.
8300
373
      return BTy->getKind() == BuiltinType::SChar ||
8301
373
             
BTy->getKind() == BuiltinType::Short246
||
8302
373
             
BTy->getKind() == BuiltinType::LongLong123
;
8303
373
    }
8304
1.24k
  }
8305
8306
  // Non-polynomial vector types: the usual suspects are allowed, as well as
8307
  // float64_t on AArch64.
8308
6.40k
  if ((Triple.isArch64Bit() || 
Triple.getArch() == llvm::Triple::aarch64_322.96k
) &&
8309
6.40k
      
BTy->getKind() == BuiltinType::Double3.45k
)
8310
287
    return true;
8311
8312
6.11k
  return BTy->getKind() == BuiltinType::SChar ||
8313
6.11k
         
BTy->getKind() == BuiltinType::UChar5.55k
||
8314
6.11k
         
BTy->getKind() == BuiltinType::Short4.99k
||
8315
6.11k
         
BTy->getKind() == BuiltinType::UShort4.42k
||
8316
6.11k
         
BTy->getKind() == BuiltinType::Int3.86k
||
8317
6.11k
         
BTy->getKind() == BuiltinType::UInt3.25k
||
8318
6.11k
         
BTy->getKind() == BuiltinType::Long2.69k
||
8319
6.11k
         
BTy->getKind() == BuiltinType::ULong2.44k
||
8320
6.11k
         
BTy->getKind() == BuiltinType::LongLong2.19k
||
8321
6.11k
         
BTy->getKind() == BuiltinType::ULongLong1.86k
||
8322
6.11k
         
BTy->getKind() == BuiltinType::Float1.53k
||
8323
6.11k
         
BTy->getKind() == BuiltinType::Half962
||
8324
6.11k
         
BTy->getKind() == BuiltinType::BFloat16406
;
8325
6.40k
}
8326
8327
static bool verifyValidIntegerConstantExpr(Sema &S, const ParsedAttr &Attr,
8328
8.99k
                                           llvm::APSInt &Result) {
8329
8.99k
  const auto *AttrExpr = Attr.getArgAsExpr(0);
8330
8.99k
  if (!AttrExpr->isTypeDependent()) {
8331
8.99k
    if (std::optional<llvm::APSInt> Res =
8332
8.99k
            AttrExpr->getIntegerConstantExpr(S.Context)) {
8333
8.97k
      Result = *Res;
8334
8.97k
      return true;
8335
8.97k
    }
8336
8.99k
  }
8337
27
  S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
8338
27
      << Attr << AANT_ArgumentIntegerConstant << AttrExpr->getSourceRange();
8339
27
  Attr.setInvalid();
8340
27
  return false;
8341
8.99k
}
8342
8343
/// HandleNeonVectorTypeAttr - The "neon_vector_type" and
8344
/// "neon_polyvector_type" attributes are used to create vector types that
8345
/// are mangled according to ARM's ABI.  Otherwise, these types are identical
8346
/// to those created with the "vector_size" attribute.  Unlike "vector_size"
8347
/// the argument to these Neon attributes is the number of vector elements,
8348
/// not the vector size in bytes.  The vector width and element type must
8349
/// match one of the standard Neon vector types.
8350
static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8351
7.67k
                                     Sema &S, VectorKind VecKind) {
8352
7.67k
  bool IsTargetCUDAAndHostARM = false;
8353
7.67k
  if (S.getLangOpts().CUDAIsDevice) {
8354
2
    const TargetInfo *AuxTI = S.getASTContext().getAuxTargetInfo();
8355
2
    IsTargetCUDAAndHostARM =
8356
2
        AuxTI && (AuxTI->getTriple().isAArch64() || 
AuxTI->getTriple().isARM()0
);
8357
2
  }
8358
8359
  // Target must have NEON (or MVE, whose vectors are similar enough
8360
  // not to need a separate attribute)
8361
7.67k
  if (!(S.Context.getTargetInfo().hasFeature("neon") ||
8362
7.67k
        
S.Context.getTargetInfo().hasFeature("mve")1.59k
||
8363
7.67k
        
IsTargetCUDAAndHostARM8
)) {
8364
6
    S.Diag(Attr.getLoc(), diag::err_attribute_unsupported)
8365
6
        << Attr << "'neon' or 'mve'";
8366
6
    Attr.setInvalid();
8367
6
    return;
8368
6
  }
8369
  // Check the attribute arguments.
8370
7.66k
  if (Attr.getNumArgs() != 1) {
8371
7
    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8372
7
        << Attr << 1;
8373
7
    Attr.setInvalid();
8374
7
    return;
8375
7
  }
8376
  // The number of elements must be an ICE.
8377
7.66k
  llvm::APSInt numEltsInt(32);
8378
7.66k
  if (!verifyValidIntegerConstantExpr(S, Attr, numEltsInt))
8379
7
    return;
8380
8381
  // Only certain element types are supported for Neon vectors.
8382
7.65k
  if (!isPermittedNeonBaseType(CurType, VecKind, S) &&
8383
7.65k
      
!IsTargetCUDAAndHostARM22
) {
8384
21
    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
8385
21
    Attr.setInvalid();
8386
21
    return;
8387
21
  }
8388
8389
  // The total size of the vector must be 64 or 128 bits.
8390
7.63k
  unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
8391
7.63k
  unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
8392
7.63k
  unsigned vecSize = typeSize * numElts;
8393
7.63k
  if (vecSize != 64 && 
vecSize != 1284.63k
) {
8394
14
    S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
8395
14
    Attr.setInvalid();
8396
14
    return;
8397
14
  }
8398
8399
7.62k
  CurType = S.Context.getVectorType(CurType, numElts, VecKind);
8400
7.62k
}
8401
8402
/// HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is
8403
/// used to create fixed-length versions of sizeless SVE types defined by
8404
/// the ACLE, such as svint32_t and svbool_t.
8405
static void HandleArmSveVectorBitsTypeAttr(QualType &CurType, ParsedAttr &Attr,
8406
511
                                           Sema &S) {
8407
  // Target must have SVE.
8408
511
  if (!S.Context.getTargetInfo().hasFeature("sve")) {
8409
1
    S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr << "'sve'";
8410
1
    Attr.setInvalid();
8411
1
    return;
8412
1
  }
8413
8414
  // Attribute is unsupported if '-msve-vector-bits=<bits>' isn't specified, or
8415
  // if <bits>+ syntax is used.
8416
510
  if (!S.getLangOpts().VScaleMin ||
8417
510
      
S.getLangOpts().VScaleMin != S.getLangOpts().VScaleMax506
) {
8418
6
    S.Diag(Attr.getLoc(), diag::err_attribute_arm_feature_sve_bits_unsupported)
8419
6
        << Attr;
8420
6
    Attr.setInvalid();
8421
6
    return;
8422
6
  }
8423
8424
  // Check the attribute arguments.
8425
504
  if (Attr.getNumArgs() != 1) {
8426
10
    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8427
10
        << Attr << 1;
8428
10
    Attr.setInvalid();
8429
10
    return;
8430
10
  }
8431
8432
  // The vector size must be an integer constant expression.
8433
494
  llvm::APSInt SveVectorSizeInBits(32);
8434
494
  if (!verifyValidIntegerConstantExpr(S, Attr, SveVectorSizeInBits))
8435
10
    return;
8436
8437
484
  unsigned VecSize = static_cast<unsigned>(SveVectorSizeInBits.getZExtValue());
8438
8439
  // The attribute vector size must match -msve-vector-bits.
8440
484
  if (VecSize != S.getLangOpts().VScaleMin * 128) {
8441
2
    S.Diag(Attr.getLoc(), diag::err_attribute_bad_sve_vector_size)
8442
2
        << VecSize << S.getLangOpts().VScaleMin * 128;
8443
2
    Attr.setInvalid();
8444
2
    return;
8445
2
  }
8446
8447
  // Attribute can only be attached to a single SVE vector or predicate type.
8448
482
  if (!CurType->isSveVLSBuiltinType()) {
8449
25
    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_sve_type)
8450
25
        << Attr << CurType;
8451
25
    Attr.setInvalid();
8452
25
    return;
8453
25
  }
8454
8455
457
  const auto *BT = CurType->castAs<BuiltinType>();
8456
8457
457
  QualType EltType = CurType->getSveEltType(S.Context);
8458
457
  unsigned TypeSize = S.Context.getTypeSize(EltType);
8459
457
  VectorKind VecKind = VectorKind::SveFixedLengthData;
8460
457
  if (BT->getKind() == BuiltinType::SveBool) {
8461
    // Predicates are represented as i8.
8462
43
    VecSize /= S.Context.getCharWidth() * S.Context.getCharWidth();
8463
43
    VecKind = VectorKind::SveFixedLengthPredicate;
8464
43
  } else
8465
414
    VecSize /= TypeSize;
8466
457
  CurType = S.Context.getVectorType(EltType, VecSize, VecKind);
8467
457
}
8468
8469
static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State,
8470
                                               QualType &CurType,
8471
1.58k
                                               ParsedAttr &Attr) {
8472
1.58k
  const VectorType *VT = dyn_cast<VectorType>(CurType);
8473
1.58k
  if (!VT || 
VT->getVectorKind() != VectorKind::Neon1.58k
) {
8474
3
    State.getSema().Diag(Attr.getLoc(),
8475
3
                         diag::err_attribute_arm_mve_polymorphism);
8476
3
    Attr.setInvalid();
8477
3
    return;
8478
3
  }
8479
8480
1.58k
  CurType =
8481
1.58k
      State.getAttributedType(createSimpleAttr<ArmMveStrictPolymorphismAttr>(
8482
1.58k
                                  State.getSema().Context, Attr),
8483
1.58k
                              CurType, CurType);
8484
1.58k
}
8485
8486
/// HandleRISCVRVVVectorBitsTypeAttr - The "riscv_rvv_vector_bits" attribute is
8487
/// used to create fixed-length versions of sizeless RVV types such as
8488
/// vint8m1_t_t.
8489
static void HandleRISCVRVVVectorBitsTypeAttr(QualType &CurType,
8490
856
                                             ParsedAttr &Attr, Sema &S) {
8491
  // Target must have vector extension.
8492
856
  if (!S.Context.getTargetInfo().hasFeature("zve32x")) {
8493
1
    S.Diag(Attr.getLoc(), diag::err_attribute_unsupported)
8494
1
        << Attr << "'zve32x'";
8495
1
    Attr.setInvalid();
8496
1
    return;
8497
1
  }
8498
8499
855
  auto VScale = S.Context.getTargetInfo().getVScaleRange(S.getLangOpts());
8500
855
  if (!VScale || !VScale->first || VScale->first != VScale->second) {
8501
4
    S.Diag(Attr.getLoc(), diag::err_attribute_riscv_rvv_bits_unsupported)
8502
4
        << Attr;
8503
4
    Attr.setInvalid();
8504
4
    return;
8505
4
  }
8506
8507
  // Check the attribute arguments.
8508
851
  if (Attr.getNumArgs() != 1) {
8509
10
    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8510
10
        << Attr << 1;
8511
10
    Attr.setInvalid();
8512
10
    return;
8513
10
  }
8514
8515
  // The vector size must be an integer constant expression.
8516
841
  llvm::APSInt RVVVectorSizeInBits(32);
8517
841
  if (!verifyValidIntegerConstantExpr(S, Attr, RVVVectorSizeInBits))
8518
10
    return;
8519
8520
  // Attribute can only be attached to a single RVV vector type.
8521
831
  if (!CurType->isRVVVLSBuiltinType()) {
8522
20
    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_rvv_type)
8523
20
        << Attr << CurType;
8524
20
    Attr.setInvalid();
8525
20
    return;
8526
20
  }
8527
8528
811
  unsigned VecSize = static_cast<unsigned>(RVVVectorSizeInBits.getZExtValue());
8529
8530
811
  ASTContext::BuiltinVectorTypeInfo Info =
8531
811
      S.Context.getBuiltinVectorTypeInfo(CurType->castAs<BuiltinType>());
8532
811
  unsigned EltSize = S.Context.getTypeSize(Info.ElementType);
8533
811
  unsigned MinElts = Info.EC.getKnownMinValue();
8534
8535
  // The attribute vector size must match -mrvv-vector-bits.
8536
811
  unsigned ExpectedSize = VScale->first * MinElts * EltSize;
8537
811
  if (VecSize != ExpectedSize) {
8538
2
    S.Diag(Attr.getLoc(), diag::err_attribute_bad_rvv_vector_size)
8539
2
        << VecSize << ExpectedSize;
8540
2
    Attr.setInvalid();
8541
2
    return;
8542
2
  }
8543
8544
809
  VectorKind VecKind = VectorKind::RVVFixedLengthData;
8545
809
  VecSize /= EltSize;
8546
809
  CurType = S.Context.getVectorType(Info.ElementType, VecSize, VecKind);
8547
809
}
8548
8549
/// Handle OpenCL Access Qualifier Attribute.
8550
static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr,
8551
8.74k
                                   Sema &S) {
8552
  // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
8553
8.74k
  if (!(CurType->isImageType() || 
CurType->isPipeType()221
)) {
8554
21
    S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
8555
21
    Attr.setInvalid();
8556
21
    return;
8557
21
  }
8558
8559
8.72k
  if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
8560
36
    QualType BaseTy = TypedefTy->desugar();
8561
8562
36
    std::string PrevAccessQual;
8563
36
    if (BaseTy->isPipeType()) {
8564
3
      if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) {
8565
3
        OpenCLAccessAttr *Attr =
8566
3
            TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>();
8567
3
        PrevAccessQual = Attr->getSpelling();
8568
3
      } else {
8569
0
        PrevAccessQual = "read_only";
8570
0
      }
8571
33
    } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) {
8572
8573
33
      switch (ImgType->getKind()) {
8574
0
        #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8575
33
      case BuiltinType::Id:                                          \
8576
33
        PrevAccessQual = #Access;                                    \
8577
33
        break;
8578
0
        #include "clang/Basic/OpenCLImageTypes.def"
8579
0
      default:
8580
0
        llvm_unreachable("Unable to find corresponding image type.");
8581
33
      }
8582
33
    } else {
8583
0
      llvm_unreachable("unexpected type");
8584
0
    }
8585
36
    StringRef AttrName = Attr.getAttrName()->getName();
8586
36
    if (PrevAccessQual == AttrName.ltrim("_")) {
8587
      // Duplicated qualifiers
8588
24
      S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec)
8589
24
         << AttrName << Attr.getRange();
8590
24
    } else {
8591
      // Contradicting qualifiers
8592
12
      S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
8593
12
    }
8594
8595
36
    S.Diag(TypedefTy->getDecl()->getBeginLoc(),
8596
36
           diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
8597
8.69k
  } else if (CurType->isPipeType()) {
8598
197
    if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
8599
48
      QualType ElemType = CurType->castAs<PipeType>()->getElementType();
8600
48
      CurType = S.Context.getWritePipeType(ElemType);
8601
48
    }
8602
197
  }
8603
8.72k
}
8604
8605
/// HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type
8606
static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8607
214
                                 Sema &S) {
8608
214
  if (!S.getLangOpts().MatrixTypes) {
8609
1
    S.Diag(Attr.getLoc(), diag::err_builtin_matrix_disabled);
8610
1
    return;
8611
1
  }
8612
8613
213
  if (Attr.getNumArgs() != 2) {
8614
0
    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8615
0
        << Attr << 2;
8616
0
    return;
8617
0
  }
8618
8619
213
  Expr *RowsExpr = Attr.getArgAsExpr(0);
8620
213
  Expr *ColsExpr = Attr.getArgAsExpr(1);
8621
213
  QualType T = S.BuildMatrixType(CurType, RowsExpr, ColsExpr, Attr.getLoc());
8622
213
  if (!T.isNull())
8623
200
    CurType = T;
8624
213
}
8625
8626
static void HandleAnnotateTypeAttr(TypeProcessingState &State,
8627
56
                                   QualType &CurType, const ParsedAttr &PA) {
8628
56
  Sema &S = State.getSema();
8629
8630
56
  if (PA.getNumArgs() < 1) {
8631
3
    S.Diag(PA.getLoc(), diag::err_attribute_too_few_arguments) << PA << 1;
8632
3
    return;
8633
3
  }
8634
8635
  // Make sure that there is a string literal as the annotation's first
8636
  // argument.
8637
53
  StringRef Str;
8638
53
  if (!S.checkStringLiteralArgumentAttr(PA, 0, Str))
8639
0
    return;
8640
8641
53
  llvm::SmallVector<Expr *, 4> Args;
8642
53
  Args.reserve(PA.getNumArgs() - 1);
8643
62
  for (unsigned Idx = 1; Idx < PA.getNumArgs(); 
Idx++9
) {
8644
9
    assert(!PA.isArgIdent(Idx));
8645
9
    Args.push_back(PA.getArgAsExpr(Idx));
8646
9
  }
8647
53
  if (!S.ConstantFoldAttrArgs(PA, Args))
8648
2
    return;
8649
51
  auto *AnnotateTypeAttr =
8650
51
      AnnotateTypeAttr::Create(S.Context, Str, Args.data(), Args.size(), PA);
8651
51
  CurType = State.getAttributedType(AnnotateTypeAttr, CurType, CurType);
8652
51
}
8653
8654
static void HandleLifetimeBoundAttr(TypeProcessingState &State,
8655
                                    QualType &CurType,
8656
8
                                    ParsedAttr &Attr) {
8657
8
  if (State.getDeclarator().isDeclarationOfFunction()) {
8658
8
    CurType = State.getAttributedType(
8659
8
        createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr),
8660
8
        CurType, CurType);
8661
8
  }
8662
8
}
8663
8664
static void processTypeAttrs(TypeProcessingState &state, QualType &type,
8665
                             TypeAttrLocation TAL,
8666
                             const ParsedAttributesView &attrs,
8667
672M
                             Sema::CUDAFunctionTarget CFT) {
8668
8669
672M
  state.setParsedNoDeref(false);
8670
672M
  if (attrs.empty())
8671
633M
    return;
8672
8673
  // Scan through and apply attributes to this type where it makes sense.  Some
8674
  // attributes (such as __address_space__, __vector_size__, etc) apply to the
8675
  // type, but others can be present in the type specifiers even though they
8676
  // apply to the decl.  Here we apply type attributes and ignore the rest.
8677
8678
  // This loop modifies the list pretty frequently, but we still need to make
8679
  // sure we visit every element once. Copy the attributes list, and iterate
8680
  // over that.
8681
39.6M
  ParsedAttributesView AttrsCopy{attrs};
8682
122M
  for (ParsedAttr &attr : AttrsCopy) {
8683
8684
    // Skip attributes that were marked to be invalid.
8685
122M
    if (attr.isInvalid())
8686
75
      continue;
8687
8688
122M
    if (attr.isStandardAttributeSyntax() || 
attr.isRegularKeywordAttribute()122M
) {
8689
      // [[gnu::...]] attributes are treated as declaration attributes, so may
8690
      // not appertain to a DeclaratorChunk. If we handle them as type
8691
      // attributes, accept them in that position and diagnose the GCC
8692
      // incompatibility.
8693
1.35M
      if (attr.isGNUScope()) {
8694
534
        assert(attr.isStandardAttributeSyntax());
8695
534
        bool IsTypeAttr = attr.isTypeAttr();
8696
534
        if (TAL == TAL_DeclChunk) {
8697
16
          state.getSema().Diag(attr.getLoc(),
8698
16
                               IsTypeAttr
8699
16
                                   ? 
diag::warn_gcc_ignores_type_attr7
8700
16
                                   : 
diag::warn_cxx11_gnu_attribute_on_type9
)
8701
16
              << attr;
8702
16
          if (!IsTypeAttr)
8703
9
            continue;
8704
16
        }
8705
1.35M
      } else if (TAL != TAL_DeclSpec && 
TAL != TAL_DeclChunk1.35M
&&
8706
1.35M
                 
!attr.isTypeAttr()118k
) {
8707
        // Otherwise, only consider type processing for a C++11 attribute if
8708
        // - it has actually been applied to a type (decl-specifier-seq or
8709
        //   declarator chunk), or
8710
        // - it is a type attribute, irrespective of where it was applied (so
8711
        //   that we can support the legacy behavior of some type attributes
8712
        //   that can be applied to the declaration name).
8713
110k
        continue;
8714
110k
      }
8715
1.35M
    }
8716
8717
    // If this is an attribute we can handle, do so now,
8718
    // otherwise, add it to the FnAttrs list for rechaining.
8719
122M
    switch (attr.getKind()) {
8720
118M
    default:
8721
      // A [[]] attribute on a declarator chunk must appertain to a type.
8722
118M
      if ((attr.isStandardAttributeSyntax() ||
8723
118M
           
attr.isRegularKeywordAttribute()118M
) &&
8724
118M
          
TAL == TAL_DeclChunk502
) {
8725
12
        state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
8726
12
            << attr << attr.isRegularKeywordAttribute();
8727
12
        attr.setUsedAsTypeAttr();
8728
12
      }
8729
118M
      break;
8730
8731
535k
    case ParsedAttr::UnknownAttribute:
8732
535k
      if (attr.isStandardAttributeSyntax()) {
8733
16
        state.getSema().Diag(attr.getLoc(),
8734
16
                             diag::warn_unknown_attribute_ignored)
8735
16
            << attr << attr.getRange();
8736
        // Mark the attribute as invalid so we don't emit the same diagnostic
8737
        // multiple times.
8738
16
        attr.setInvalid();
8739
16
      }
8740
535k
      break;
8741
8742
163
    case ParsedAttr::IgnoredAttribute:
8743
163
      break;
8744
8745
68
    case ParsedAttr::AT_BTFTypeTag:
8746
68
      HandleBTFTypeTagAttribute(type, attr, state);
8747
68
      attr.setUsedAsTypeAttr();
8748
68
      break;
8749
8750
36
    case ParsedAttr::AT_MayAlias:
8751
      // FIXME: This attribute needs to actually be handled, but if we ignore
8752
      // it it breaks large amounts of Linux software.
8753
36
      attr.setUsedAsTypeAttr();
8754
36
      break;
8755
5.19k
    case ParsedAttr::AT_OpenCLPrivateAddressSpace:
8756
22.5k
    case ParsedAttr::AT_OpenCLGlobalAddressSpace:
8757
22.5k
    case ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace:
8758
22.6k
    case ParsedAttr::AT_OpenCLGlobalHostAddressSpace:
8759
37.5k
    case ParsedAttr::AT_OpenCLLocalAddressSpace:
8760
40.2k
    case ParsedAttr::AT_OpenCLConstantAddressSpace:
8761
42.1k
    case ParsedAttr::AT_OpenCLGenericAddressSpace:
8762
42.2k
    case ParsedAttr::AT_HLSLGroupSharedAddressSpace:
8763
43.2k
    case ParsedAttr::AT_AddressSpace:
8764
43.2k
      HandleAddressSpaceTypeAttribute(type, attr, state);
8765
43.2k
      attr.setUsedAsTypeAttr();
8766
43.2k
      break;
8767
8.22k
    
OBJC_POINTER_TYPE_ATTRS_CASELIST292
:
8768
8.22k
      if (!handleObjCPointerTypeAttr(state, attr, type))
8769
1.62k
        distributeObjCPointerTypeAttr(state, attr, type);
8770
8.22k
      attr.setUsedAsTypeAttr();
8771
8.22k
      break;
8772
36.0k
    case ParsedAttr::AT_VectorSize:
8773
36.0k
      HandleVectorSizeAttr(type, attr, state.getSema());
8774
36.0k
      attr.setUsedAsTypeAttr();
8775
36.0k
      break;
8776
5.47k
    case ParsedAttr::AT_ExtVectorType:
8777
5.47k
      HandleExtVectorTypeAttr(type, attr, state.getSema());
8778
5.47k
      attr.setUsedAsTypeAttr();
8779
5.47k
      break;
8780
6.42k
    case ParsedAttr::AT_NeonVectorType:
8781
6.42k
      HandleNeonVectorTypeAttr(type, attr, state.getSema(), VectorKind::Neon);
8782
6.42k
      attr.setUsedAsTypeAttr();
8783
6.42k
      break;
8784
1.24k
    case ParsedAttr::AT_NeonPolyVectorType:
8785
1.24k
      HandleNeonVectorTypeAttr(type, attr, state.getSema(),
8786
1.24k
                               VectorKind::NeonPoly);
8787
1.24k
      attr.setUsedAsTypeAttr();
8788
1.24k
      break;
8789
511
    case ParsedAttr::AT_ArmSveVectorBits:
8790
511
      HandleArmSveVectorBitsTypeAttr(type, attr, state.getSema());
8791
511
      attr.setUsedAsTypeAttr();
8792
511
      break;
8793
1.58k
    case ParsedAttr::AT_ArmMveStrictPolymorphism: {
8794
1.58k
      HandleArmMveStrictPolymorphismAttr(state, type, attr);
8795
1.58k
      attr.setUsedAsTypeAttr();
8796
1.58k
      break;
8797
292
    }
8798
856
    case ParsedAttr::AT_RISCVRVVVectorBits:
8799
856
      HandleRISCVRVVVectorBitsTypeAttr(type, attr, state.getSema());
8800
856
      attr.setUsedAsTypeAttr();
8801
856
      break;
8802
8.74k
    case ParsedAttr::AT_OpenCLAccess:
8803
8.74k
      HandleOpenCLAccessAttr(type, attr, state.getSema());
8804
8.74k
      attr.setUsedAsTypeAttr();
8805
8.74k
      break;
8806
7.66k
    case ParsedAttr::AT_LifetimeBound:
8807
7.66k
      if (TAL == TAL_DeclChunk)
8808
8
        HandleLifetimeBoundAttr(state, type, attr);
8809
7.66k
      break;
8810
8811
104
    case ParsedAttr::AT_NoDeref: {
8812
      // FIXME: `noderef` currently doesn't work correctly in [[]] syntax.
8813
      // See https://github.com/llvm/llvm-project/issues/55790 for details.
8814
      // For the time being, we simply emit a warning that the attribute is
8815
      // ignored.
8816
104
      if (attr.isStandardAttributeSyntax()) {
8817
5
        state.getSema().Diag(attr.getLoc(), diag::warn_attribute_ignored)
8818
5
            << attr;
8819
5
        break;
8820
5
      }
8821
99
      ASTContext &Ctx = state.getSema().Context;
8822
99
      type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr),
8823
99
                                     type, type);
8824
99
      attr.setUsedAsTypeAttr();
8825
99
      state.setParsedNoDeref(true);
8826
99
      break;
8827
104
    }
8828
8829
214
    case ParsedAttr::AT_MatrixType:
8830
214
      HandleMatrixTypeAttr(type, attr, state.getSema());
8831
214
      attr.setUsedAsTypeAttr();
8832
214
      break;
8833
8834
10
    case ParsedAttr::AT_WebAssemblyFuncref: {
8835
10
      if (!HandleWebAssemblyFuncrefAttr(state, type, attr))
8836
8
        attr.setUsedAsTypeAttr();
8837
10
      break;
8838
104
    }
8839
8840
147
    
MS_TYPE_ATTRS_CASELIST67
:
8841
147
      if (!handleMSPointerTypeQualifierAttr(state, attr, type))
8842
123
        attr.setUsedAsTypeAttr();
8843
147
      break;
8844
8845
8846
2.04M
    
NULLABILITY_TYPE_ATTRS_CASELIST1.04M
:
8847
      // Either add nullability here or try to distribute it.  We
8848
      // don't want to distribute the nullability specifier past any
8849
      // dependent type, because that complicates the user model.
8850
2.04M
      if (type->canHaveNullability() || 
type->isDependentType()13.6k
||
8851
2.04M
          
type->isArrayType()13.6k
||
8852
2.04M
          
!distributeNullabilityTypeAttr(state, type, attr)67
) {
8853
2.04M
        unsigned endIndex;
8854
2.04M
        if (TAL == TAL_DeclChunk)
8855
1.55M
          endIndex = state.getCurrentChunkIndex();
8856
485k
        else
8857
485k
          endIndex = state.getDeclarator().getNumTypeObjects();
8858
2.04M
        bool allowOnArrayType =
8859
2.04M
            state.getDeclarator().isPrototypeContext() &&
8860
2.04M
            
!hasOuterPointerLikeChunk(state.getDeclarator(), endIndex)1.58M
;
8861
2.04M
        if (checkNullabilityTypeSpecifier(
8862
2.04M
              state,
8863
2.04M
              type,
8864
2.04M
              attr,
8865
2.04M
              allowOnArrayType)) {
8866
56
          attr.setInvalid();
8867
56
        }
8868
8869
2.04M
        attr.setUsedAsTypeAttr();
8870
2.04M
      }
8871
2.04M
      break;
8872
8873
1.84k
    case ParsedAttr::AT_ObjCKindOf:
8874
      // '__kindof' must be part of the decl-specifiers.
8875
1.84k
      switch (TAL) {
8876
1.84k
      case TAL_DeclSpec:
8877
1.84k
        break;
8878
8879
1
      case TAL_DeclChunk:
8880
1
      case TAL_DeclName:
8881
1
        state.getSema().Diag(attr.getLoc(),
8882
1
                             diag::err_objc_kindof_wrong_position)
8883
1
            << FixItHint::CreateRemoval(attr.getLoc())
8884
1
            << FixItHint::CreateInsertion(
8885
1
                   state.getDeclarator().getDeclSpec().getBeginLoc(),
8886
1
                   "__kindof ");
8887
1
        break;
8888
1.84k
      }
8889
8890
      // Apply it regardless.
8891
1.84k
      if (checkObjCKindOfType(state, type, attr))
8892
2
        attr.setInvalid();
8893
1.84k
      break;
8894
8895
99.0k
    case ParsedAttr::AT_NoThrow:
8896
    // Exception Specifications aren't generally supported in C mode throughout
8897
    // clang, so revert to attribute-based handling for C.
8898
99.0k
      if (!state.getSema().getLangOpts().CPlusPlus)
8899
23.2k
        break;
8900
99.0k
      
[[fallthrough]];75.7k
8901
33.0M
    
FUNCTION_TYPE_ATTRS_CASELIST102k
:
8902
33.0M
      attr.setUsedAsTypeAttr();
8903
8904
      // Attributes with standard syntax have strict rules for what they
8905
      // appertain to and hence should not use the "distribution" logic below.
8906
33.0M
      if (
attr.isStandardAttributeSyntax()1.35M
||
8907
1.35M
          
attr.isRegularKeywordAttribute()1.35M
) {
8908
1.23M
        if (!handleFunctionTypeAttr(state, attr, type, CFT)) {
8909
100
          diagnoseBadTypeAttribute(state.getSema(), attr, type);
8910
100
          attr.setInvalid();
8911
100
        }
8912
1.23M
        break;
8913
1.23M
      }
8914
8915
      // Never process function type attributes as part of the
8916
      // declaration-specifiers.
8917
116k
      if (TAL == TAL_DeclSpec)
8918
45.6k
        distributeFunctionTypeAttrFromDeclSpec(state, attr, type, CFT);
8919
8920
      // Otherwise, handle the possible delays.
8921
70.6k
      else if (!handleFunctionTypeAttr(state, attr, type, CFT))
8922
34
        distributeFunctionTypeAttr(state, attr, type);
8923
116k
      break;
8924
16
    case ParsedAttr::AT_AcquireHandle: {
8925
16
      if (!type->isFunctionType())
8926
13
        return;
8927
8928
3
      if (attr.getNumArgs() != 1) {
8929
1
        state.getSema().Diag(attr.getLoc(),
8930
1
                             diag::err_attribute_wrong_number_arguments)
8931
1
            << attr << 1;
8932
1
        attr.setInvalid();
8933
1
        return;
8934
1
      }
8935
8936
2
      StringRef HandleType;
8937
2
      if (!state.getSema().checkStringLiteralArgumentAttr(attr, 0, HandleType))
8938
0
        return;
8939
2
      type = state.getAttributedType(
8940
2
          AcquireHandleAttr::Create(state.getSema().Context, HandleType, attr),
8941
2
          type, type);
8942
2
      attr.setUsedAsTypeAttr();
8943
2
      break;
8944
2
    }
8945
56
    case ParsedAttr::AT_AnnotateType: {
8946
56
      HandleAnnotateTypeAttr(state, type, attr);
8947
56
      attr.setUsedAsTypeAttr();
8948
56
      break;
8949
2
    }
8950
122M
    }
8951
8952
    // Handle attributes that are defined in a macro. We do not want this to be
8953
    // applied to ObjC builtin attributes.
8954
122M
    if (isa<AttributedType>(type) && 
attr.hasMacroIdentifier()3.60M
&&
8955
122M
        
!type.getQualifiers().hasObjCLifetime()238k
&&
8956
122M
        
!type.getQualifiers().hasObjCGCAttr()238k
&&
8957
122M
        
attr.getKind() != ParsedAttr::AT_ObjCGC238k
&&
8958
122M
        
attr.getKind() != ParsedAttr::AT_ObjCOwnership238k
) {
8959
238k
      const IdentifierInfo *MacroII = attr.getMacroIdentifier();
8960
238k
      type = state.getSema().Context.getMacroQualifiedType(type, MacroII);
8961
238k
      state.setExpansionLocForMacroQualifiedType(
8962
238k
          cast<MacroQualifiedType>(type.getTypePtr()),
8963
238k
          attr.getMacroExpansionLoc());
8964
238k
    }
8965
122M
  }
8966
39.6M
}
8967
8968
85
void Sema::completeExprArrayBound(Expr *E) {
8969
85
  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
8970
83
    if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
8971
83
      if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
8972
26
        auto *Def = Var->getDefinition();
8973
26
        if (!Def) {
8974
24
          SourceLocation PointOfInstantiation = E->getExprLoc();
8975
24
          runWithSufficientStackSpace(PointOfInstantiation, [&] {
8976
24
            InstantiateVariableDefinition(PointOfInstantiation, Var);
8977
24
          });
8978
24
          Def = Var->getDefinition();
8979
8980
          // If we don't already have a point of instantiation, and we managed
8981
          // to instantiate a definition, this is the point of instantiation.
8982
          // Otherwise, we don't request an end-of-TU instantiation, so this is
8983
          // not a point of instantiation.
8984
          // FIXME: Is this really the right behavior?
8985
24
          if (Var->getPointOfInstantiation().isInvalid() && 
Def8
) {
8986
7
            assert(Var->getTemplateSpecializationKind() ==
8987
7
                       TSK_ImplicitInstantiation &&
8988
7
                   "explicit instantiation with no point of instantiation");
8989
7
            Var->setTemplateSpecializationKind(
8990
7
                Var->getTemplateSpecializationKind(), PointOfInstantiation);
8991
7
          }
8992
24
        }
8993
8994
        // Update the type to the definition's type both here and within the
8995
        // expression.
8996
26
        if (Def) {
8997
25
          DRE->setDecl(Def);
8998
25
          QualType T = Def->getType();
8999
25
          DRE->setType(T);
9000
          // FIXME: Update the type on all intervening expressions.
9001
25
          E->setType(T);
9002
25
        }
9003
9004
        // We still go on to try to complete the type independently, as it
9005
        // may also require instantiations or diagnostics if it remains
9006
        // incomplete.
9007
26
      }
9008
83
    }
9009
83
  }
9010
85
}
9011
9012
681k
QualType Sema::getCompletedType(Expr *E) {
9013
  // Incomplete array types may be completed by the initializer attached to
9014
  // their definitions. For static data members of class templates and for
9015
  // variable templates, we need to instantiate the definition to get this
9016
  // initializer and complete the type.
9017
681k
  if (E->getType()->isIncompleteArrayType())
9018
85
    completeExprArrayBound(E);
9019
9020
  // FIXME: Are there other cases which require instantiating something other
9021
  // than the type to complete the type of an expression?
9022
9023
681k
  return E->getType();
9024
681k
}
9025
9026
/// Ensure that the type of the given expression is complete.
9027
///
9028
/// This routine checks whether the expression \p E has a complete type. If the
9029
/// expression refers to an instantiable construct, that instantiation is
9030
/// performed as needed to complete its type. Furthermore
9031
/// Sema::RequireCompleteType is called for the expression's type (or in the
9032
/// case of a reference type, the referred-to type).
9033
///
9034
/// \param E The expression whose type is required to be complete.
9035
/// \param Kind Selects which completeness rules should be applied.
9036
/// \param Diagnoser The object that will emit a diagnostic if the type is
9037
/// incomplete.
9038
///
9039
/// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
9040
/// otherwise.
9041
bool Sema::RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
9042
13.1k
                                   TypeDiagnoser &Diagnoser) {
9043
13.1k
  return RequireCompleteType(E->getExprLoc(), getCompletedType(E), Kind,
9044
13.1k
                             Diagnoser);
9045
13.1k
}
9046
9047
297
bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
9048
297
  BoundTypeDiagnoser<> Diagnoser(DiagID);
9049
297
  return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
9050
297
}
9051
9052
/// Ensure that the type T is a complete type.
9053
///
9054
/// This routine checks whether the type @p T is complete in any
9055
/// context where a complete type is required. If @p T is a complete
9056
/// type, returns false. If @p T is a class template specialization,
9057
/// this routine then attempts to perform class template
9058
/// instantiation. If instantiation fails, or if @p T is incomplete
9059
/// and cannot be completed, issues the diagnostic @p diag (giving it
9060
/// the type @p T) and returns true.
9061
///
9062
/// @param Loc  The location in the source that the incomplete type
9063
/// diagnostic should refer to.
9064
///
9065
/// @param T  The type that this routine is examining for completeness.
9066
///
9067
/// @param Kind Selects which completeness rules should be applied.
9068
///
9069
/// @returns @c true if @p T is incomplete and a diagnostic was emitted,
9070
/// @c false otherwise.
9071
bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
9072
                               CompleteTypeKind Kind,
9073
44.3M
                               TypeDiagnoser &Diagnoser) {
9074
44.3M
  if (RequireCompleteTypeImpl(Loc, T, Kind, &Diagnoser))
9075
13.1k
    return true;
9076
44.3M
  if (const TagType *Tag = T->getAs<TagType>()) {
9077
7.69M
    if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
9078
1.01M
      Tag->getDecl()->setCompleteDefinitionRequired();
9079
1.01M
      Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
9080
1.01M
    }
9081
7.69M
  }
9082
44.3M
  return false;
9083
44.3M
}
9084
9085
14
bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) {
9086
14
  llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
9087
14
  if (!Suggested)
9088
0
    return false;
9089
9090
  // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
9091
  // and isolate from other C++ specific checks.
9092
14
  StructuralEquivalenceContext Ctx(
9093
14
      D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls,
9094
14
      StructuralEquivalenceKind::Default,
9095
14
      false /*StrictTypeSpelling*/, true /*Complain*/,
9096
14
      true /*ErrorOnTagTypeMismatch*/);
9097
14
  return Ctx.IsEquivalent(D, Suggested);
9098
14
}
9099
9100
bool Sema::hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
9101
33.0M
                                   AcceptableKind Kind, bool OnlyNeedComplete) {
9102
  // Easy case: if we don't have modules, all declarations are visible.
9103
33.0M
  if (!getLangOpts().Modules && 
!getLangOpts().ModulesLocalVisibility31.2M
)
9104
31.2M
    return true;
9105
9106
  // If this definition was instantiated from a template, map back to the
9107
  // pattern from which it was instantiated.
9108
1.86M
  if (isa<TagDecl>(D) && 
cast<TagDecl>(D)->isBeingDefined()1.79M
) {
9109
    // We're in the middle of defining it; this definition should be treated
9110
    // as visible.
9111
6
    return true;
9112
1.86M
  } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9113
1.13M
    if (auto *Pattern = RD->getTemplateInstantiationPattern())
9114
550k
      RD = Pattern;
9115
1.13M
    D = RD->getDefinition();
9116
1.13M
  } else 
if (auto *732k
ED732k
= dyn_cast<EnumDecl>(D)) {
9117
642k
    if (auto *Pattern = ED->getTemplateInstantiationPattern())
9118
48.9k
      ED = Pattern;
9119
642k
    if (OnlyNeedComplete && 
(629k
ED->isFixed()629k
||
getLangOpts().MSVCCompat343k
)) {
9120
      // If the enum has a fixed underlying type, it may have been forward
9121
      // declared. In -fms-compatibility, `enum Foo;` will also forward declare
9122
      // the enum and assign it the underlying type of `int`. Since we're only
9123
      // looking for a complete type (not a definition), any visible declaration
9124
      // of it will do.
9125
286k
      *Suggested = nullptr;
9126
287k
      for (auto *Redecl : ED->redecls()) {
9127
287k
        if (isAcceptable(Redecl, Kind))
9128
286k
          return true;
9129
44
        if (Redecl->isThisDeclarationADefinition() ||
9130
44
            
(8
Redecl->isCanonicalDecl()8
&&
!*Suggested8
))
9131
38
          *Suggested = Redecl;
9132
44
      }
9133
9134
2
      return false;
9135
286k
    }
9136
355k
    D = ED->getDefinition();
9137
355k
  } else 
if (auto *90.1k
FD90.1k
= dyn_cast<FunctionDecl>(D)) {
9138
15.9k
    if (auto *Pattern = FD->getTemplateInstantiationPattern())
9139
1
      FD = Pattern;
9140
15.9k
    D = FD->getDefinition();
9141
74.1k
  } else if (auto *VD = dyn_cast<VarDecl>(D)) {
9142
52.0k
    if (auto *Pattern = VD->getTemplateInstantiationPattern())
9143
6.59k
      VD = Pattern;
9144
52.0k
    D = VD->getDefinition();
9145
52.0k
  }
9146
9147
1.57M
  assert(D && "missing definition for pattern of instantiated definition");
9148
9149
1.57M
  *Suggested = D;
9150
9151
1.58M
  auto DefinitionIsAcceptable = [&] {
9152
    // The (primary) definition might be in a visible module.
9153
1.58M
    if (isAcceptable(D, Kind))
9154
1.57M
      return true;
9155
9156
    // A visible module might have a merged definition instead.
9157
9.45k
    if (D->isModulePrivate() ? 
hasMergedDefinitionInCurrentModule(D)18
9158
9.45k
                             : 
hasVisibleMergedDefinition(D)9.43k
) {
9159
619
      if (CodeSynthesisContexts.empty() &&
9160
619
          
!getLangOpts().ModulesLocalVisibility616
) {
9161
        // Cache the fact that this definition is implicitly visible because
9162
        // there is a visible merged definition.
9163
34
        D->setVisibleDespiteOwningModule();
9164
34
      }
9165
619
      return true;
9166
619
    }
9167
9168
8.83k
    return false;
9169
9.45k
  };
9170
9171
1.57M
  if (DefinitionIsAcceptable())
9172
1.57M
    return true;
9173
9174
  // The external source may have additional definitions of this entity that are
9175
  // visible, so complete the redeclaration chain now and ask again.
9176
4.41k
  if (auto *Source = Context.getExternalSource()) {
9177
4.41k
    Source->CompleteRedeclChain(D);
9178
4.41k
    return DefinitionIsAcceptable();
9179
4.41k
  }
9180
9181
0
  return false;
9182
4.41k
}
9183
9184
/// Determine whether there is any declaration of \p D that was ever a
9185
///        definition (perhaps before module merging) and is currently visible.
9186
/// \param D The definition of the entity.
9187
/// \param Suggested Filled in with the declaration that should be made visible
9188
///        in order to provide a definition of this entity.
9189
/// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9190
///        not defined. This only matters for enums with a fixed underlying
9191
///        type, since in all other cases, a type is complete if and only if it
9192
///        is defined.
9193
bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
9194
909
                                bool OnlyNeedComplete) {
9195
909
  return hasAcceptableDefinition(D, Suggested, Sema::AcceptableKind::Visible,
9196
909
                                 OnlyNeedComplete);
9197
909
}
9198
9199
/// Determine whether there is any declaration of \p D that was ever a
9200
///        definition (perhaps before module merging) and is currently
9201
///        reachable.
9202
/// \param D The definition of the entity.
9203
/// \param Suggested Filled in with the declaration that should be made
9204
/// reachable
9205
///        in order to provide a definition of this entity.
9206
/// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9207
///        not defined. This only matters for enums with a fixed underlying
9208
///        type, since in all other cases, a type is complete if and only if it
9209
///        is defined.
9210
bool Sema::hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
9211
33.0M
                                  bool OnlyNeedComplete) {
9212
33.0M
  return hasAcceptableDefinition(D, Suggested, Sema::AcceptableKind::Reachable,
9213
33.0M
                                 OnlyNeedComplete);
9214
33.0M
}
9215
9216
/// Locks in the inheritance model for the given class and all of its bases.
9217
2.38k
static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
9218
2.38k
  RD = RD->getMostRecentNonInjectedDecl();
9219
2.38k
  if (!RD->hasAttr<MSInheritanceAttr>()) {
9220
715
    MSInheritanceModel IM;
9221
715
    bool BestCase = false;
9222
715
    switch (S.MSPointerToMemberRepresentationMethod) {
9223
681
    case LangOptions::PPTMK_BestCase:
9224
681
      BestCase = true;
9225
681
      IM = RD->calculateInheritanceModel();
9226
681
      break;
9227
4
    case LangOptions::PPTMK_FullGeneralitySingleInheritance:
9228
4
      IM = MSInheritanceModel::Single;
9229
4
      break;
9230
2
    case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
9231
2
      IM = MSInheritanceModel::Multiple;
9232
2
      break;
9233
28
    case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
9234
28
      IM = MSInheritanceModel::Unspecified;
9235
28
      break;
9236
715
    }
9237
9238
715
    SourceRange Loc = S.ImplicitMSInheritanceAttrLoc.isValid()
9239
715
                          ? 
S.ImplicitMSInheritanceAttrLoc56
9240
715
                          : 
RD->getSourceRange()659
;
9241
715
    RD->addAttr(MSInheritanceAttr::CreateImplicit(
9242
715
        S.getASTContext(), BestCase, Loc, MSInheritanceAttr::Spelling(IM)));
9243
715
    S.Consumer.AssignInheritanceModel(RD);
9244
715
  }
9245
2.38k
}
9246
9247
/// The implementation of RequireCompleteType
9248
bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
9249
                                   CompleteTypeKind Kind,
9250
70.7M
                                   TypeDiagnoser *Diagnoser) {
9251
  // FIXME: Add this assertion to make sure we always get instantiation points.
9252
  //  assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
9253
  // FIXME: Add this assertion to help us flush out problems with
9254
  // checking for dependent types and type-dependent expressions.
9255
  //
9256
  //  assert(!T->isDependentType() &&
9257
  //         "Can't ask whether a dependent type is complete");
9258
9259
70.7M
  if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
9260
11.5k
    if (!MPTy->getClass()->isDependentType()) {
9261
7.00k
      if (getLangOpts().CompleteMemberPointers &&
9262
7.00k
          
!MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined()4
&&
9263
7.00k
          RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), Kind,
9264
2
                              diag::err_memptr_incomplete))
9265
1
        return true;
9266
9267
      // We lock in the inheritance model once somebody has asked us to ensure
9268
      // that a pointer-to-member type is complete.
9269
7.00k
      if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9270
2.38k
        (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
9271
2.38k
        assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
9272
2.38k
      }
9273
7.00k
    }
9274
11.5k
  }
9275
9276
70.7M
  NamedDecl *Def = nullptr;
9277
70.7M
  bool AcceptSizeless = (Kind == CompleteTypeKind::AcceptSizeless);
9278
70.7M
  bool Incomplete = (T->isIncompleteType(&Def) ||
9279
70.7M
                     
(70.0M
!AcceptSizeless70.0M
&&
T->isSizelessBuiltinType()7.34M
));
9280
9281
  // Check that any necessary explicit specializations are visible. For an
9282
  // enum, we just need the declaration, so don't check this.
9283
70.7M
  if (Def && 
!isa<EnumDecl>(Def)31.9M
)
9284
20.9M
    checkSpecializationReachability(Loc, Def);
9285
9286
  // If we have a complete type, we're done.
9287
70.7M
  if (!Incomplete) {
9288
70.0M
    NamedDecl *Suggested = nullptr;
9289
70.0M
    if (Def &&
9290
70.0M
        
!hasReachableDefinition(Def, &Suggested, /*OnlyNeedComplete=*/true)31.2M
) {
9291
      // If the user is going to see an error here, recover by making the
9292
      // definition visible.
9293
328
      bool TreatAsComplete = Diagnoser && 
!isSFINAEContext()203
;
9294
328
      if (Diagnoser && 
Suggested203
)
9295
203
        diagnoseMissingImport(Loc, Suggested, MissingImportKind::Definition,
9296
203
                              /*Recover*/ TreatAsComplete);
9297
328
      return !TreatAsComplete;
9298
70.0M
    } else if (Def && 
!TemplateInstCallbacks.empty()31.2M
) {
9299
40
      CodeSynthesisContext TempInst;
9300
40
      TempInst.Kind = CodeSynthesisContext::Memoization;
9301
40
      TempInst.Template = Def;
9302
40
      TempInst.Entity = Def;
9303
40
      TempInst.PointOfInstantiation = Loc;
9304
40
      atTemplateBegin(TemplateInstCallbacks, *this, TempInst);
9305
40
      atTemplateEnd(TemplateInstCallbacks, *this, TempInst);
9306
40
    }
9307
9308
70.0M
    return false;
9309
70.0M
  }
9310
9311
660k
  TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def);
9312
660k
  ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def);
9313
9314
  // Give the external source a chance to provide a definition of the type.
9315
  // This is kept separate from completing the redeclaration chain so that
9316
  // external sources such as LLDB can avoid synthesizing a type definition
9317
  // unless it's actually needed.
9318
660k
  if (Tag || 
IFace29.9k
) {
9319
    // Avoid diagnosing invalid decls as incomplete.
9320
630k
    if (Def->isInvalidDecl())
9321
11
      return true;
9322
9323
    // Give the external AST source a chance to complete the type.
9324
630k
    if (auto *Source = Context.getExternalSource()) {
9325
47.6k
      if (Tag && 
Tag->hasExternalLexicalStorage()47.6k
)
9326
86
          Source->CompleteType(Tag);
9327
47.6k
      if (IFace && 
IFace->hasExternalLexicalStorage()35
)
9328
35
          Source->CompleteType(IFace);
9329
      // If the external source completed the type, go through the motions
9330
      // again to ensure we're allowed to use the completed type.
9331
47.6k
      if (!T->isIncompleteType())
9332
87
        return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9333
47.6k
    }
9334
630k
  }
9335
9336
  // If we have a class template specialization or a class member of a
9337
  // class template specialization, or an array with known size of such,
9338
  // try to instantiate it.
9339
660k
  if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) {
9340
630k
    bool Instantiated = false;
9341
630k
    bool Diagnosed = false;
9342
630k
    if (RD->isDependentContext()) {
9343
      // Don't try to instantiate a dependent class (eg, a member template of
9344
      // an instantiated class template specialization).
9345
      // FIXME: Can this ever happen?
9346
630k
    } else if (auto *ClassTemplateSpec =
9347
630k
            dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
9348
577k
      if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
9349
577k
        runWithSufficientStackSpace(Loc, [&] {
9350
577k
          Diagnosed = InstantiateClassTemplateSpecialization(
9351
577k
              Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
9352
577k
              /*Complain=*/Diagnoser);
9353
577k
        });
9354
577k
        Instantiated = true;
9355
577k
      }
9356
577k
    } else {
9357
52.6k
      CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass();
9358
52.6k
      if (!RD->isBeingDefined() && 
Pattern51.6k
) {
9359
14.7k
        MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo();
9360
14.7k
        assert(MSI && "Missing member specialization information?");
9361
        // This record was instantiated from a class within a template.
9362
14.7k
        if (MSI->getTemplateSpecializationKind() !=
9363
14.7k
            TSK_ExplicitSpecialization) {
9364
14.7k
          runWithSufficientStackSpace(Loc, [&] {
9365
14.7k
            Diagnosed = InstantiateClass(Loc, RD, Pattern,
9366
14.7k
                                         getTemplateInstantiationArgs(RD),
9367
14.7k
                                         TSK_ImplicitInstantiation,
9368
14.7k
                                         /*Complain=*/Diagnoser);
9369
14.7k
          });
9370
14.7k
          Instantiated = true;
9371
14.7k
        }
9372
14.7k
      }
9373
52.6k
    }
9374
9375
630k
    if (Instantiated) {
9376
      // Instantiate* might have already complained that the template is not
9377
      // defined, if we asked it to.
9378
592k
      if (Diagnoser && 
Diagnosed546k
)
9379
6.07k
        return true;
9380
      // If we instantiated a definition, check that it's usable, even if
9381
      // instantiation produced an error, so that repeated calls to this
9382
      // function give consistent answers.
9383
586k
      if (!T->isIncompleteType())
9384
546k
        return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9385
586k
    }
9386
630k
  }
9387
9388
  // FIXME: If we didn't instantiate a definition because of an explicit
9389
  // specialization declaration, check that it's visible.
9390
9391
107k
  if (!Diagnoser)
9392
100k
    return true;
9393
9394
7.08k
  Diagnoser->diagnose(*this, Loc, T);
9395
9396
  // If the type was a forward declaration of a class/struct/union
9397
  // type, produce a note.
9398
7.08k
  if (Tag && 
!Tag->isInvalidDecl()6.51k
&&
!Tag->getLocation().isInvalid()6.51k
)
9399
6.50k
    Diag(Tag->getLocation(),
9400
6.50k
         Tag->isBeingDefined() ? 
diag::note_type_being_defined58
9401
6.50k
                               : 
diag::note_forward_declaration6.44k
)
9402
6.50k
      << Context.getTagDeclType(Tag);
9403
9404
  // If the Objective-C class was a forward declaration, produce a note.
9405
7.08k
  if (IFace && 
!IFace->isInvalidDecl()126
&&
!IFace->getLocation().isInvalid()126
)
9406
120
    Diag(IFace->getLocation(), diag::note_forward_class);
9407
9408
  // If we have external information that we can use to suggest a fix,
9409
  // produce a note.
9410
7.08k
  if (ExternalSource)
9411
157
    ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
9412
9413
7.08k
  return true;
9414
107k
}
9415
9416
bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
9417
24.0M
                               CompleteTypeKind Kind, unsigned DiagID) {
9418
24.0M
  BoundTypeDiagnoser<> Diagnoser(DiagID);
9419
24.0M
  return RequireCompleteType(Loc, T, Kind, Diagnoser);
9420
24.0M
}
9421
9422
/// Get diagnostic %select index for tag kind for
9423
/// literal type diagnostic message.
9424
/// WARNING: Indexes apply to particular diagnostics only!
9425
///
9426
/// \returns diagnostic %select index.
9427
6
static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
9428
6
  switch (Tag) {
9429
5
  case TagTypeKind::Struct:
9430
5
    return 0;
9431
0
  case TagTypeKind::Interface:
9432
0
    return 1;
9433
1
  case TagTypeKind::Class:
9434
1
    return 2;
9435
0
  default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
9436
6
  }
9437
6
}
9438
9439
/// Ensure that the type T is a literal type.
9440
///
9441
/// This routine checks whether the type @p T is a literal type. If @p T is an
9442
/// incomplete type, an attempt is made to complete it. If @p T is a literal
9443
/// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
9444
/// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
9445
/// it the type @p T), along with notes explaining why the type is not a
9446
/// literal type, and returns true.
9447
///
9448
/// @param Loc  The location in the source that the non-literal type
9449
/// diagnostic should refer to.
9450
///
9451
/// @param T  The type that this routine is examining for literalness.
9452
///
9453
/// @param Diagnoser Emits a diagnostic if T is not a literal type.
9454
///
9455
/// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
9456
/// @c false otherwise.
9457
bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
9458
545k
                              TypeDiagnoser &Diagnoser) {
9459
545k
  assert(!T->isDependentType() && "type should not be dependent");
9460
9461
545k
  QualType ElemType = Context.getBaseElementType(T);
9462
545k
  if ((isCompleteType(Loc, ElemType) || 
ElemType->isVoidType()4.06k
) &&
9463
545k
      
T->isLiteralType(Context)545k
)
9464
545k
    return false;
9465
9466
122
  Diagnoser.diagnose(*this, Loc, T);
9467
9468
122
  if (T->isVariableArrayType())
9469
4
    return true;
9470
9471
118
  const RecordType *RT = ElemType->getAs<RecordType>();
9472
118
  if (!RT)
9473
9
    return true;
9474
9475
109
  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
9476
9477
  // A partially-defined class type can't be a literal type, because a literal
9478
  // class type must have a trivial destructor (which can't be checked until
9479
  // the class definition is complete).
9480
109
  if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
9481
4
    return true;
9482
9483
  // [expr.prim.lambda]p3:
9484
  //   This class type is [not] a literal type.
9485
105
  if (RD->isLambda() && 
!getLangOpts().CPlusPlus173
) {
9486
3
    Diag(RD->getLocation(), diag::note_non_literal_lambda);
9487
3
    return true;
9488
3
  }
9489
9490
  // If the class has virtual base classes, then it's not an aggregate, and
9491
  // cannot have any constexpr constructors or a trivial default constructor,
9492
  // so is non-literal. This is better to diagnose than the resulting absence
9493
  // of constexpr constructors.
9494
102
  if (RD->getNumVBases()) {
9495
6
    Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
9496
6
      << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
9497
6
    for (const auto &I : RD->vbases())
9498
6
      Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
9499
6
          << I.getSourceRange();
9500
96
  } else if (!RD->isAggregate() && 
!RD->hasConstexprNonCopyMoveConstructor()81
&&
9501
96
             
!RD->hasTrivialDefaultConstructor()67
) {
9502
67
    Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
9503
67
  } else 
if (29
RD->hasNonLiteralTypeFieldsOrBases()29
) {
9504
16
    for (const auto &I : RD->bases()) {
9505
8
      if (!I.getType()->isLiteralType(Context)) {
9506
5
        Diag(I.getBeginLoc(), diag::note_non_literal_base_class)
9507
5
            << RD << I.getType() << I.getSourceRange();
9508
5
        return true;
9509
5
      }
9510
8
    }
9511
11
    for (const auto *I : RD->fields()) {
9512
11
      if (!I->getType()->isLiteralType(Context) ||
9513
11
          
I->getType().isVolatileQualified()2
) {
9514
11
        Diag(I->getLocation(), diag::note_non_literal_field)
9515
11
          << RD << I << I->getType()
9516
11
          << I->getType().isVolatileQualified();
9517
11
        return true;
9518
11
      }
9519
11
    }
9520
13
  } else if (getLangOpts().CPlusPlus20 ? 
!RD->hasConstexprDestructor()5
9521
13
                                       : 
!RD->hasTrivialDestructor()8
) {
9522
    // All fields and bases are of literal types, so have trivial or constexpr
9523
    // destructors. If this class's destructor is non-trivial / non-constexpr,
9524
    // it must be user-declared.
9525
13
    CXXDestructorDecl *Dtor = RD->getDestructor();
9526
13
    assert(Dtor && "class has literal fields and bases but no dtor?");
9527
13
    if (!Dtor)
9528
0
      return true;
9529
9530
13
    if (getLangOpts().CPlusPlus20) {
9531
5
      Diag(Dtor->getLocation(), diag::note_non_literal_non_constexpr_dtor)
9532
5
          << RD;
9533
8
    } else {
9534
8
      Diag(Dtor->getLocation(), Dtor->isUserProvided()
9535
8
                                    ? 
diag::note_non_literal_user_provided_dtor6
9536
8
                                    : 
diag::note_non_literal_nontrivial_dtor2
)
9537
8
          << RD;
9538
8
      if (!Dtor->isUserProvided())
9539
2
        SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI,
9540
2
                               /*Diagnose*/ true);
9541
8
    }
9542
13
  }
9543
9544
86
  return true;
9545
102
}
9546
9547
370k
bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
9548
370k
  BoundTypeDiagnoser<> Diagnoser(DiagID);
9549
370k
  return RequireLiteralType(Loc, T, Diagnoser);
9550
370k
}
9551
9552
/// Retrieve a version of the type 'T' that is elaborated by Keyword, qualified
9553
/// by the nested-name-specifier contained in SS, and that is (re)declared by
9554
/// OwnedTagDecl, which is nullptr if this is not a (re)declaration.
9555
QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
9556
                                 const CXXScopeSpec &SS, QualType T,
9557
3.65M
                                 TagDecl *OwnedTagDecl) {
9558
3.65M
  if (T.isNull())
9559
0
    return T;
9560
3.65M
  return Context.getElaboratedType(
9561
3.65M
      Keyword, SS.isValid() ? 
SS.getScopeRep()271k
:
nullptr3.38M
, T, OwnedTagDecl);
9562
3.65M
}
9563
9564
3.58k
QualType Sema::BuildTypeofExprType(Expr *E, TypeOfKind Kind) {
9565
3.58k
  assert(!E->hasPlaceholderType() && "unexpected placeholder");
9566
9567
3.58k
  if (!getLangOpts().CPlusPlus && 
E->refersToBitField()803
)
9568
3
    Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
9569
3
        << (Kind == TypeOfKind::Unqualified ? 
31
:
22
);
9570
9571
3.58k
  if (!E->isTypeDependent()) {
9572
2.33k
    QualType T = E->getType();
9573
2.33k
    if (const TagType *TT = T->getAs<TagType>())
9574
43
      DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
9575
2.33k
  }
9576
3.58k
  return Context.getTypeOfExprType(E, Kind);
9577
3.58k
}
9578
9579
/// getDecltypeForExpr - Given an expr, will return the decltype for
9580
/// that expression, according to the rules in C++11
9581
/// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
9582
229k
QualType Sema::getDecltypeForExpr(Expr *E) {
9583
229k
  if (E->isTypeDependent())
9584
104k
    return Context.DependentTy;
9585
9586
124k
  Expr *IDExpr = E;
9587
124k
  if (auto *ImplCastExpr = dyn_cast<ImplicitCastExpr>(E))
9588
7
    IDExpr = ImplCastExpr->getSubExpr();
9589
9590
  // C++11 [dcl.type.simple]p4:
9591
  //   The type denoted by decltype(e) is defined as follows:
9592
9593
  // C++20:
9594
  //     - if E is an unparenthesized id-expression naming a non-type
9595
  //       template-parameter (13.2), decltype(E) is the type of the
9596
  //       template-parameter after performing any necessary type deduction
9597
  // Note that this does not pick up the implicit 'const' for a template
9598
  // parameter object. This rule makes no difference before C++20 so we apply
9599
  // it unconditionally.
9600
124k
  if (const auto *SNTTPE = dyn_cast<SubstNonTypeTemplateParmExpr>(IDExpr))
9601
113
    return SNTTPE->getParameterType(Context);
9602
9603
  //     - if e is an unparenthesized id-expression or an unparenthesized class
9604
  //       member access (5.2.5), decltype(e) is the type of the entity named
9605
  //       by e. If there is no such entity, or if e names a set of overloaded
9606
  //       functions, the program is ill-formed;
9607
  //
9608
  // We apply the same rules for Objective-C ivar and property references.
9609
124k
  if (const auto *DRE = dyn_cast<DeclRefExpr>(IDExpr)) {
9610
4.08k
    const ValueDecl *VD = DRE->getDecl();
9611
4.08k
    QualType T = VD->getType();
9612
4.08k
    return isa<TemplateParamObjectDecl>(VD) ? 
T.getUnqualifiedType()0
: T;
9613
4.08k
  }
9614
120k
  if (const auto *ME = dyn_cast<MemberExpr>(IDExpr)) {
9615
2.14k
    if (const auto *VD = ME->getMemberDecl())
9616
2.14k
      if (isa<FieldDecl>(VD) || 
isa<VarDecl>(VD)1
)
9617
2.14k
        return VD->getType();
9618
118k
  } else if (const auto *IR = dyn_cast<ObjCIvarRefExpr>(IDExpr)) {
9619
20
    return IR->getDecl()->getType();
9620
118k
  } else if (const auto *PR = dyn_cast<ObjCPropertyRefExpr>(IDExpr)) {
9621
0
    if (PR->isExplicitProperty())
9622
0
      return PR->getExplicitProperty()->getType();
9623
118k
  } else if (const auto *PE = dyn_cast<PredefinedExpr>(IDExpr)) {
9624
3
    return PE->getType();
9625
3
  }
9626
9627
  // C++11 [expr.lambda.prim]p18:
9628
  //   Every occurrence of decltype((x)) where x is a possibly
9629
  //   parenthesized id-expression that names an entity of automatic
9630
  //   storage duration is treated as if x were transformed into an
9631
  //   access to a corresponding data member of the closure type that
9632
  //   would have been declared if x were an odr-use of the denoted
9633
  //   entity.
9634
118k
  if (getCurLambda() && 
isa<ParenExpr>(IDExpr)288
) {
9635
90
    if (auto *DRE = dyn_cast<DeclRefExpr>(IDExpr->IgnoreParens())) {
9636
90
      if (auto *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
9637
90
        QualType T = getCapturedDeclRefType(Var, DRE->getLocation());
9638
90
        if (!T.isNull())
9639
77
          return Context.getLValueReferenceType(T);
9640
90
      }
9641
90
    }
9642
90
  }
9643
9644
118k
  return Context.getReferenceQualifiedType(E);
9645
118k
}
9646
9647
228k
QualType Sema::BuildDecltypeType(Expr *E, bool AsUnevaluated) {
9648
228k
  assert(!E->hasPlaceholderType() && "unexpected placeholder");
9649
9650
228k
  if (AsUnevaluated && 
CodeSynthesisContexts.empty()228k
&&
9651
228k
      
!E->isInstantiationDependent()65.9k
&&
E->HasSideEffects(Context, false)6.76k
) {
9652
    // The expression operand for decltype is in an unevaluated expression
9653
    // context, so side effects could result in unintended consequences.
9654
    // Exclude instantiation-dependent expressions, because 'decltype' is often
9655
    // used to build SFINAE gadgets.
9656
34
    Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
9657
34
  }
9658
228k
  return Context.getDecltypeType(E, getDecltypeForExpr(E));
9659
228k
}
9660
9661
static QualType GetEnumUnderlyingType(Sema &S, QualType BaseType,
9662
1.07k
                                      SourceLocation Loc) {
9663
1.07k
  assert(BaseType->isEnumeralType());
9664
1.07k
  EnumDecl *ED = BaseType->castAs<EnumType>()->getDecl();
9665
1.07k
  assert(ED && "EnumType has no EnumDecl");
9666
9667
1.07k
  S.DiagnoseUseOfDecl(ED, Loc);
9668
9669
1.07k
  QualType Underlying = ED->getIntegerType();
9670
1.07k
  assert(!Underlying.isNull());
9671
9672
1.07k
  return Underlying;
9673
1.07k
}
9674
9675
QualType Sema::BuiltinEnumUnderlyingType(QualType BaseType,
9676
682
                                         SourceLocation Loc) {
9677
682
  if (!BaseType->isEnumeralType()) {
9678
3
    Diag(Loc, diag::err_only_enums_have_underlying_types);
9679
3
    return QualType();
9680
3
  }
9681
9682
  // The enum could be incomplete if we're parsing its definition or
9683
  // recovering from an error.
9684
679
  NamedDecl *FwdDecl = nullptr;
9685
679
  if (BaseType->isIncompleteType(&FwdDecl)) {
9686
2
    Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
9687
2
    Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
9688
2
    return QualType();
9689
2
  }
9690
9691
677
  return GetEnumUnderlyingType(*this, BaseType, Loc);
9692
679
}
9693
9694
364
QualType Sema::BuiltinAddPointer(QualType BaseType, SourceLocation Loc) {
9695
364
  QualType Pointer = BaseType.isReferenceable() || 
BaseType->isVoidType()16
9696
364
                         ? BuildPointerType(BaseType.getNonReferenceType(), Loc,
9697
364
                                            DeclarationName())
9698
364
                         : 
BaseType0
;
9699
9700
364
  return Pointer.isNull() ? 
QualType()0
: Pointer;
9701
364
}
9702
9703
2.33k
QualType Sema::BuiltinRemovePointer(QualType BaseType, SourceLocation Loc) {
9704
  // We don't want block pointers or ObjectiveC's id type.
9705
2.33k
  if (!BaseType->isAnyPointerType() || 
BaseType->isObjCIdType()98
)
9706
2.23k
    return BaseType;
9707
9708
97
  return BaseType->getPointeeType();
9709
2.33k
}
9710
9711
42.2k
QualType Sema::BuiltinDecay(QualType BaseType, SourceLocation Loc) {
9712
42.2k
  QualType Underlying = BaseType.getNonReferenceType();
9713
42.2k
  if (Underlying->isArrayType())
9714
8
    return Context.getDecayedType(Underlying);
9715
9716
42.2k
  if (Underlying->isFunctionType())
9717
185
    return BuiltinAddPointer(BaseType, Loc);
9718
9719
42.0k
  SplitQualType Split = Underlying.getSplitUnqualifiedType();
9720
  // std::decay is supposed to produce 'std::remove_cv', but since 'restrict' is
9721
  // in the same group of qualifiers as 'const' and 'volatile', we're extending
9722
  // '__decay(T)' so that it removes all qualifiers.
9723
42.0k
  Split.Quals.removeCVRQualifiers();
9724
42.0k
  return Context.getQualifiedType(Split);
9725
42.2k
}
9726
9727
QualType Sema::BuiltinAddReference(QualType BaseType, UTTKind UKind,
9728
36.6k
                                   SourceLocation Loc) {
9729
36.6k
  assert(LangOpts.CPlusPlus);
9730
36.6k
  QualType Reference =
9731
36.6k
      BaseType.isReferenceable()
9732
36.6k
          ? BuildReferenceType(BaseType,
9733
36.3k
                               UKind == UnaryTransformType::AddLvalueReference,
9734
36.3k
                               Loc, DeclarationName())
9735
36.6k
          : 
BaseType293
;
9736
36.6k
  return Reference.isNull() ? 
QualType()0
: Reference;
9737
36.6k
}
9738
9739
QualType Sema::BuiltinRemoveExtent(QualType BaseType, UTTKind UKind,
9740
248
                                   SourceLocation Loc) {
9741
248
  if (UKind == UnaryTransformType::RemoveAllExtents)
9742
127
    return Context.getBaseElementType(BaseType);
9743
9744
121
  if (const auto *AT = Context.getAsArrayType(BaseType))
9745
68
    return AT->getElementType();
9746
9747
53
  return BaseType;
9748
121
}
9749
9750
QualType Sema::BuiltinRemoveReference(QualType BaseType, UTTKind UKind,
9751
119k
                                      SourceLocation Loc) {
9752
119k
  assert(LangOpts.CPlusPlus);
9753
119k
  QualType T = BaseType.getNonReferenceType();
9754
119k
  if (UKind == UTTKind::RemoveCVRef &&
9755
119k
      
(10.3k
T.isConstQualified()10.3k
||
T.isVolatileQualified()8.85k
)) {
9756
1.49k
    Qualifiers Quals;
9757
1.49k
    QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
9758
1.49k
    Quals.removeConst();
9759
1.49k
    Quals.removeVolatile();
9760
1.49k
    T = Context.getQualifiedType(Unqual, Quals);
9761
1.49k
  }
9762
119k
  return T;
9763
119k
}
9764
9765
QualType Sema::BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind,
9766
27.0k
                                          SourceLocation Loc) {
9767
27.0k
  if ((BaseType->isReferenceType() && 
UKind != UTTKind::RemoveRestrict80
) ||
9768
27.0k
      
BaseType->isFunctionType()26.9k
)
9769
76
    return BaseType;
9770
9771
26.9k
  Qualifiers Quals;
9772
26.9k
  QualType Unqual = Context.getUnqualifiedArrayType(BaseType, Quals);
9773
9774
26.9k
  if (UKind == UTTKind::RemoveConst || 
UKind == UTTKind::RemoveCV23.3k
)
9775
26.7k
    Quals.removeConst();
9776
26.9k
  if (UKind == UTTKind::RemoveVolatile || 
UKind == UTTKind::RemoveCV26.8k
)
9777
23.2k
    Quals.removeVolatile();
9778
26.9k
  if (UKind == UTTKind::RemoveRestrict)
9779
87
    Quals.removeRestrict();
9780
9781
26.9k
  return Context.getQualifiedType(Unqual, Quals);
9782
27.0k
}
9783
9784
static QualType ChangeIntegralSignedness(Sema &S, QualType BaseType,
9785
                                         bool IsMakeSigned,
9786
496
                                         SourceLocation Loc) {
9787
496
  if (BaseType->isEnumeralType()) {
9788
400
    QualType Underlying = GetEnumUnderlyingType(S, BaseType, Loc);
9789
400
    if (auto *BitInt = dyn_cast<BitIntType>(Underlying)) {
9790
0
      unsigned int Bits = BitInt->getNumBits();
9791
0
      if (Bits > 1)
9792
0
        return S.Context.getBitIntType(!IsMakeSigned, Bits);
9793
9794
0
      S.Diag(Loc, diag::err_make_signed_integral_only)
9795
0
          << IsMakeSigned << /*_BitInt(1)*/ true << BaseType << 1 << Underlying;
9796
0
      return QualType();
9797
0
    }
9798
400
    if (Underlying->isBooleanType()) {
9799
16
      S.Diag(Loc, diag::err_make_signed_integral_only)
9800
16
          << IsMakeSigned << /*_BitInt(1)*/ false << BaseType << 1
9801
16
          << Underlying;
9802
16
      return QualType();
9803
16
    }
9804
400
  }
9805
9806
480
  bool Int128Unsupported = !S.Context.getTargetInfo().hasInt128Type();
9807
480
  std::array<CanQualType *, 6> AllSignedIntegers = {
9808
480
      &S.Context.SignedCharTy, &S.Context.ShortTy,    &S.Context.IntTy,
9809
480
      &S.Context.LongTy,       &S.Context.LongLongTy, &S.Context.Int128Ty};
9810
480
  ArrayRef<CanQualType *> AvailableSignedIntegers(
9811
480
      AllSignedIntegers.data(), AllSignedIntegers.size() - Int128Unsupported);
9812
480
  std::array<CanQualType *, 6> AllUnsignedIntegers = {
9813
480
      &S.Context.UnsignedCharTy,     &S.Context.UnsignedShortTy,
9814
480
      &S.Context.UnsignedIntTy,      &S.Context.UnsignedLongTy,
9815
480
      &S.Context.UnsignedLongLongTy, &S.Context.UnsignedInt128Ty};
9816
480
  ArrayRef<CanQualType *> AvailableUnsignedIntegers(AllUnsignedIntegers.data(),
9817
480
                                                    AllUnsignedIntegers.size() -
9818
480
                                                        Int128Unsupported);
9819
480
  ArrayRef<CanQualType *> *Consider =
9820
480
      IsMakeSigned ? 
&AvailableSignedIntegers240
:
&AvailableUnsignedIntegers240
;
9821
9822
480
  uint64_t BaseSize = S.Context.getTypeSize(BaseType);
9823
480
  auto *Result =
9824
1.66k
      llvm::find_if(*Consider, [&S, BaseSize](const CanQual<Type> *T) {
9825
1.66k
        return BaseSize == S.Context.getTypeSize(T->getTypePtr());
9826
1.66k
      });
9827
9828
480
  assert(Result != Consider->end());
9829
480
  return QualType((*Result)->getTypePtr(), 0);
9830
480
}
9831
9832
QualType Sema::BuiltinChangeSignedness(QualType BaseType, UTTKind UKind,
9833
1.53k
                                       SourceLocation Loc) {
9834
1.53k
  bool IsMakeSigned = UKind == UnaryTransformType::MakeSigned;
9835
1.53k
  if ((!BaseType->isIntegerType() && 
!BaseType->isEnumeralType()368
) ||
9836
1.53k
      
BaseType->isBooleanType()1.43k
||
9837
1.53k
      
(1.42k
BaseType->isBitIntType()1.42k
&&
9838
1.42k
       
BaseType->getAs<BitIntType>()->getNumBits() < 272
)) {
9839
120
    Diag(Loc, diag::err_make_signed_integral_only)
9840
120
        << IsMakeSigned << BaseType->isBitIntType() << BaseType << 0;
9841
120
    return QualType();
9842
120
  }
9843
9844
1.41k
  bool IsNonIntIntegral =
9845
1.41k
      BaseType->isChar16Type() || 
BaseType->isChar32Type()1.38k
||
9846
1.41k
      
BaseType->isWideCharType()1.35k
||
BaseType->isEnumeralType()1.32k
;
9847
9848
1.41k
  QualType Underlying =
9849
1.41k
      IsNonIntIntegral
9850
1.41k
          ? 
ChangeIntegralSignedness(*this, BaseType, IsMakeSigned, Loc)496
9851
1.41k
      : 
IsMakeSigned923
?
Context.getCorrespondingSignedType(BaseType)247
9852
923
                     : 
Context.getCorrespondingUnsignedType(BaseType)676
;
9853
1.41k
  if (Underlying.isNull())
9854
16
    return Underlying;
9855
1.40k
  return Context.getQualifiedType(Underlying, BaseType.getQualifiers());
9856
1.41k
}
9857
9858
QualType Sema::BuildUnaryTransformType(QualType BaseType, UTTKind UKind,
9859
396k
                                       SourceLocation Loc) {
9860
396k
  if (BaseType->isDependentType())
9861
166k
    return Context.getUnaryTransformType(BaseType, BaseType, UKind);
9862
230k
  QualType Result;
9863
230k
  switch (UKind) {
9864
682
  case UnaryTransformType::EnumUnderlyingType: {
9865
682
    Result = BuiltinEnumUnderlyingType(BaseType, Loc);
9866
682
    break;
9867
0
  }
9868
179
  case UnaryTransformType::AddPointer: {
9869
179
    Result = BuiltinAddPointer(BaseType, Loc);
9870
179
    break;
9871
0
  }
9872
2.33k
  case UnaryTransformType::RemovePointer: {
9873
2.33k
    Result = BuiltinRemovePointer(BaseType, Loc);
9874
2.33k
    break;
9875
0
  }
9876
42.2k
  case UnaryTransformType::Decay: {
9877
42.2k
    Result = BuiltinDecay(BaseType, Loc);
9878
42.2k
    break;
9879
0
  }
9880
25.1k
  case UnaryTransformType::AddLvalueReference:
9881
36.6k
  case UnaryTransformType::AddRvalueReference: {
9882
36.6k
    Result = BuiltinAddReference(BaseType, UKind, Loc);
9883
36.6k
    break;
9884
25.1k
  }
9885
127
  case UnaryTransformType::RemoveAllExtents:
9886
248
  case UnaryTransformType::RemoveExtent: {
9887
248
    Result = BuiltinRemoveExtent(BaseType, UKind, Loc);
9888
248
    break;
9889
127
  }
9890
10.2k
  case UnaryTransformType::RemoveCVRef:
9891
119k
  case UnaryTransformType::RemoveReference: {
9892
119k
    Result = BuiltinRemoveReference(BaseType, UKind, Loc);
9893
119k
    break;
9894
10.2k
  }
9895
3.62k
  case UnaryTransformType::RemoveConst:
9896
26.8k
  case UnaryTransformType::RemoveCV:
9897
26.9k
  case UnaryTransformType::RemoveRestrict:
9898
27.0k
  case UnaryTransformType::RemoveVolatile: {
9899
27.0k
    Result = BuiltinChangeCVRQualifiers(BaseType, UKind, Loc);
9900
27.0k
    break;
9901
26.9k
  }
9902
555
  case UnaryTransformType::MakeSigned:
9903
1.53k
  case UnaryTransformType::MakeUnsigned: {
9904
1.53k
    Result = BuiltinChangeSignedness(BaseType, UKind, Loc);
9905
1.53k
    break;
9906
555
  }
9907
230k
  }
9908
9909
230k
  return !Result.isNull()
9910
230k
             ? 
Context.getUnaryTransformType(BaseType, Result, UKind)230k
9911
230k
             : 
Result141
;
9912
230k
}
9913
9914
3.98k
QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
9915
3.98k
  if (!isDependentOrGNUAutoType(T)) {
9916
    // FIXME: It isn't entirely clear whether incomplete atomic types
9917
    // are allowed or not; for simplicity, ban them for the moment.
9918
3.49k
    if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
9919
1
      return QualType();
9920
9921
3.49k
    int DisallowedKind = -1;
9922
3.49k
    if (T->isArrayType())
9923
7
      DisallowedKind = 1;
9924
3.48k
    else if (T->isFunctionType())
9925
3
      DisallowedKind = 2;
9926
3.48k
    else if (T->isReferenceType())
9927
2
      DisallowedKind = 3;
9928
3.48k
    else if (T->isAtomicType())
9929
3
      DisallowedKind = 4;
9930
3.47k
    else if (T.hasQualifiers())
9931
3
      DisallowedKind = 5;
9932
3.47k
    else if (T->isSizelessType())
9933
7
      DisallowedKind = 6;
9934
3.46k
    else if (!T.isTriviallyCopyableType(Context) && 
getLangOpts().CPlusPlus5
)
9935
      // Some other non-trivially-copyable type (probably a C++ class)
9936
2
      DisallowedKind = 7;
9937
3.46k
    else if (T->isBitIntType())
9938
3
      DisallowedKind = 8;
9939
3.46k
    else if (getLangOpts().C23 && 
T->isUndeducedAutoType()171
)
9940
      // _Atomic auto is prohibited in C23
9941
3
      DisallowedKind = 9;
9942
9943
3.49k
    if (DisallowedKind != -1) {
9944
33
      Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
9945
33
      return QualType();
9946
33
    }
9947
9948
    // FIXME: Do we need any handling for ARC here?
9949
3.49k
  }
9950
9951
  // Build the pointer type.
9952
3.94k
  return Context.getAtomicType(T);
9953
3.98k
}