Coverage Report

Created: 2020-02-18 08:44

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