Coverage Report

Created: 2020-11-24 06:42

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