1 //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements type-related semantic analysis.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/ASTStructuralEquivalence.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/TypeLoc.h"
23 #include "clang/AST/TypeLocVisitor.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Lex/Preprocessor.h"
27 #include "clang/Sema/DeclSpec.h"
28 #include "clang/Sema/DelayedDiagnostic.h"
29 #include "clang/Sema/Lookup.h"
30 #include "clang/Sema/ParsedTemplate.h"
31 #include "clang/Sema/ScopeInfo.h"
32 #include "clang/Sema/SemaInternal.h"
33 #include "clang/Sema/Template.h"
34 #include "clang/Sema/TemplateInstCallback.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallString.h"
37 #include "llvm/ADT/StringSwitch.h"
38 #include "llvm/IR/DerivedTypes.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include <bitset>
41 
42 using namespace clang;
43 
44 enum TypeDiagSelector {
45   TDS_Function,
46   TDS_Pointer,
47   TDS_ObjCObjOrBlock
48 };
49 
50 /// isOmittedBlockReturnType - Return true if this declarator is missing a
51 /// return type because this is a omitted return type on a block literal.
isOmittedBlockReturnType(const Declarator & D)52 static bool isOmittedBlockReturnType(const Declarator &D) {
53   if (D.getContext() != DeclaratorContext::BlockLiteral ||
54       D.getDeclSpec().hasTypeSpecifier())
55     return false;
56 
57   if (D.getNumTypeObjects() == 0)
58     return true;   // ^{ ... }
59 
60   if (D.getNumTypeObjects() == 1 &&
61       D.getTypeObject(0).Kind == DeclaratorChunk::Function)
62     return true;   // ^(int X, float Y) { ... }
63 
64   return false;
65 }
66 
67 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
68 /// doesn't apply to the given type.
diagnoseBadTypeAttribute(Sema & S,const ParsedAttr & attr,QualType type)69 static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr,
70                                      QualType type) {
71   TypeDiagSelector WhichType;
72   bool useExpansionLoc = true;
73   switch (attr.getKind()) {
74   case ParsedAttr::AT_ObjCGC:
75     WhichType = TDS_Pointer;
76     break;
77   case ParsedAttr::AT_ObjCOwnership:
78     WhichType = TDS_ObjCObjOrBlock;
79     break;
80   default:
81     // Assume everything else was a function attribute.
82     WhichType = TDS_Function;
83     useExpansionLoc = false;
84     break;
85   }
86 
87   SourceLocation loc = attr.getLoc();
88   StringRef name = attr.getAttrName()->getName();
89 
90   // The GC attributes are usually written with macros;  special-case them.
91   IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
92                                           : nullptr;
93   if (useExpansionLoc && loc.isMacroID() && II) {
94     if (II->isStr("strong")) {
95       if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
96     } else if (II->isStr("weak")) {
97       if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
98     }
99   }
100 
101   S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
102     << type;
103 }
104 
105 // objc_gc applies to Objective-C pointers or, otherwise, to the
106 // smallest available pointer type (i.e. 'void*' in 'void**').
107 #define OBJC_POINTER_TYPE_ATTRS_CASELIST                                       \
108   case ParsedAttr::AT_ObjCGC:                                                  \
109   case ParsedAttr::AT_ObjCOwnership
110 
111 // Calling convention attributes.
112 #define CALLING_CONV_ATTRS_CASELIST                                            \
113   case ParsedAttr::AT_CDecl:                                                   \
114   case ParsedAttr::AT_FastCall:                                                \
115   case ParsedAttr::AT_StdCall:                                                 \
116   case ParsedAttr::AT_ThisCall:                                                \
117   case ParsedAttr::AT_RegCall:                                                 \
118   case ParsedAttr::AT_Pascal:                                                  \
119   case ParsedAttr::AT_SwiftCall:                                               \
120   case ParsedAttr::AT_SwiftAsyncCall:                                          \
121   case ParsedAttr::AT_VectorCall:                                              \
122   case ParsedAttr::AT_AArch64VectorPcs:                                        \
123   case ParsedAttr::AT_MSABI:                                                   \
124   case ParsedAttr::AT_SysVABI:                                                 \
125   case ParsedAttr::AT_Pcs:                                                     \
126   case ParsedAttr::AT_IntelOclBicc:                                            \
127   case ParsedAttr::AT_PreserveMost:                                            \
128   case ParsedAttr::AT_PreserveAll
129 
130 // Function type attributes.
131 #define FUNCTION_TYPE_ATTRS_CASELIST                                           \
132   case ParsedAttr::AT_NSReturnsRetained:                                       \
133   case ParsedAttr::AT_NoReturn:                                                \
134   case ParsedAttr::AT_Regparm:                                                 \
135   case ParsedAttr::AT_CmseNSCall:                                              \
136   case ParsedAttr::AT_AnyX86NoCallerSavedRegisters:                            \
137   case ParsedAttr::AT_AnyX86NoCfCheck:                                         \
138     CALLING_CONV_ATTRS_CASELIST
139 
140 // Microsoft-specific type qualifiers.
141 #define MS_TYPE_ATTRS_CASELIST                                                 \
142   case ParsedAttr::AT_Ptr32:                                                   \
143   case ParsedAttr::AT_Ptr64:                                                   \
144   case ParsedAttr::AT_SPtr:                                                    \
145   case ParsedAttr::AT_UPtr
146 
147 // Nullability qualifiers.
148 #define NULLABILITY_TYPE_ATTRS_CASELIST                                        \
149   case ParsedAttr::AT_TypeNonNull:                                             \
150   case ParsedAttr::AT_TypeNullable:                                            \
151   case ParsedAttr::AT_TypeNullableResult:                                      \
152   case ParsedAttr::AT_TypeNullUnspecified
153 
154 namespace {
155   /// An object which stores processing state for the entire
156   /// GetTypeForDeclarator process.
157   class TypeProcessingState {
158     Sema &sema;
159 
160     /// The declarator being processed.
161     Declarator &declarator;
162 
163     /// The index of the declarator chunk we're currently processing.
164     /// May be the total number of valid chunks, indicating the
165     /// DeclSpec.
166     unsigned chunkIndex;
167 
168     /// Whether there are non-trivial modifications to the decl spec.
169     bool trivial;
170 
171     /// Whether we saved the attributes in the decl spec.
172     bool hasSavedAttrs;
173 
174     /// The original set of attributes on the DeclSpec.
175     SmallVector<ParsedAttr *, 2> savedAttrs;
176 
177     /// A list of attributes to diagnose the uselessness of when the
178     /// processing is complete.
179     SmallVector<ParsedAttr *, 2> ignoredTypeAttrs;
180 
181     /// Attributes corresponding to AttributedTypeLocs that we have not yet
182     /// populated.
183     // FIXME: The two-phase mechanism by which we construct Types and fill
184     // their TypeLocs makes it hard to correctly assign these. We keep the
185     // attributes in creation order as an attempt to make them line up
186     // properly.
187     using TypeAttrPair = std::pair<const AttributedType*, const Attr*>;
188     SmallVector<TypeAttrPair, 8> AttrsForTypes;
189     bool AttrsForTypesSorted = true;
190 
191     /// MacroQualifiedTypes mapping to macro expansion locations that will be
192     /// stored in a MacroQualifiedTypeLoc.
193     llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros;
194 
195     /// Flag to indicate we parsed a noderef attribute. This is used for
196     /// validating that noderef was used on a pointer or array.
197     bool parsedNoDeref;
198 
199   public:
TypeProcessingState(Sema & sema,Declarator & declarator)200     TypeProcessingState(Sema &sema, Declarator &declarator)
201         : sema(sema), declarator(declarator),
202           chunkIndex(declarator.getNumTypeObjects()), trivial(true),
203           hasSavedAttrs(false), parsedNoDeref(false) {}
204 
getSema() const205     Sema &getSema() const {
206       return sema;
207     }
208 
getDeclarator() const209     Declarator &getDeclarator() const {
210       return declarator;
211     }
212 
isProcessingDeclSpec() const213     bool isProcessingDeclSpec() const {
214       return chunkIndex == declarator.getNumTypeObjects();
215     }
216 
getCurrentChunkIndex() const217     unsigned getCurrentChunkIndex() const {
218       return chunkIndex;
219     }
220 
setCurrentChunkIndex(unsigned idx)221     void setCurrentChunkIndex(unsigned idx) {
222       assert(idx <= declarator.getNumTypeObjects());
223       chunkIndex = idx;
224     }
225 
getCurrentAttributes() const226     ParsedAttributesView &getCurrentAttributes() const {
227       if (isProcessingDeclSpec())
228         return getMutableDeclSpec().getAttributes();
229       return declarator.getTypeObject(chunkIndex).getAttrs();
230     }
231 
232     /// Save the current set of attributes on the DeclSpec.
saveDeclSpecAttrs()233     void saveDeclSpecAttrs() {
234       // Don't try to save them multiple times.
235       if (hasSavedAttrs) return;
236 
237       DeclSpec &spec = getMutableDeclSpec();
238       for (ParsedAttr &AL : spec.getAttributes())
239         savedAttrs.push_back(&AL);
240       trivial &= savedAttrs.empty();
241       hasSavedAttrs = true;
242     }
243 
244     /// Record that we had nowhere to put the given type attribute.
245     /// We will diagnose such attributes later.
addIgnoredTypeAttr(ParsedAttr & attr)246     void addIgnoredTypeAttr(ParsedAttr &attr) {
247       ignoredTypeAttrs.push_back(&attr);
248     }
249 
250     /// Diagnose all the ignored type attributes, given that the
251     /// declarator worked out to the given type.
diagnoseIgnoredTypeAttrs(QualType type) const252     void diagnoseIgnoredTypeAttrs(QualType type) const {
253       for (auto *Attr : ignoredTypeAttrs)
254         diagnoseBadTypeAttribute(getSema(), *Attr, type);
255     }
256 
257     /// Get an attributed type for the given attribute, and remember the Attr
258     /// object so that we can attach it to the AttributedTypeLoc.
getAttributedType(Attr * A,QualType ModifiedType,QualType EquivType)259     QualType getAttributedType(Attr *A, QualType ModifiedType,
260                                QualType EquivType) {
261       QualType T =
262           sema.Context.getAttributedType(A->getKind(), ModifiedType, EquivType);
263       AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A});
264       AttrsForTypesSorted = false;
265       return T;
266     }
267 
268     /// Completely replace the \c auto in \p TypeWithAuto by
269     /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if
270     /// necessary.
ReplaceAutoType(QualType TypeWithAuto,QualType Replacement)271     QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) {
272       QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement);
273       if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) {
274         // Attributed type still should be an attributed type after replacement.
275         auto *NewAttrTy = cast<AttributedType>(T.getTypePtr());
276         for (TypeAttrPair &A : AttrsForTypes) {
277           if (A.first == AttrTy)
278             A.first = NewAttrTy;
279         }
280         AttrsForTypesSorted = false;
281       }
282       return T;
283     }
284 
285     /// Extract and remove the Attr* for a given attributed type.
takeAttrForAttributedType(const AttributedType * AT)286     const Attr *takeAttrForAttributedType(const AttributedType *AT) {
287       if (!AttrsForTypesSorted) {
288         llvm::stable_sort(AttrsForTypes, llvm::less_first());
289         AttrsForTypesSorted = true;
290       }
291 
292       // FIXME: This is quadratic if we have lots of reuses of the same
293       // attributed type.
294       for (auto It = std::partition_point(
295                AttrsForTypes.begin(), AttrsForTypes.end(),
296                [=](const TypeAttrPair &A) { return A.first < AT; });
297            It != AttrsForTypes.end() && It->first == AT; ++It) {
298         if (It->second) {
299           const Attr *Result = It->second;
300           It->second = nullptr;
301           return Result;
302         }
303       }
304 
305       llvm_unreachable("no Attr* for AttributedType*");
306     }
307 
308     SourceLocation
getExpansionLocForMacroQualifiedType(const MacroQualifiedType * MQT) const309     getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const {
310       auto FoundLoc = LocsForMacros.find(MQT);
311       assert(FoundLoc != LocsForMacros.end() &&
312              "Unable to find macro expansion location for MacroQualifedType");
313       return FoundLoc->second;
314     }
315 
setExpansionLocForMacroQualifiedType(const MacroQualifiedType * MQT,SourceLocation Loc)316     void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT,
317                                               SourceLocation Loc) {
318       LocsForMacros[MQT] = Loc;
319     }
320 
setParsedNoDeref(bool parsed)321     void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; }
322 
didParseNoDeref() const323     bool didParseNoDeref() const { return parsedNoDeref; }
324 
~TypeProcessingState()325     ~TypeProcessingState() {
326       if (trivial) return;
327 
328       restoreDeclSpecAttrs();
329     }
330 
331   private:
getMutableDeclSpec() const332     DeclSpec &getMutableDeclSpec() const {
333       return const_cast<DeclSpec&>(declarator.getDeclSpec());
334     }
335 
restoreDeclSpecAttrs()336     void restoreDeclSpecAttrs() {
337       assert(hasSavedAttrs);
338 
339       getMutableDeclSpec().getAttributes().clearListOnly();
340       for (ParsedAttr *AL : savedAttrs)
341         getMutableDeclSpec().getAttributes().addAtEnd(AL);
342     }
343   };
344 } // end anonymous namespace
345 
moveAttrFromListToList(ParsedAttr & attr,ParsedAttributesView & fromList,ParsedAttributesView & toList)346 static void moveAttrFromListToList(ParsedAttr &attr,
347                                    ParsedAttributesView &fromList,
348                                    ParsedAttributesView &toList) {
349   fromList.remove(&attr);
350   toList.addAtEnd(&attr);
351 }
352 
353 /// The location of a type attribute.
354 enum TypeAttrLocation {
355   /// The attribute is in the decl-specifier-seq.
356   TAL_DeclSpec,
357   /// The attribute is part of a DeclaratorChunk.
358   TAL_DeclChunk,
359   /// The attribute is immediately after the declaration's name.
360   TAL_DeclName
361 };
362 
363 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
364                              TypeAttrLocation TAL, ParsedAttributesView &attrs);
365 
366 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
367                                    QualType &type);
368 
369 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
370                                              ParsedAttr &attr, QualType &type);
371 
372 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
373                                  QualType &type);
374 
375 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
376                                         ParsedAttr &attr, QualType &type);
377 
handleObjCPointerTypeAttr(TypeProcessingState & state,ParsedAttr & attr,QualType & type)378 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
379                                       ParsedAttr &attr, QualType &type) {
380   if (attr.getKind() == ParsedAttr::AT_ObjCGC)
381     return handleObjCGCTypeAttr(state, attr, type);
382   assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership);
383   return handleObjCOwnershipTypeAttr(state, attr, type);
384 }
385 
386 /// Given the index of a declarator chunk, check whether that chunk
387 /// directly specifies the return type of a function and, if so, find
388 /// an appropriate place for it.
389 ///
390 /// \param i - a notional index which the search will start
391 ///   immediately inside
392 ///
393 /// \param onlyBlockPointers Whether we should only look into block
394 /// pointer types (vs. all pointer types).
maybeMovePastReturnType(Declarator & declarator,unsigned i,bool onlyBlockPointers)395 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
396                                                 unsigned i,
397                                                 bool onlyBlockPointers) {
398   assert(i <= declarator.getNumTypeObjects());
399 
400   DeclaratorChunk *result = nullptr;
401 
402   // First, look inwards past parens for a function declarator.
403   for (; i != 0; --i) {
404     DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
405     switch (fnChunk.Kind) {
406     case DeclaratorChunk::Paren:
407       continue;
408 
409     // If we find anything except a function, bail out.
410     case DeclaratorChunk::Pointer:
411     case DeclaratorChunk::BlockPointer:
412     case DeclaratorChunk::Array:
413     case DeclaratorChunk::Reference:
414     case DeclaratorChunk::MemberPointer:
415     case DeclaratorChunk::Pipe:
416       return result;
417 
418     // If we do find a function declarator, scan inwards from that,
419     // looking for a (block-)pointer declarator.
420     case DeclaratorChunk::Function:
421       for (--i; i != 0; --i) {
422         DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
423         switch (ptrChunk.Kind) {
424         case DeclaratorChunk::Paren:
425         case DeclaratorChunk::Array:
426         case DeclaratorChunk::Function:
427         case DeclaratorChunk::Reference:
428         case DeclaratorChunk::Pipe:
429           continue;
430 
431         case DeclaratorChunk::MemberPointer:
432         case DeclaratorChunk::Pointer:
433           if (onlyBlockPointers)
434             continue;
435 
436           LLVM_FALLTHROUGH;
437 
438         case DeclaratorChunk::BlockPointer:
439           result = &ptrChunk;
440           goto continue_outer;
441         }
442         llvm_unreachable("bad declarator chunk kind");
443       }
444 
445       // If we run out of declarators doing that, we're done.
446       return result;
447     }
448     llvm_unreachable("bad declarator chunk kind");
449 
450     // Okay, reconsider from our new point.
451   continue_outer: ;
452   }
453 
454   // Ran out of chunks, bail out.
455   return result;
456 }
457 
458 /// Given that an objc_gc attribute was written somewhere on a
459 /// declaration *other* than on the declarator itself (for which, use
460 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
461 /// didn't apply in whatever position it was written in, try to move
462 /// it to a more appropriate position.
distributeObjCPointerTypeAttr(TypeProcessingState & state,ParsedAttr & attr,QualType type)463 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
464                                           ParsedAttr &attr, QualType type) {
465   Declarator &declarator = state.getDeclarator();
466 
467   // Move it to the outermost normal or block pointer declarator.
468   for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
469     DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
470     switch (chunk.Kind) {
471     case DeclaratorChunk::Pointer:
472     case DeclaratorChunk::BlockPointer: {
473       // But don't move an ARC ownership attribute to the return type
474       // of a block.
475       DeclaratorChunk *destChunk = nullptr;
476       if (state.isProcessingDeclSpec() &&
477           attr.getKind() == ParsedAttr::AT_ObjCOwnership)
478         destChunk = maybeMovePastReturnType(declarator, i - 1,
479                                             /*onlyBlockPointers=*/true);
480       if (!destChunk) destChunk = &chunk;
481 
482       moveAttrFromListToList(attr, state.getCurrentAttributes(),
483                              destChunk->getAttrs());
484       return;
485     }
486 
487     case DeclaratorChunk::Paren:
488     case DeclaratorChunk::Array:
489       continue;
490 
491     // We may be starting at the return type of a block.
492     case DeclaratorChunk::Function:
493       if (state.isProcessingDeclSpec() &&
494           attr.getKind() == ParsedAttr::AT_ObjCOwnership) {
495         if (DeclaratorChunk *dest = maybeMovePastReturnType(
496                                       declarator, i,
497                                       /*onlyBlockPointers=*/true)) {
498           moveAttrFromListToList(attr, state.getCurrentAttributes(),
499                                  dest->getAttrs());
500           return;
501         }
502       }
503       goto error;
504 
505     // Don't walk through these.
506     case DeclaratorChunk::Reference:
507     case DeclaratorChunk::MemberPointer:
508     case DeclaratorChunk::Pipe:
509       goto error;
510     }
511   }
512  error:
513 
514   diagnoseBadTypeAttribute(state.getSema(), attr, type);
515 }
516 
517 /// Distribute an objc_gc type attribute that was written on the
518 /// declarator.
distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState & state,ParsedAttr & attr,QualType & declSpecType)519 static void distributeObjCPointerTypeAttrFromDeclarator(
520     TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) {
521   Declarator &declarator = state.getDeclarator();
522 
523   // objc_gc goes on the innermost pointer to something that's not a
524   // pointer.
525   unsigned innermost = -1U;
526   bool considerDeclSpec = true;
527   for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
528     DeclaratorChunk &chunk = declarator.getTypeObject(i);
529     switch (chunk.Kind) {
530     case DeclaratorChunk::Pointer:
531     case DeclaratorChunk::BlockPointer:
532       innermost = i;
533       continue;
534 
535     case DeclaratorChunk::Reference:
536     case DeclaratorChunk::MemberPointer:
537     case DeclaratorChunk::Paren:
538     case DeclaratorChunk::Array:
539     case DeclaratorChunk::Pipe:
540       continue;
541 
542     case DeclaratorChunk::Function:
543       considerDeclSpec = false;
544       goto done;
545     }
546   }
547  done:
548 
549   // That might actually be the decl spec if we weren't blocked by
550   // anything in the declarator.
551   if (considerDeclSpec) {
552     if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
553       // Splice the attribute into the decl spec.  Prevents the
554       // attribute from being applied multiple times and gives
555       // the source-location-filler something to work with.
556       state.saveDeclSpecAttrs();
557       declarator.getMutableDeclSpec().getAttributes().takeOneFrom(
558           declarator.getAttributes(), &attr);
559       return;
560     }
561   }
562 
563   // Otherwise, if we found an appropriate chunk, splice the attribute
564   // into it.
565   if (innermost != -1U) {
566     moveAttrFromListToList(attr, declarator.getAttributes(),
567                            declarator.getTypeObject(innermost).getAttrs());
568     return;
569   }
570 
571   // Otherwise, diagnose when we're done building the type.
572   declarator.getAttributes().remove(&attr);
573   state.addIgnoredTypeAttr(attr);
574 }
575 
576 /// A function type attribute was written somewhere in a declaration
577 /// *other* than on the declarator itself or in the decl spec.  Given
578 /// that it didn't apply in whatever position it was written in, try
579 /// to move it to a more appropriate position.
distributeFunctionTypeAttr(TypeProcessingState & state,ParsedAttr & attr,QualType type)580 static void distributeFunctionTypeAttr(TypeProcessingState &state,
581                                        ParsedAttr &attr, QualType type) {
582   Declarator &declarator = state.getDeclarator();
583 
584   // Try to push the attribute from the return type of a function to
585   // the function itself.
586   for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
587     DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
588     switch (chunk.Kind) {
589     case DeclaratorChunk::Function:
590       moveAttrFromListToList(attr, state.getCurrentAttributes(),
591                              chunk.getAttrs());
592       return;
593 
594     case DeclaratorChunk::Paren:
595     case DeclaratorChunk::Pointer:
596     case DeclaratorChunk::BlockPointer:
597     case DeclaratorChunk::Array:
598     case DeclaratorChunk::Reference:
599     case DeclaratorChunk::MemberPointer:
600     case DeclaratorChunk::Pipe:
601       continue;
602     }
603   }
604 
605   diagnoseBadTypeAttribute(state.getSema(), attr, type);
606 }
607 
608 /// Try to distribute a function type attribute to the innermost
609 /// function chunk or type.  Returns true if the attribute was
610 /// distributed, false if no location was found.
distributeFunctionTypeAttrToInnermost(TypeProcessingState & state,ParsedAttr & attr,ParsedAttributesView & attrList,QualType & declSpecType)611 static bool distributeFunctionTypeAttrToInnermost(
612     TypeProcessingState &state, ParsedAttr &attr,
613     ParsedAttributesView &attrList, QualType &declSpecType) {
614   Declarator &declarator = state.getDeclarator();
615 
616   // Put it on the innermost function chunk, if there is one.
617   for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
618     DeclaratorChunk &chunk = declarator.getTypeObject(i);
619     if (chunk.Kind != DeclaratorChunk::Function) continue;
620 
621     moveAttrFromListToList(attr, attrList, chunk.getAttrs());
622     return true;
623   }
624 
625   return handleFunctionTypeAttr(state, attr, declSpecType);
626 }
627 
628 /// A function type attribute was written in the decl spec.  Try to
629 /// apply it somewhere.
distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState & state,ParsedAttr & attr,QualType & declSpecType)630 static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
631                                                    ParsedAttr &attr,
632                                                    QualType &declSpecType) {
633   state.saveDeclSpecAttrs();
634 
635   // C++11 attributes before the decl specifiers actually appertain to
636   // the declarators. Move them straight there. We don't support the
637   // 'put them wherever you like' semantics we allow for GNU attributes.
638   if (attr.isStandardAttributeSyntax()) {
639     moveAttrFromListToList(attr, state.getCurrentAttributes(),
640                            state.getDeclarator().getAttributes());
641     return;
642   }
643 
644   // Try to distribute to the innermost.
645   if (distributeFunctionTypeAttrToInnermost(
646           state, attr, state.getCurrentAttributes(), declSpecType))
647     return;
648 
649   // If that failed, diagnose the bad attribute when the declarator is
650   // fully built.
651   state.addIgnoredTypeAttr(attr);
652 }
653 
654 /// A function type attribute was written on the declarator.  Try to
655 /// apply it somewhere.
distributeFunctionTypeAttrFromDeclarator(TypeProcessingState & state,ParsedAttr & attr,QualType & declSpecType)656 static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
657                                                      ParsedAttr &attr,
658                                                      QualType &declSpecType) {
659   Declarator &declarator = state.getDeclarator();
660 
661   // Try to distribute to the innermost.
662   if (distributeFunctionTypeAttrToInnermost(
663           state, attr, declarator.getAttributes(), declSpecType))
664     return;
665 
666   // If that failed, diagnose the bad attribute when the declarator is
667   // fully built.
668   declarator.getAttributes().remove(&attr);
669   state.addIgnoredTypeAttr(attr);
670 }
671 
672 /// Given that there are attributes written on the declarator
673 /// itself, try to distribute any type attributes to the appropriate
674 /// declarator chunk.
675 ///
676 /// These are attributes like the following:
677 ///   int f ATTR;
678 ///   int (f ATTR)();
679 /// but not necessarily this:
680 ///   int f() ATTR;
distributeTypeAttrsFromDeclarator(TypeProcessingState & state,QualType & declSpecType)681 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
682                                               QualType &declSpecType) {
683   // Collect all the type attributes from the declarator itself.
684   assert(!state.getDeclarator().getAttributes().empty() &&
685          "declarator has no attrs!");
686   // The called functions in this loop actually remove things from the current
687   // list, so iterating over the existing list isn't possible.  Instead, make a
688   // non-owning copy and iterate over that.
689   ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()};
690   for (ParsedAttr &attr : AttrsCopy) {
691     // Do not distribute [[]] attributes. They have strict rules for what
692     // they appertain to.
693     if (attr.isStandardAttributeSyntax())
694       continue;
695 
696     switch (attr.getKind()) {
697     OBJC_POINTER_TYPE_ATTRS_CASELIST:
698       distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType);
699       break;
700 
701     FUNCTION_TYPE_ATTRS_CASELIST:
702       distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType);
703       break;
704 
705     MS_TYPE_ATTRS_CASELIST:
706       // Microsoft type attributes cannot go after the declarator-id.
707       continue;
708 
709     NULLABILITY_TYPE_ATTRS_CASELIST:
710       // Nullability specifiers cannot go after the declarator-id.
711 
712     // Objective-C __kindof does not get distributed.
713     case ParsedAttr::AT_ObjCKindOf:
714       continue;
715 
716     default:
717       break;
718     }
719   }
720 }
721 
722 /// Add a synthetic '()' to a block-literal declarator if it is
723 /// required, given the return type.
maybeSynthesizeBlockSignature(TypeProcessingState & state,QualType declSpecType)724 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
725                                           QualType declSpecType) {
726   Declarator &declarator = state.getDeclarator();
727 
728   // First, check whether the declarator would produce a function,
729   // i.e. whether the innermost semantic chunk is a function.
730   if (declarator.isFunctionDeclarator()) {
731     // If so, make that declarator a prototyped declarator.
732     declarator.getFunctionTypeInfo().hasPrototype = true;
733     return;
734   }
735 
736   // If there are any type objects, the type as written won't name a
737   // function, regardless of the decl spec type.  This is because a
738   // block signature declarator is always an abstract-declarator, and
739   // abstract-declarators can't just be parentheses chunks.  Therefore
740   // we need to build a function chunk unless there are no type
741   // objects and the decl spec type is a function.
742   if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
743     return;
744 
745   // Note that there *are* cases with invalid declarators where
746   // declarators consist solely of parentheses.  In general, these
747   // occur only in failed efforts to make function declarators, so
748   // faking up the function chunk is still the right thing to do.
749 
750   // Otherwise, we need to fake up a function declarator.
751   SourceLocation loc = declarator.getBeginLoc();
752 
753   // ...and *prepend* it to the declarator.
754   SourceLocation NoLoc;
755   declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
756       /*HasProto=*/true,
757       /*IsAmbiguous=*/false,
758       /*LParenLoc=*/NoLoc,
759       /*ArgInfo=*/nullptr,
760       /*NumParams=*/0,
761       /*EllipsisLoc=*/NoLoc,
762       /*RParenLoc=*/NoLoc,
763       /*RefQualifierIsLvalueRef=*/true,
764       /*RefQualifierLoc=*/NoLoc,
765       /*MutableLoc=*/NoLoc, EST_None,
766       /*ESpecRange=*/SourceRange(),
767       /*Exceptions=*/nullptr,
768       /*ExceptionRanges=*/nullptr,
769       /*NumExceptions=*/0,
770       /*NoexceptExpr=*/nullptr,
771       /*ExceptionSpecTokens=*/nullptr,
772       /*DeclsInPrototype=*/None, loc, loc, declarator));
773 
774   // For consistency, make sure the state still has us as processing
775   // the decl spec.
776   assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
777   state.setCurrentChunkIndex(declarator.getNumTypeObjects());
778 }
779 
diagnoseAndRemoveTypeQualifiers(Sema & S,const DeclSpec & DS,unsigned & TypeQuals,QualType TypeSoFar,unsigned RemoveTQs,unsigned DiagID)780 static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
781                                             unsigned &TypeQuals,
782                                             QualType TypeSoFar,
783                                             unsigned RemoveTQs,
784                                             unsigned DiagID) {
785   // If this occurs outside a template instantiation, warn the user about
786   // it; they probably didn't mean to specify a redundant qualifier.
787   typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
788   for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
789                        QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()),
790                        QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
791                        QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
792     if (!(RemoveTQs & Qual.first))
793       continue;
794 
795     if (!S.inTemplateInstantiation()) {
796       if (TypeQuals & Qual.first)
797         S.Diag(Qual.second, DiagID)
798           << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
799           << FixItHint::CreateRemoval(Qual.second);
800     }
801 
802     TypeQuals &= ~Qual.first;
803   }
804 }
805 
806 /// Return true if this is omitted block return type. Also check type
807 /// attributes and type qualifiers when returning true.
checkOmittedBlockReturnType(Sema & S,Declarator & declarator,QualType Result)808 static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
809                                         QualType Result) {
810   if (!isOmittedBlockReturnType(declarator))
811     return false;
812 
813   // Warn if we see type attributes for omitted return type on a block literal.
814   SmallVector<ParsedAttr *, 2> ToBeRemoved;
815   for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) {
816     if (AL.isInvalid() || !AL.isTypeAttr())
817       continue;
818     S.Diag(AL.getLoc(),
819            diag::warn_block_literal_attributes_on_omitted_return_type)
820         << AL;
821     ToBeRemoved.push_back(&AL);
822   }
823   // Remove bad attributes from the list.
824   for (ParsedAttr *AL : ToBeRemoved)
825     declarator.getMutableDeclSpec().getAttributes().remove(AL);
826 
827   // Warn if we see type qualifiers for omitted return type on a block literal.
828   const DeclSpec &DS = declarator.getDeclSpec();
829   unsigned TypeQuals = DS.getTypeQualifiers();
830   diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
831       diag::warn_block_literal_qualifiers_on_omitted_return_type);
832   declarator.getMutableDeclSpec().ClearTypeQualifiers();
833 
834   return true;
835 }
836 
837 /// Apply Objective-C type arguments to the given type.
applyObjCTypeArgs(Sema & S,SourceLocation loc,QualType type,ArrayRef<TypeSourceInfo * > typeArgs,SourceRange typeArgsRange,bool failOnError=false)838 static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
839                                   ArrayRef<TypeSourceInfo *> typeArgs,
840                                   SourceRange typeArgsRange,
841                                   bool failOnError = false) {
842   // We can only apply type arguments to an Objective-C class type.
843   const auto *objcObjectType = type->getAs<ObjCObjectType>();
844   if (!objcObjectType || !objcObjectType->getInterface()) {
845     S.Diag(loc, diag::err_objc_type_args_non_class)
846       << type
847       << typeArgsRange;
848 
849     if (failOnError)
850       return QualType();
851     return type;
852   }
853 
854   // The class type must be parameterized.
855   ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
856   ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
857   if (!typeParams) {
858     S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
859       << objcClass->getDeclName()
860       << FixItHint::CreateRemoval(typeArgsRange);
861 
862     if (failOnError)
863       return QualType();
864 
865     return type;
866   }
867 
868   // The type must not already be specialized.
869   if (objcObjectType->isSpecialized()) {
870     S.Diag(loc, diag::err_objc_type_args_specialized_class)
871       << type
872       << FixItHint::CreateRemoval(typeArgsRange);
873 
874     if (failOnError)
875       return QualType();
876 
877     return type;
878   }
879 
880   // Check the type arguments.
881   SmallVector<QualType, 4> finalTypeArgs;
882   unsigned numTypeParams = typeParams->size();
883   bool anyPackExpansions = false;
884   for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) {
885     TypeSourceInfo *typeArgInfo = typeArgs[i];
886     QualType typeArg = typeArgInfo->getType();
887 
888     // Type arguments cannot have explicit qualifiers or nullability.
889     // We ignore indirect sources of these, e.g. behind typedefs or
890     // template arguments.
891     if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
892       bool diagnosed = false;
893       SourceRange rangeToRemove;
894       if (auto attr = qual.getAs<AttributedTypeLoc>()) {
895         rangeToRemove = attr.getLocalSourceRange();
896         if (attr.getTypePtr()->getImmediateNullability()) {
897           typeArg = attr.getTypePtr()->getModifiedType();
898           S.Diag(attr.getBeginLoc(),
899                  diag::err_objc_type_arg_explicit_nullability)
900               << typeArg << FixItHint::CreateRemoval(rangeToRemove);
901           diagnosed = true;
902         }
903       }
904 
905       if (!diagnosed) {
906         S.Diag(qual.getBeginLoc(), diag::err_objc_type_arg_qualified)
907             << typeArg << typeArg.getQualifiers().getAsString()
908             << FixItHint::CreateRemoval(rangeToRemove);
909       }
910     }
911 
912     // Remove qualifiers even if they're non-local.
913     typeArg = typeArg.getUnqualifiedType();
914 
915     finalTypeArgs.push_back(typeArg);
916 
917     if (typeArg->getAs<PackExpansionType>())
918       anyPackExpansions = true;
919 
920     // Find the corresponding type parameter, if there is one.
921     ObjCTypeParamDecl *typeParam = nullptr;
922     if (!anyPackExpansions) {
923       if (i < numTypeParams) {
924         typeParam = typeParams->begin()[i];
925       } else {
926         // Too many arguments.
927         S.Diag(loc, diag::err_objc_type_args_wrong_arity)
928           << false
929           << objcClass->getDeclName()
930           << (unsigned)typeArgs.size()
931           << numTypeParams;
932         S.Diag(objcClass->getLocation(), diag::note_previous_decl)
933           << objcClass;
934 
935         if (failOnError)
936           return QualType();
937 
938         return type;
939       }
940     }
941 
942     // Objective-C object pointer types must be substitutable for the bounds.
943     if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
944       // If we don't have a type parameter to match against, assume
945       // everything is fine. There was a prior pack expansion that
946       // means we won't be able to match anything.
947       if (!typeParam) {
948         assert(anyPackExpansions && "Too many arguments?");
949         continue;
950       }
951 
952       // Retrieve the bound.
953       QualType bound = typeParam->getUnderlyingType();
954       const auto *boundObjC = bound->getAs<ObjCObjectPointerType>();
955 
956       // Determine whether the type argument is substitutable for the bound.
957       if (typeArgObjC->isObjCIdType()) {
958         // When the type argument is 'id', the only acceptable type
959         // parameter bound is 'id'.
960         if (boundObjC->isObjCIdType())
961           continue;
962       } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
963         // Otherwise, we follow the assignability rules.
964         continue;
965       }
966 
967       // Diagnose the mismatch.
968       S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
969              diag::err_objc_type_arg_does_not_match_bound)
970           << typeArg << bound << typeParam->getDeclName();
971       S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
972         << typeParam->getDeclName();
973 
974       if (failOnError)
975         return QualType();
976 
977       return type;
978     }
979 
980     // Block pointer types are permitted for unqualified 'id' bounds.
981     if (typeArg->isBlockPointerType()) {
982       // If we don't have a type parameter to match against, assume
983       // everything is fine. There was a prior pack expansion that
984       // means we won't be able to match anything.
985       if (!typeParam) {
986         assert(anyPackExpansions && "Too many arguments?");
987         continue;
988       }
989 
990       // Retrieve the bound.
991       QualType bound = typeParam->getUnderlyingType();
992       if (bound->isBlockCompatibleObjCPointerType(S.Context))
993         continue;
994 
995       // Diagnose the mismatch.
996       S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
997              diag::err_objc_type_arg_does_not_match_bound)
998           << typeArg << bound << typeParam->getDeclName();
999       S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
1000         << typeParam->getDeclName();
1001 
1002       if (failOnError)
1003         return QualType();
1004 
1005       return type;
1006     }
1007 
1008     // Dependent types will be checked at instantiation time.
1009     if (typeArg->isDependentType()) {
1010       continue;
1011     }
1012 
1013     // Diagnose non-id-compatible type arguments.
1014     S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
1015            diag::err_objc_type_arg_not_id_compatible)
1016         << typeArg << typeArgInfo->getTypeLoc().getSourceRange();
1017 
1018     if (failOnError)
1019       return QualType();
1020 
1021     return type;
1022   }
1023 
1024   // Make sure we didn't have the wrong number of arguments.
1025   if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
1026     S.Diag(loc, diag::err_objc_type_args_wrong_arity)
1027       << (typeArgs.size() < typeParams->size())
1028       << objcClass->getDeclName()
1029       << (unsigned)finalTypeArgs.size()
1030       << (unsigned)numTypeParams;
1031     S.Diag(objcClass->getLocation(), diag::note_previous_decl)
1032       << objcClass;
1033 
1034     if (failOnError)
1035       return QualType();
1036 
1037     return type;
1038   }
1039 
1040   // Success. Form the specialized type.
1041   return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
1042 }
1043 
BuildObjCTypeParamType(const ObjCTypeParamDecl * Decl,SourceLocation ProtocolLAngleLoc,ArrayRef<ObjCProtocolDecl * > Protocols,ArrayRef<SourceLocation> ProtocolLocs,SourceLocation ProtocolRAngleLoc,bool FailOnError)1044 QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1045                                       SourceLocation ProtocolLAngleLoc,
1046                                       ArrayRef<ObjCProtocolDecl *> Protocols,
1047                                       ArrayRef<SourceLocation> ProtocolLocs,
1048                                       SourceLocation ProtocolRAngleLoc,
1049                                       bool FailOnError) {
1050   QualType Result = QualType(Decl->getTypeForDecl(), 0);
1051   if (!Protocols.empty()) {
1052     bool HasError;
1053     Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1054                                                  HasError);
1055     if (HasError) {
1056       Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers)
1057         << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1058       if (FailOnError) Result = QualType();
1059     }
1060     if (FailOnError && Result.isNull())
1061       return QualType();
1062   }
1063 
1064   return Result;
1065 }
1066 
BuildObjCObjectType(QualType BaseType,SourceLocation Loc,SourceLocation TypeArgsLAngleLoc,ArrayRef<TypeSourceInfo * > TypeArgs,SourceLocation TypeArgsRAngleLoc,SourceLocation ProtocolLAngleLoc,ArrayRef<ObjCProtocolDecl * > Protocols,ArrayRef<SourceLocation> ProtocolLocs,SourceLocation ProtocolRAngleLoc,bool FailOnError)1067 QualType Sema::BuildObjCObjectType(QualType BaseType,
1068                                    SourceLocation Loc,
1069                                    SourceLocation TypeArgsLAngleLoc,
1070                                    ArrayRef<TypeSourceInfo *> TypeArgs,
1071                                    SourceLocation TypeArgsRAngleLoc,
1072                                    SourceLocation ProtocolLAngleLoc,
1073                                    ArrayRef<ObjCProtocolDecl *> Protocols,
1074                                    ArrayRef<SourceLocation> ProtocolLocs,
1075                                    SourceLocation ProtocolRAngleLoc,
1076                                    bool FailOnError) {
1077   QualType Result = BaseType;
1078   if (!TypeArgs.empty()) {
1079     Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
1080                                SourceRange(TypeArgsLAngleLoc,
1081                                            TypeArgsRAngleLoc),
1082                                FailOnError);
1083     if (FailOnError && Result.isNull())
1084       return QualType();
1085   }
1086 
1087   if (!Protocols.empty()) {
1088     bool HasError;
1089     Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1090                                                  HasError);
1091     if (HasError) {
1092       Diag(Loc, diag::err_invalid_protocol_qualifiers)
1093         << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1094       if (FailOnError) Result = QualType();
1095     }
1096     if (FailOnError && Result.isNull())
1097       return QualType();
1098   }
1099 
1100   return Result;
1101 }
1102 
actOnObjCProtocolQualifierType(SourceLocation lAngleLoc,ArrayRef<Decl * > protocols,ArrayRef<SourceLocation> protocolLocs,SourceLocation rAngleLoc)1103 TypeResult Sema::actOnObjCProtocolQualifierType(
1104              SourceLocation lAngleLoc,
1105              ArrayRef<Decl *> protocols,
1106              ArrayRef<SourceLocation> protocolLocs,
1107              SourceLocation rAngleLoc) {
1108   // Form id<protocol-list>.
1109   QualType Result = Context.getObjCObjectType(
1110                       Context.ObjCBuiltinIdTy, { },
1111                       llvm::makeArrayRef(
1112                         (ObjCProtocolDecl * const *)protocols.data(),
1113                         protocols.size()),
1114                       false);
1115   Result = Context.getObjCObjectPointerType(Result);
1116 
1117   TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1118   TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1119 
1120   auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1121   ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1122 
1123   auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1124                         .castAs<ObjCObjectTypeLoc>();
1125   ObjCObjectTL.setHasBaseTypeAsWritten(false);
1126   ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1127 
1128   // No type arguments.
1129   ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1130   ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1131 
1132   // Fill in protocol qualifiers.
1133   ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
1134   ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
1135   for (unsigned i = 0, n = protocols.size(); i != n; ++i)
1136     ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
1137 
1138   // We're done. Return the completed type to the parser.
1139   return CreateParsedType(Result, ResultTInfo);
1140 }
1141 
actOnObjCTypeArgsAndProtocolQualifiers(Scope * S,SourceLocation Loc,ParsedType BaseType,SourceLocation TypeArgsLAngleLoc,ArrayRef<ParsedType> TypeArgs,SourceLocation TypeArgsRAngleLoc,SourceLocation ProtocolLAngleLoc,ArrayRef<Decl * > Protocols,ArrayRef<SourceLocation> ProtocolLocs,SourceLocation ProtocolRAngleLoc)1142 TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers(
1143              Scope *S,
1144              SourceLocation Loc,
1145              ParsedType BaseType,
1146              SourceLocation TypeArgsLAngleLoc,
1147              ArrayRef<ParsedType> TypeArgs,
1148              SourceLocation TypeArgsRAngleLoc,
1149              SourceLocation ProtocolLAngleLoc,
1150              ArrayRef<Decl *> Protocols,
1151              ArrayRef<SourceLocation> ProtocolLocs,
1152              SourceLocation ProtocolRAngleLoc) {
1153   TypeSourceInfo *BaseTypeInfo = nullptr;
1154   QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
1155   if (T.isNull())
1156     return true;
1157 
1158   // Handle missing type-source info.
1159   if (!BaseTypeInfo)
1160     BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
1161 
1162   // Extract type arguments.
1163   SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
1164   for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
1165     TypeSourceInfo *TypeArgInfo = nullptr;
1166     QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
1167     if (TypeArg.isNull()) {
1168       ActualTypeArgInfos.clear();
1169       break;
1170     }
1171 
1172     assert(TypeArgInfo && "No type source info?");
1173     ActualTypeArgInfos.push_back(TypeArgInfo);
1174   }
1175 
1176   // Build the object type.
1177   QualType Result = BuildObjCObjectType(
1178       T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1179       TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1180       ProtocolLAngleLoc,
1181       llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(),
1182                          Protocols.size()),
1183       ProtocolLocs, ProtocolRAngleLoc,
1184       /*FailOnError=*/false);
1185 
1186   if (Result == T)
1187     return BaseType;
1188 
1189   // Create source information for this type.
1190   TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1191   TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1192 
1193   // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
1194   // object pointer type. Fill in source information for it.
1195   if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
1196     // The '*' is implicit.
1197     ObjCObjectPointerTL.setStarLoc(SourceLocation());
1198     ResultTL = ObjCObjectPointerTL.getPointeeLoc();
1199   }
1200 
1201   if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) {
1202     // Protocol qualifier information.
1203     if (OTPTL.getNumProtocols() > 0) {
1204       assert(OTPTL.getNumProtocols() == Protocols.size());
1205       OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1206       OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1207       for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1208         OTPTL.setProtocolLoc(i, ProtocolLocs[i]);
1209     }
1210 
1211     // We're done. Return the completed type to the parser.
1212     return CreateParsedType(Result, ResultTInfo);
1213   }
1214 
1215   auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
1216 
1217   // Type argument information.
1218   if (ObjCObjectTL.getNumTypeArgs() > 0) {
1219     assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
1220     ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
1221     ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
1222     for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
1223       ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
1224   } else {
1225     ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1226     ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1227   }
1228 
1229   // Protocol qualifier information.
1230   if (ObjCObjectTL.getNumProtocols() > 0) {
1231     assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
1232     ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1233     ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1234     for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1235       ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
1236   } else {
1237     ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1238     ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1239   }
1240 
1241   // Base type.
1242   ObjCObjectTL.setHasBaseTypeAsWritten(true);
1243   if (ObjCObjectTL.getType() == T)
1244     ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1245   else
1246     ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1247 
1248   // We're done. Return the completed type to the parser.
1249   return CreateParsedType(Result, ResultTInfo);
1250 }
1251 
1252 static OpenCLAccessAttr::Spelling
getImageAccess(const ParsedAttributesView & Attrs)1253 getImageAccess(const ParsedAttributesView &Attrs) {
1254   for (const ParsedAttr &AL : Attrs)
1255     if (AL.getKind() == ParsedAttr::AT_OpenCLAccess)
1256       return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling());
1257   return OpenCLAccessAttr::Keyword_read_only;
1258 }
1259 
1260 /// Convert the specified declspec to the appropriate type
1261 /// object.
1262 /// \param state Specifies the declarator containing the declaration specifier
1263 /// to be converted, along with other associated processing state.
1264 /// \returns The type described by the declaration specifiers.  This function
1265 /// never returns null.
ConvertDeclSpecToType(TypeProcessingState & state)1266 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
1267   // FIXME: Should move the logic from DeclSpec::Finish to here for validity
1268   // checking.
1269 
1270   Sema &S = state.getSema();
1271   Declarator &declarator = state.getDeclarator();
1272   DeclSpec &DS = declarator.getMutableDeclSpec();
1273   SourceLocation DeclLoc = declarator.getIdentifierLoc();
1274   if (DeclLoc.isInvalid())
1275     DeclLoc = DS.getBeginLoc();
1276 
1277   ASTContext &Context = S.Context;
1278 
1279   QualType Result;
1280   switch (DS.getTypeSpecType()) {
1281   case DeclSpec::TST_void:
1282     Result = Context.VoidTy;
1283     break;
1284   case DeclSpec::TST_char:
1285     if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
1286       Result = Context.CharTy;
1287     else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed)
1288       Result = Context.SignedCharTy;
1289     else {
1290       assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&
1291              "Unknown TSS value");
1292       Result = Context.UnsignedCharTy;
1293     }
1294     break;
1295   case DeclSpec::TST_wchar:
1296     if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
1297       Result = Context.WCharTy;
1298     else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed) {
1299       S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
1300         << DS.getSpecifierName(DS.getTypeSpecType(),
1301                                Context.getPrintingPolicy());
1302       Result = Context.getSignedWCharType();
1303     } else {
1304       assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&
1305              "Unknown TSS value");
1306       S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
1307         << DS.getSpecifierName(DS.getTypeSpecType(),
1308                                Context.getPrintingPolicy());
1309       Result = Context.getUnsignedWCharType();
1310     }
1311     break;
1312   case DeclSpec::TST_char8:
1313     assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1314            "Unknown TSS value");
1315     Result = Context.Char8Ty;
1316     break;
1317   case DeclSpec::TST_char16:
1318     assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1319            "Unknown TSS value");
1320     Result = Context.Char16Ty;
1321     break;
1322   case DeclSpec::TST_char32:
1323     assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1324            "Unknown TSS value");
1325     Result = Context.Char32Ty;
1326     break;
1327   case DeclSpec::TST_unspecified:
1328     // If this is a missing declspec in a block literal return context, then it
1329     // is inferred from the return statements inside the block.
1330     // The declspec is always missing in a lambda expr context; it is either
1331     // specified with a trailing return type or inferred.
1332     if (S.getLangOpts().CPlusPlus14 &&
1333         declarator.getContext() == DeclaratorContext::LambdaExpr) {
1334       // In C++1y, a lambda's implicit return type is 'auto'.
1335       Result = Context.getAutoDeductType();
1336       break;
1337     } else if (declarator.getContext() == DeclaratorContext::LambdaExpr ||
1338                checkOmittedBlockReturnType(S, declarator,
1339                                            Context.DependentTy)) {
1340       Result = Context.DependentTy;
1341       break;
1342     }
1343 
1344     // Unspecified typespec defaults to int in C90.  However, the C90 grammar
1345     // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
1346     // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
1347     // Note that the one exception to this is function definitions, which are
1348     // allowed to be completely missing a declspec.  This is handled in the
1349     // parser already though by it pretending to have seen an 'int' in this
1350     // case.
1351     if (S.getLangOpts().ImplicitInt) {
1352       // In C89 mode, we only warn if there is a completely missing declspec
1353       // when one is not allowed.
1354       if (DS.isEmpty()) {
1355         S.Diag(DeclLoc, diag::ext_missing_declspec)
1356             << DS.getSourceRange()
1357             << FixItHint::CreateInsertion(DS.getBeginLoc(), "int");
1358       }
1359     } else if (!DS.hasTypeSpecifier()) {
1360       // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
1361       // "At least one type specifier shall be given in the declaration
1362       // specifiers in each declaration, and in the specifier-qualifier list in
1363       // each struct declaration and type name."
1364       if (S.getLangOpts().CPlusPlus && !DS.isTypeSpecPipe()) {
1365         S.Diag(DeclLoc, diag::err_missing_type_specifier)
1366           << DS.getSourceRange();
1367 
1368         // When this occurs in C++ code, often something is very broken with the
1369         // value being declared, poison it as invalid so we don't get chains of
1370         // errors.
1371         declarator.setInvalidType(true);
1372       } else if (S.getLangOpts().getOpenCLCompatibleVersion() >= 200 &&
1373                  DS.isTypeSpecPipe()) {
1374         S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1375           << DS.getSourceRange();
1376         declarator.setInvalidType(true);
1377       } else {
1378         S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1379           << DS.getSourceRange();
1380       }
1381     }
1382 
1383     LLVM_FALLTHROUGH;
1384   case DeclSpec::TST_int: {
1385     if (DS.getTypeSpecSign() != TypeSpecifierSign::Unsigned) {
1386       switch (DS.getTypeSpecWidth()) {
1387       case TypeSpecifierWidth::Unspecified:
1388         Result = Context.IntTy;
1389         break;
1390       case TypeSpecifierWidth::Short:
1391         Result = Context.ShortTy;
1392         break;
1393       case TypeSpecifierWidth::Long:
1394         Result = Context.LongTy;
1395         break;
1396       case TypeSpecifierWidth::LongLong:
1397         Result = Context.LongLongTy;
1398 
1399         // 'long long' is a C99 or C++11 feature.
1400         if (!S.getLangOpts().C99) {
1401           if (S.getLangOpts().CPlusPlus)
1402             S.Diag(DS.getTypeSpecWidthLoc(),
1403                    S.getLangOpts().CPlusPlus11 ?
1404                    diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1405           else
1406             S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1407         }
1408         break;
1409       }
1410     } else {
1411       switch (DS.getTypeSpecWidth()) {
1412       case TypeSpecifierWidth::Unspecified:
1413         Result = Context.UnsignedIntTy;
1414         break;
1415       case TypeSpecifierWidth::Short:
1416         Result = Context.UnsignedShortTy;
1417         break;
1418       case TypeSpecifierWidth::Long:
1419         Result = Context.UnsignedLongTy;
1420         break;
1421       case TypeSpecifierWidth::LongLong:
1422         Result = Context.UnsignedLongLongTy;
1423 
1424         // 'long long' is a C99 or C++11 feature.
1425         if (!S.getLangOpts().C99) {
1426           if (S.getLangOpts().CPlusPlus)
1427             S.Diag(DS.getTypeSpecWidthLoc(),
1428                    S.getLangOpts().CPlusPlus11 ?
1429                    diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1430           else
1431             S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1432         }
1433         break;
1434       }
1435     }
1436     break;
1437   }
1438   case DeclSpec::TST_extint: {
1439     if (!S.Context.getTargetInfo().hasExtIntType())
1440       S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1441         << "_ExtInt";
1442     Result =
1443         S.BuildExtIntType(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned,
1444                           DS.getRepAsExpr(), DS.getBeginLoc());
1445     if (Result.isNull()) {
1446       Result = Context.IntTy;
1447       declarator.setInvalidType(true);
1448     }
1449     break;
1450   }
1451   case DeclSpec::TST_accum: {
1452     switch (DS.getTypeSpecWidth()) {
1453     case TypeSpecifierWidth::Short:
1454       Result = Context.ShortAccumTy;
1455       break;
1456     case TypeSpecifierWidth::Unspecified:
1457       Result = Context.AccumTy;
1458       break;
1459     case TypeSpecifierWidth::Long:
1460       Result = Context.LongAccumTy;
1461       break;
1462     case TypeSpecifierWidth::LongLong:
1463       llvm_unreachable("Unable to specify long long as _Accum width");
1464     }
1465 
1466     if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1467       Result = Context.getCorrespondingUnsignedType(Result);
1468 
1469     if (DS.isTypeSpecSat())
1470       Result = Context.getCorrespondingSaturatedType(Result);
1471 
1472     break;
1473   }
1474   case DeclSpec::TST_fract: {
1475     switch (DS.getTypeSpecWidth()) {
1476     case TypeSpecifierWidth::Short:
1477       Result = Context.ShortFractTy;
1478       break;
1479     case TypeSpecifierWidth::Unspecified:
1480       Result = Context.FractTy;
1481       break;
1482     case TypeSpecifierWidth::Long:
1483       Result = Context.LongFractTy;
1484       break;
1485     case TypeSpecifierWidth::LongLong:
1486       llvm_unreachable("Unable to specify long long as _Fract width");
1487     }
1488 
1489     if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1490       Result = Context.getCorrespondingUnsignedType(Result);
1491 
1492     if (DS.isTypeSpecSat())
1493       Result = Context.getCorrespondingSaturatedType(Result);
1494 
1495     break;
1496   }
1497   case DeclSpec::TST_int128:
1498     if (!S.Context.getTargetInfo().hasInt128Type() &&
1499         !S.getLangOpts().SYCLIsDevice &&
1500         !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
1501       S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1502         << "__int128";
1503     if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1504       Result = Context.UnsignedInt128Ty;
1505     else
1506       Result = Context.Int128Ty;
1507     break;
1508   case DeclSpec::TST_float16:
1509     // CUDA host and device may have different _Float16 support, therefore
1510     // do not diagnose _Float16 usage to avoid false alarm.
1511     // ToDo: more precise diagnostics for CUDA.
1512     if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA &&
1513         !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
1514       S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1515         << "_Float16";
1516     Result = Context.Float16Ty;
1517     break;
1518   case DeclSpec::TST_half:    Result = Context.HalfTy; break;
1519   case DeclSpec::TST_BFloat16:
1520     if (!S.Context.getTargetInfo().hasBFloat16Type())
1521       S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1522         << "__bf16";
1523     Result = Context.BFloat16Ty;
1524     break;
1525   case DeclSpec::TST_float:   Result = Context.FloatTy; break;
1526   case DeclSpec::TST_double:
1527     if (DS.getTypeSpecWidth() == TypeSpecifierWidth::Long)
1528       Result = Context.LongDoubleTy;
1529     else
1530       Result = Context.DoubleTy;
1531     if (S.getLangOpts().OpenCL) {
1532       if (!S.getOpenCLOptions().isSupported("cl_khr_fp64", S.getLangOpts()))
1533         S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1534             << 0 << Result
1535             << (S.getLangOpts().getOpenCLCompatibleVersion() == 300
1536                     ? "cl_khr_fp64 and __opencl_c_fp64"
1537                     : "cl_khr_fp64");
1538       else if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp64", S.getLangOpts()))
1539         S.Diag(DS.getTypeSpecTypeLoc(), diag::ext_opencl_double_without_pragma);
1540     }
1541     break;
1542   case DeclSpec::TST_float128:
1543     if (!S.Context.getTargetInfo().hasFloat128Type() &&
1544         !S.getLangOpts().SYCLIsDevice &&
1545         !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
1546       S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1547         << "__float128";
1548     Result = Context.Float128Ty;
1549     break;
1550   case DeclSpec::TST_ibm128:
1551     if (!S.Context.getTargetInfo().hasIbm128Type() &&
1552         !S.getLangOpts().SYCLIsDevice &&
1553         !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
1554       S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__ibm128";
1555     Result = Context.Ibm128Ty;
1556     break;
1557   case DeclSpec::TST_bool:
1558     Result = Context.BoolTy; // _Bool or bool
1559     break;
1560   case DeclSpec::TST_decimal32:    // _Decimal32
1561   case DeclSpec::TST_decimal64:    // _Decimal64
1562   case DeclSpec::TST_decimal128:   // _Decimal128
1563     S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1564     Result = Context.IntTy;
1565     declarator.setInvalidType(true);
1566     break;
1567   case DeclSpec::TST_class:
1568   case DeclSpec::TST_enum:
1569   case DeclSpec::TST_union:
1570   case DeclSpec::TST_struct:
1571   case DeclSpec::TST_interface: {
1572     TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl());
1573     if (!D) {
1574       // This can happen in C++ with ambiguous lookups.
1575       Result = Context.IntTy;
1576       declarator.setInvalidType(true);
1577       break;
1578     }
1579 
1580     // If the type is deprecated or unavailable, diagnose it.
1581     S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
1582 
1583     assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&
1584            DS.getTypeSpecComplex() == 0 &&
1585            DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1586            "No qualifiers on tag names!");
1587 
1588     // TypeQuals handled by caller.
1589     Result = Context.getTypeDeclType(D);
1590 
1591     // In both C and C++, make an ElaboratedType.
1592     ElaboratedTypeKeyword Keyword
1593       = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
1594     Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result,
1595                                  DS.isTypeSpecOwned() ? D : nullptr);
1596     break;
1597   }
1598   case DeclSpec::TST_typename: {
1599     assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&
1600            DS.getTypeSpecComplex() == 0 &&
1601            DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1602            "Can't handle qualifiers on typedef names yet!");
1603     Result = S.GetTypeFromParser(DS.getRepAsType());
1604     if (Result.isNull()) {
1605       declarator.setInvalidType(true);
1606     }
1607 
1608     // TypeQuals handled by caller.
1609     break;
1610   }
1611   case DeclSpec::TST_typeofType:
1612     // FIXME: Preserve type source info.
1613     Result = S.GetTypeFromParser(DS.getRepAsType());
1614     assert(!Result.isNull() && "Didn't get a type for typeof?");
1615     if (!Result->isDependentType())
1616       if (const TagType *TT = Result->getAs<TagType>())
1617         S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1618     // TypeQuals handled by caller.
1619     Result = Context.getTypeOfType(Result);
1620     break;
1621   case DeclSpec::TST_typeofExpr: {
1622     Expr *E = DS.getRepAsExpr();
1623     assert(E && "Didn't get an expression for typeof?");
1624     // TypeQuals handled by caller.
1625     Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
1626     if (Result.isNull()) {
1627       Result = Context.IntTy;
1628       declarator.setInvalidType(true);
1629     }
1630     break;
1631   }
1632   case DeclSpec::TST_decltype: {
1633     Expr *E = DS.getRepAsExpr();
1634     assert(E && "Didn't get an expression for decltype?");
1635     // TypeQuals handled by caller.
1636     Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
1637     if (Result.isNull()) {
1638       Result = Context.IntTy;
1639       declarator.setInvalidType(true);
1640     }
1641     break;
1642   }
1643   case DeclSpec::TST_underlyingType:
1644     Result = S.GetTypeFromParser(DS.getRepAsType());
1645     assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
1646     Result = S.BuildUnaryTransformType(Result,
1647                                        UnaryTransformType::EnumUnderlyingType,
1648                                        DS.getTypeSpecTypeLoc());
1649     if (Result.isNull()) {
1650       Result = Context.IntTy;
1651       declarator.setInvalidType(true);
1652     }
1653     break;
1654 
1655   case DeclSpec::TST_auto:
1656   case DeclSpec::TST_decltype_auto: {
1657     auto AutoKW = DS.getTypeSpecType() == DeclSpec::TST_decltype_auto
1658                       ? AutoTypeKeyword::DecltypeAuto
1659                       : AutoTypeKeyword::Auto;
1660 
1661     ConceptDecl *TypeConstraintConcept = nullptr;
1662     llvm::SmallVector<TemplateArgument, 8> TemplateArgs;
1663     if (DS.isConstrainedAuto()) {
1664       if (TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId()) {
1665         TypeConstraintConcept =
1666             cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl());
1667         TemplateArgumentListInfo TemplateArgsInfo;
1668         TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc);
1669         TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc);
1670         ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1671                                            TemplateId->NumArgs);
1672         S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
1673         for (const auto &ArgLoc : TemplateArgsInfo.arguments())
1674           TemplateArgs.push_back(ArgLoc.getArgument());
1675       } else {
1676         declarator.setInvalidType(true);
1677       }
1678     }
1679     Result = S.Context.getAutoType(QualType(), AutoKW,
1680                                    /*IsDependent*/ false, /*IsPack=*/false,
1681                                    TypeConstraintConcept, TemplateArgs);
1682     break;
1683   }
1684 
1685   case DeclSpec::TST_auto_type:
1686     Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1687     break;
1688 
1689   case DeclSpec::TST_unknown_anytype:
1690     Result = Context.UnknownAnyTy;
1691     break;
1692 
1693   case DeclSpec::TST_atomic:
1694     Result = S.GetTypeFromParser(DS.getRepAsType());
1695     assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1696     Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1697     if (Result.isNull()) {
1698       Result = Context.IntTy;
1699       declarator.setInvalidType(true);
1700     }
1701     break;
1702 
1703 #define GENERIC_IMAGE_TYPE(ImgType, Id)                                        \
1704   case DeclSpec::TST_##ImgType##_t:                                            \
1705     switch (getImageAccess(DS.getAttributes())) {                              \
1706     case OpenCLAccessAttr::Keyword_write_only:                                 \
1707       Result = Context.Id##WOTy;                                               \
1708       break;                                                                   \
1709     case OpenCLAccessAttr::Keyword_read_write:                                 \
1710       Result = Context.Id##RWTy;                                               \
1711       break;                                                                   \
1712     case OpenCLAccessAttr::Keyword_read_only:                                  \
1713       Result = Context.Id##ROTy;                                               \
1714       break;                                                                   \
1715     case OpenCLAccessAttr::SpellingNotCalculated:                              \
1716       llvm_unreachable("Spelling not yet calculated");                         \
1717     }                                                                          \
1718     break;
1719 #include "clang/Basic/OpenCLImageTypes.def"
1720 
1721   case DeclSpec::TST_error:
1722     Result = Context.IntTy;
1723     declarator.setInvalidType(true);
1724     break;
1725   }
1726 
1727   // FIXME: we want resulting declarations to be marked invalid, but claiming
1728   // the type is invalid is too strong - e.g. it causes ActOnTypeName to return
1729   // a null type.
1730   if (Result->containsErrors())
1731     declarator.setInvalidType();
1732 
1733   if (S.getLangOpts().OpenCL) {
1734     const auto &OpenCLOptions = S.getOpenCLOptions();
1735     bool IsOpenCLC30Compatible =
1736         S.getLangOpts().getOpenCLCompatibleVersion() == 300;
1737     // OpenCL C v3.0 s6.3.3 - OpenCL image types require __opencl_c_images
1738     // support.
1739     // OpenCL C v3.0 s6.2.1 - OpenCL 3d image write types requires support
1740     // for OpenCL C 2.0, or OpenCL C 3.0 or newer and the
1741     // __opencl_c_3d_image_writes feature. OpenCL C v3.0 API s4.2 - For devices
1742     // that support OpenCL 3.0, cl_khr_3d_image_writes must be returned when and
1743     // only when the optional feature is supported
1744     if ((Result->isImageType() || Result->isSamplerT()) &&
1745         (IsOpenCLC30Compatible &&
1746          !OpenCLOptions.isSupported("__opencl_c_images", S.getLangOpts()))) {
1747       S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1748           << 0 << Result << "__opencl_c_images";
1749       declarator.setInvalidType();
1750     } else if (Result->isOCLImage3dWOType() &&
1751                !OpenCLOptions.isSupported("cl_khr_3d_image_writes",
1752                                           S.getLangOpts())) {
1753       S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1754           << 0 << Result
1755           << (IsOpenCLC30Compatible
1756                   ? "cl_khr_3d_image_writes and __opencl_c_3d_image_writes"
1757                   : "cl_khr_3d_image_writes");
1758       declarator.setInvalidType();
1759     }
1760   }
1761 
1762   bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1763                           DS.getTypeSpecType() == DeclSpec::TST_fract;
1764 
1765   // Only fixed point types can be saturated
1766   if (DS.isTypeSpecSat() && !IsFixedPointType)
1767     S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
1768         << DS.getSpecifierName(DS.getTypeSpecType(),
1769                                Context.getPrintingPolicy());
1770 
1771   // Handle complex types.
1772   if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1773     if (S.getLangOpts().Freestanding)
1774       S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1775     Result = Context.getComplexType(Result);
1776   } else if (DS.isTypeAltiVecVector()) {
1777     unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1778     assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1779     VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1780     if (DS.isTypeAltiVecPixel())
1781       VecKind = VectorType::AltiVecPixel;
1782     else if (DS.isTypeAltiVecBool())
1783       VecKind = VectorType::AltiVecBool;
1784     Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1785   }
1786 
1787   // FIXME: Imaginary.
1788   if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1789     S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1790 
1791   // Before we process any type attributes, synthesize a block literal
1792   // function declarator if necessary.
1793   if (declarator.getContext() == DeclaratorContext::BlockLiteral)
1794     maybeSynthesizeBlockSignature(state, Result);
1795 
1796   // Apply any type attributes from the decl spec.  This may cause the
1797   // list of type attributes to be temporarily saved while the type
1798   // attributes are pushed around.
1799   // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1800   if (!DS.isTypeSpecPipe())
1801     processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes());
1802 
1803   // Apply const/volatile/restrict qualifiers to T.
1804   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1805     // Warn about CV qualifiers on function types.
1806     // C99 6.7.3p8:
1807     //   If the specification of a function type includes any type qualifiers,
1808     //   the behavior is undefined.
1809     // C++11 [dcl.fct]p7:
1810     //   The effect of a cv-qualifier-seq in a function declarator is not the
1811     //   same as adding cv-qualification on top of the function type. In the
1812     //   latter case, the cv-qualifiers are ignored.
1813     if (Result->isFunctionType()) {
1814       diagnoseAndRemoveTypeQualifiers(
1815           S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1816           S.getLangOpts().CPlusPlus
1817               ? diag::warn_typecheck_function_qualifiers_ignored
1818               : diag::warn_typecheck_function_qualifiers_unspecified);
1819       // No diagnostic for 'restrict' or '_Atomic' applied to a
1820       // function type; we'll diagnose those later, in BuildQualifiedType.
1821     }
1822 
1823     // C++11 [dcl.ref]p1:
1824     //   Cv-qualified references are ill-formed except when the
1825     //   cv-qualifiers are introduced through the use of a typedef-name
1826     //   or decltype-specifier, in which case the cv-qualifiers are ignored.
1827     //
1828     // There don't appear to be any other contexts in which a cv-qualified
1829     // reference type could be formed, so the 'ill-formed' clause here appears
1830     // to never happen.
1831     if (TypeQuals && Result->isReferenceType()) {
1832       diagnoseAndRemoveTypeQualifiers(
1833           S, DS, TypeQuals, Result,
1834           DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1835           diag::warn_typecheck_reference_qualifiers);
1836     }
1837 
1838     // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1839     // than once in the same specifier-list or qualifier-list, either directly
1840     // or via one or more typedefs."
1841     if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1842         && TypeQuals & Result.getCVRQualifiers()) {
1843       if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1844         S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1845           << "const";
1846       }
1847 
1848       if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1849         S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1850           << "volatile";
1851       }
1852 
1853       // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1854       // produce a warning in this case.
1855     }
1856 
1857     QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1858 
1859     // If adding qualifiers fails, just use the unqualified type.
1860     if (Qualified.isNull())
1861       declarator.setInvalidType(true);
1862     else
1863       Result = Qualified;
1864   }
1865 
1866   assert(!Result.isNull() && "This function should not return a null type");
1867   return Result;
1868 }
1869 
getPrintableNameForEntity(DeclarationName Entity)1870 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1871   if (Entity)
1872     return Entity.getAsString();
1873 
1874   return "type name";
1875 }
1876 
BuildQualifiedType(QualType T,SourceLocation Loc,Qualifiers Qs,const DeclSpec * DS)1877 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1878                                   Qualifiers Qs, const DeclSpec *DS) {
1879   if (T.isNull())
1880     return QualType();
1881 
1882   // Ignore any attempt to form a cv-qualified reference.
1883   if (T->isReferenceType()) {
1884     Qs.removeConst();
1885     Qs.removeVolatile();
1886   }
1887 
1888   // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1889   // object or incomplete types shall not be restrict-qualified."
1890   if (Qs.hasRestrict()) {
1891     unsigned DiagID = 0;
1892     QualType ProblemTy;
1893 
1894     if (T->isAnyPointerType() || T->isReferenceType() ||
1895         T->isMemberPointerType()) {
1896       QualType EltTy;
1897       if (T->isObjCObjectPointerType())
1898         EltTy = T;
1899       else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1900         EltTy = PTy->getPointeeType();
1901       else
1902         EltTy = T->getPointeeType();
1903 
1904       // If we have a pointer or reference, the pointee must have an object
1905       // incomplete type.
1906       if (!EltTy->isIncompleteOrObjectType()) {
1907         DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1908         ProblemTy = EltTy;
1909       }
1910     } else if (!T->isDependentType()) {
1911       DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1912       ProblemTy = T;
1913     }
1914 
1915     if (DiagID) {
1916       Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1917       Qs.removeRestrict();
1918     }
1919   }
1920 
1921   return Context.getQualifiedType(T, Qs);
1922 }
1923 
BuildQualifiedType(QualType T,SourceLocation Loc,unsigned CVRAU,const DeclSpec * DS)1924 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1925                                   unsigned CVRAU, const DeclSpec *DS) {
1926   if (T.isNull())
1927     return QualType();
1928 
1929   // Ignore any attempt to form a cv-qualified reference.
1930   if (T->isReferenceType())
1931     CVRAU &=
1932         ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic);
1933 
1934   // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1935   // TQ_unaligned;
1936   unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1937 
1938   // C11 6.7.3/5:
1939   //   If the same qualifier appears more than once in the same
1940   //   specifier-qualifier-list, either directly or via one or more typedefs,
1941   //   the behavior is the same as if it appeared only once.
1942   //
1943   // It's not specified what happens when the _Atomic qualifier is applied to
1944   // a type specified with the _Atomic specifier, but we assume that this
1945   // should be treated as if the _Atomic qualifier appeared multiple times.
1946   if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1947     // C11 6.7.3/5:
1948     //   If other qualifiers appear along with the _Atomic qualifier in a
1949     //   specifier-qualifier-list, the resulting type is the so-qualified
1950     //   atomic type.
1951     //
1952     // Don't need to worry about array types here, since _Atomic can't be
1953     // applied to such types.
1954     SplitQualType Split = T.getSplitUnqualifiedType();
1955     T = BuildAtomicType(QualType(Split.Ty, 0),
1956                         DS ? DS->getAtomicSpecLoc() : Loc);
1957     if (T.isNull())
1958       return T;
1959     Split.Quals.addCVRQualifiers(CVR);
1960     return BuildQualifiedType(T, Loc, Split.Quals);
1961   }
1962 
1963   Qualifiers Q = Qualifiers::fromCVRMask(CVR);
1964   Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned);
1965   return BuildQualifiedType(T, Loc, Q, DS);
1966 }
1967 
1968 /// Build a paren type including \p T.
BuildParenType(QualType T)1969 QualType Sema::BuildParenType(QualType T) {
1970   return Context.getParenType(T);
1971 }
1972 
1973 /// Given that we're building a pointer or reference to the given
inferARCLifetimeForPointee(Sema & S,QualType type,SourceLocation loc,bool isReference)1974 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1975                                            SourceLocation loc,
1976                                            bool isReference) {
1977   // Bail out if retention is unrequired or already specified.
1978   if (!type->isObjCLifetimeType() ||
1979       type.getObjCLifetime() != Qualifiers::OCL_None)
1980     return type;
1981 
1982   Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1983 
1984   // If the object type is const-qualified, we can safely use
1985   // __unsafe_unretained.  This is safe (because there are no read
1986   // barriers), and it'll be safe to coerce anything but __weak* to
1987   // the resulting type.
1988   if (type.isConstQualified()) {
1989     implicitLifetime = Qualifiers::OCL_ExplicitNone;
1990 
1991   // Otherwise, check whether the static type does not require
1992   // retaining.  This currently only triggers for Class (possibly
1993   // protocol-qualifed, and arrays thereof).
1994   } else if (type->isObjCARCImplicitlyUnretainedType()) {
1995     implicitLifetime = Qualifiers::OCL_ExplicitNone;
1996 
1997   // If we are in an unevaluated context, like sizeof, skip adding a
1998   // qualification.
1999   } else if (S.isUnevaluatedContext()) {
2000     return type;
2001 
2002   // If that failed, give an error and recover using __strong.  __strong
2003   // is the option most likely to prevent spurious second-order diagnostics,
2004   // like when binding a reference to a field.
2005   } else {
2006     // These types can show up in private ivars in system headers, so
2007     // we need this to not be an error in those cases.  Instead we
2008     // want to delay.
2009     if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
2010       S.DelayedDiagnostics.add(
2011           sema::DelayedDiagnostic::makeForbiddenType(loc,
2012               diag::err_arc_indirect_no_ownership, type, isReference));
2013     } else {
2014       S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
2015     }
2016     implicitLifetime = Qualifiers::OCL_Strong;
2017   }
2018   assert(implicitLifetime && "didn't infer any lifetime!");
2019 
2020   Qualifiers qs;
2021   qs.addObjCLifetime(implicitLifetime);
2022   return S.Context.getQualifiedType(type, qs);
2023 }
2024 
getFunctionQualifiersAsString(const FunctionProtoType * FnTy)2025 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
2026   std::string Quals = FnTy->getMethodQuals().getAsString();
2027 
2028   switch (FnTy->getRefQualifier()) {
2029   case RQ_None:
2030     break;
2031 
2032   case RQ_LValue:
2033     if (!Quals.empty())
2034       Quals += ' ';
2035     Quals += '&';
2036     break;
2037 
2038   case RQ_RValue:
2039     if (!Quals.empty())
2040       Quals += ' ';
2041     Quals += "&&";
2042     break;
2043   }
2044 
2045   return Quals;
2046 }
2047 
2048 namespace {
2049 /// Kinds of declarator that cannot contain a qualified function type.
2050 ///
2051 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
2052 ///     a function type with a cv-qualifier or a ref-qualifier can only appear
2053 ///     at the topmost level of a type.
2054 ///
2055 /// Parens and member pointers are permitted. We don't diagnose array and
2056 /// function declarators, because they don't allow function types at all.
2057 ///
2058 /// The values of this enum are used in diagnostics.
2059 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
2060 } // end anonymous namespace
2061 
2062 /// Check whether the type T is a qualified function type, and if it is,
2063 /// diagnose that it cannot be contained within the given kind of declarator.
checkQualifiedFunction(Sema & S,QualType T,SourceLocation Loc,QualifiedFunctionKind QFK)2064 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
2065                                    QualifiedFunctionKind QFK) {
2066   // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
2067   const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
2068   if (!FPT ||
2069       (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
2070     return false;
2071 
2072   S.Diag(Loc, diag::err_compound_qualified_function_type)
2073     << QFK << isa<FunctionType>(T.IgnoreParens()) << T
2074     << getFunctionQualifiersAsString(FPT);
2075   return true;
2076 }
2077 
CheckQualifiedFunctionForTypeId(QualType T,SourceLocation Loc)2078 bool Sema::CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc) {
2079   const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
2080   if (!FPT ||
2081       (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
2082     return false;
2083 
2084   Diag(Loc, diag::err_qualified_function_typeid)
2085       << T << getFunctionQualifiersAsString(FPT);
2086   return true;
2087 }
2088 
2089 // Helper to deduce addr space of a pointee type in OpenCL mode.
deduceOpenCLPointeeAddrSpace(Sema & S,QualType PointeeType)2090 static QualType deduceOpenCLPointeeAddrSpace(Sema &S, QualType PointeeType) {
2091   if (!PointeeType->isUndeducedAutoType() && !PointeeType->isDependentType() &&
2092       !PointeeType->isSamplerT() &&
2093       !PointeeType.hasAddressSpace())
2094     PointeeType = S.getASTContext().getAddrSpaceQualType(
2095         PointeeType, S.getASTContext().getDefaultOpenCLPointeeAddrSpace());
2096   return PointeeType;
2097 }
2098 
2099 /// Build a pointer type.
2100 ///
2101 /// \param T The type to which we'll be building a pointer.
2102 ///
2103 /// \param Loc The location of the entity whose type involves this
2104 /// pointer type or, if there is no such entity, the location of the
2105 /// type that will have pointer type.
2106 ///
2107 /// \param Entity The name of the entity that involves the pointer
2108 /// type, if known.
2109 ///
2110 /// \returns A suitable pointer type, if there are no
2111 /// errors. Otherwise, returns a NULL type.
BuildPointerType(QualType T,SourceLocation Loc,DeclarationName Entity)2112 QualType Sema::BuildPointerType(QualType T,
2113                                 SourceLocation Loc, DeclarationName Entity) {
2114   if (T->isReferenceType()) {
2115     // C++ 8.3.2p4: There shall be no ... pointers to references ...
2116     Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
2117       << getPrintableNameForEntity(Entity) << T;
2118     return QualType();
2119   }
2120 
2121   if (T->isFunctionType() && getLangOpts().OpenCL &&
2122       !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2123                                             getLangOpts())) {
2124     Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
2125     return QualType();
2126   }
2127 
2128   if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
2129     return QualType();
2130 
2131   assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
2132 
2133   // In ARC, it is forbidden to build pointers to unqualified pointers.
2134   if (getLangOpts().ObjCAutoRefCount)
2135     T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
2136 
2137   if (getLangOpts().OpenCL)
2138     T = deduceOpenCLPointeeAddrSpace(*this, T);
2139 
2140   // Build the pointer type.
2141   return Context.getPointerType(T);
2142 }
2143 
2144 /// Build a reference type.
2145 ///
2146 /// \param T The type to which we'll be building a reference.
2147 ///
2148 /// \param Loc The location of the entity whose type involves this
2149 /// reference type or, if there is no such entity, the location of the
2150 /// type that will have reference type.
2151 ///
2152 /// \param Entity The name of the entity that involves the reference
2153 /// type, if known.
2154 ///
2155 /// \returns A suitable reference type, if there are no
2156 /// errors. Otherwise, returns a NULL type.
BuildReferenceType(QualType T,bool SpelledAsLValue,SourceLocation Loc,DeclarationName Entity)2157 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
2158                                   SourceLocation Loc,
2159                                   DeclarationName Entity) {
2160   assert(Context.getCanonicalType(T) != Context.OverloadTy &&
2161          "Unresolved overloaded function type");
2162 
2163   // C++0x [dcl.ref]p6:
2164   //   If a typedef (7.1.3), a type template-parameter (14.3.1), or a
2165   //   decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
2166   //   type T, an attempt to create the type "lvalue reference to cv TR" creates
2167   //   the type "lvalue reference to T", while an attempt to create the type
2168   //   "rvalue reference to cv TR" creates the type TR.
2169   bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
2170 
2171   // C++ [dcl.ref]p4: There shall be no references to references.
2172   //
2173   // According to C++ DR 106, references to references are only
2174   // diagnosed when they are written directly (e.g., "int & &"),
2175   // but not when they happen via a typedef:
2176   //
2177   //   typedef int& intref;
2178   //   typedef intref& intref2;
2179   //
2180   // Parser::ParseDeclaratorInternal diagnoses the case where
2181   // references are written directly; here, we handle the
2182   // collapsing of references-to-references as described in C++0x.
2183   // DR 106 and 540 introduce reference-collapsing into C++98/03.
2184 
2185   // C++ [dcl.ref]p1:
2186   //   A declarator that specifies the type "reference to cv void"
2187   //   is ill-formed.
2188   if (T->isVoidType()) {
2189     Diag(Loc, diag::err_reference_to_void);
2190     return QualType();
2191   }
2192 
2193   if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
2194     return QualType();
2195 
2196   if (T->isFunctionType() && getLangOpts().OpenCL &&
2197       !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2198                                             getLangOpts())) {
2199     Diag(Loc, diag::err_opencl_function_pointer) << /*reference*/ 1;
2200     return QualType();
2201   }
2202 
2203   // In ARC, it is forbidden to build references to unqualified pointers.
2204   if (getLangOpts().ObjCAutoRefCount)
2205     T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
2206 
2207   if (getLangOpts().OpenCL)
2208     T = deduceOpenCLPointeeAddrSpace(*this, T);
2209 
2210   // Handle restrict on references.
2211   if (LValueRef)
2212     return Context.getLValueReferenceType(T, SpelledAsLValue);
2213   return Context.getRValueReferenceType(T);
2214 }
2215 
2216 /// Build a Read-only Pipe type.
2217 ///
2218 /// \param T The type to which we'll be building a Pipe.
2219 ///
2220 /// \param Loc We do not use it for now.
2221 ///
2222 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2223 /// NULL type.
BuildReadPipeType(QualType T,SourceLocation Loc)2224 QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) {
2225   return Context.getReadPipeType(T);
2226 }
2227 
2228 /// Build a Write-only Pipe type.
2229 ///
2230 /// \param T The type to which we'll be building a Pipe.
2231 ///
2232 /// \param Loc We do not use it for now.
2233 ///
2234 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2235 /// NULL type.
BuildWritePipeType(QualType T,SourceLocation Loc)2236 QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) {
2237   return Context.getWritePipeType(T);
2238 }
2239 
2240 /// Build a extended int type.
2241 ///
2242 /// \param IsUnsigned Boolean representing the signedness of the type.
2243 ///
2244 /// \param BitWidth Size of this int type in bits, or an expression representing
2245 /// that.
2246 ///
2247 /// \param Loc Location of the keyword.
BuildExtIntType(bool IsUnsigned,Expr * BitWidth,SourceLocation Loc)2248 QualType Sema::BuildExtIntType(bool IsUnsigned, Expr *BitWidth,
2249                                SourceLocation Loc) {
2250   if (BitWidth->isInstantiationDependent())
2251     return Context.getDependentExtIntType(IsUnsigned, BitWidth);
2252 
2253   llvm::APSInt Bits(32);
2254   ExprResult ICE =
2255       VerifyIntegerConstantExpression(BitWidth, &Bits, /*FIXME*/ AllowFold);
2256 
2257   if (ICE.isInvalid())
2258     return QualType();
2259 
2260   int64_t NumBits = Bits.getSExtValue();
2261   if (!IsUnsigned && NumBits < 2) {
2262     Diag(Loc, diag::err_ext_int_bad_size) << 0;
2263     return QualType();
2264   }
2265 
2266   if (IsUnsigned && NumBits < 1) {
2267     Diag(Loc, diag::err_ext_int_bad_size) << 1;
2268     return QualType();
2269   }
2270 
2271   if (NumBits > llvm::IntegerType::MAX_INT_BITS) {
2272     Diag(Loc, diag::err_ext_int_max_size) << IsUnsigned
2273                                           << llvm::IntegerType::MAX_INT_BITS;
2274     return QualType();
2275   }
2276 
2277   return Context.getExtIntType(IsUnsigned, NumBits);
2278 }
2279 
2280 /// Check whether the specified array bound can be evaluated using the relevant
2281 /// language rules. If so, returns the possibly-converted expression and sets
2282 /// SizeVal to the size. If not, but the expression might be a VLA bound,
2283 /// returns ExprResult(). Otherwise, produces a diagnostic and returns
2284 /// ExprError().
checkArraySize(Sema & S,Expr * & ArraySize,llvm::APSInt & SizeVal,unsigned VLADiag,bool VLAIsError)2285 static ExprResult checkArraySize(Sema &S, Expr *&ArraySize,
2286                                  llvm::APSInt &SizeVal, unsigned VLADiag,
2287                                  bool VLAIsError) {
2288   if (S.getLangOpts().CPlusPlus14 &&
2289       (VLAIsError ||
2290        !ArraySize->getType()->isIntegralOrUnscopedEnumerationType())) {
2291     // C++14 [dcl.array]p1:
2292     //   The constant-expression shall be a converted constant expression of
2293     //   type std::size_t.
2294     //
2295     // Don't apply this rule if we might be forming a VLA: in that case, we
2296     // allow non-constant expressions and constant-folding. We only need to use
2297     // the converted constant expression rules (to properly convert the source)
2298     // when the source expression is of class type.
2299     return S.CheckConvertedConstantExpression(
2300         ArraySize, S.Context.getSizeType(), SizeVal, Sema::CCEK_ArrayBound);
2301   }
2302 
2303   // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2304   // (like gnu99, but not c99) accept any evaluatable value as an extension.
2305   class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2306   public:
2307     unsigned VLADiag;
2308     bool VLAIsError;
2309     bool IsVLA = false;
2310 
2311     VLADiagnoser(unsigned VLADiag, bool VLAIsError)
2312         : VLADiag(VLADiag), VLAIsError(VLAIsError) {}
2313 
2314     Sema::SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
2315                                                    QualType T) override {
2316       return S.Diag(Loc, diag::err_array_size_non_int) << T;
2317     }
2318 
2319     Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
2320                                                SourceLocation Loc) override {
2321       IsVLA = !VLAIsError;
2322       return S.Diag(Loc, VLADiag);
2323     }
2324 
2325     Sema::SemaDiagnosticBuilder diagnoseFold(Sema &S,
2326                                              SourceLocation Loc) override {
2327       return S.Diag(Loc, diag::ext_vla_folded_to_constant);
2328     }
2329   } Diagnoser(VLADiag, VLAIsError);
2330 
2331   ExprResult R =
2332       S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser);
2333   if (Diagnoser.IsVLA)
2334     return ExprResult();
2335   return R;
2336 }
2337 
2338 /// Build an array type.
2339 ///
2340 /// \param T The type of each element in the array.
2341 ///
2342 /// \param ASM C99 array size modifier (e.g., '*', 'static').
2343 ///
2344 /// \param ArraySize Expression describing the size of the array.
2345 ///
2346 /// \param Brackets The range from the opening '[' to the closing ']'.
2347 ///
2348 /// \param Entity The name of the entity that involves the array
2349 /// type, if known.
2350 ///
2351 /// \returns A suitable array type, if there are no errors. Otherwise,
2352 /// returns a NULL type.
BuildArrayType(QualType T,ArrayType::ArraySizeModifier ASM,Expr * ArraySize,unsigned Quals,SourceRange Brackets,DeclarationName Entity)2353 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2354                               Expr *ArraySize, unsigned Quals,
2355                               SourceRange Brackets, DeclarationName Entity) {
2356 
2357   SourceLocation Loc = Brackets.getBegin();
2358   if (getLangOpts().CPlusPlus) {
2359     // C++ [dcl.array]p1:
2360     //   T is called the array element type; this type shall not be a reference
2361     //   type, the (possibly cv-qualified) type void, a function type or an
2362     //   abstract class type.
2363     //
2364     // C++ [dcl.array]p3:
2365     //   When several "array of" specifications are adjacent, [...] only the
2366     //   first of the constant expressions that specify the bounds of the arrays
2367     //   may be omitted.
2368     //
2369     // Note: function types are handled in the common path with C.
2370     if (T->isReferenceType()) {
2371       Diag(Loc, diag::err_illegal_decl_array_of_references)
2372       << getPrintableNameForEntity(Entity) << T;
2373       return QualType();
2374     }
2375 
2376     if (T->isVoidType() || T->isIncompleteArrayType()) {
2377       Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 0 << T;
2378       return QualType();
2379     }
2380 
2381     if (RequireNonAbstractType(Brackets.getBegin(), T,
2382                                diag::err_array_of_abstract_type))
2383       return QualType();
2384 
2385     // Mentioning a member pointer type for an array type causes us to lock in
2386     // an inheritance model, even if it's inside an unused typedef.
2387     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2388       if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2389         if (!MPTy->getClass()->isDependentType())
2390           (void)isCompleteType(Loc, T);
2391 
2392   } else {
2393     // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2394     // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2395     if (RequireCompleteSizedType(Loc, T,
2396                                  diag::err_array_incomplete_or_sizeless_type))
2397       return QualType();
2398   }
2399 
2400   if (T->isSizelessType()) {
2401     Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 1 << T;
2402     return QualType();
2403   }
2404 
2405   if (T->isFunctionType()) {
2406     Diag(Loc, diag::err_illegal_decl_array_of_functions)
2407       << getPrintableNameForEntity(Entity) << T;
2408     return QualType();
2409   }
2410 
2411   if (const RecordType *EltTy = T->getAs<RecordType>()) {
2412     // If the element type is a struct or union that contains a variadic
2413     // array, accept it as a GNU extension: C99 6.7.2.1p2.
2414     if (EltTy->getDecl()->hasFlexibleArrayMember())
2415       Diag(Loc, diag::ext_flexible_array_in_array) << T;
2416   } else if (T->isObjCObjectType()) {
2417     Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2418     return QualType();
2419   }
2420 
2421   // Do placeholder conversions on the array size expression.
2422   if (ArraySize && ArraySize->hasPlaceholderType()) {
2423     ExprResult Result = CheckPlaceholderExpr(ArraySize);
2424     if (Result.isInvalid()) return QualType();
2425     ArraySize = Result.get();
2426   }
2427 
2428   // Do lvalue-to-rvalue conversions on the array size expression.
2429   if (ArraySize && !ArraySize->isPRValue()) {
2430     ExprResult Result = DefaultLvalueConversion(ArraySize);
2431     if (Result.isInvalid())
2432       return QualType();
2433 
2434     ArraySize = Result.get();
2435   }
2436 
2437   // C99 6.7.5.2p1: The size expression shall have integer type.
2438   // C++11 allows contextual conversions to such types.
2439   if (!getLangOpts().CPlusPlus11 &&
2440       ArraySize && !ArraySize->isTypeDependent() &&
2441       !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2442     Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2443         << ArraySize->getType() << ArraySize->getSourceRange();
2444     return QualType();
2445   }
2446 
2447   // VLAs always produce at least a -Wvla diagnostic, sometimes an error.
2448   unsigned VLADiag;
2449   bool VLAIsError;
2450   if (getLangOpts().OpenCL) {
2451     // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2452     VLADiag = diag::err_opencl_vla;
2453     VLAIsError = true;
2454   } else if (getLangOpts().C99) {
2455     VLADiag = diag::warn_vla_used;
2456     VLAIsError = false;
2457   } else if (isSFINAEContext()) {
2458     VLADiag = diag::err_vla_in_sfinae;
2459     VLAIsError = true;
2460   } else {
2461     VLADiag = diag::ext_vla;
2462     VLAIsError = false;
2463   }
2464 
2465   llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2466   if (!ArraySize) {
2467     if (ASM == ArrayType::Star) {
2468       Diag(Loc, VLADiag);
2469       if (VLAIsError)
2470         return QualType();
2471 
2472       T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2473     } else {
2474       T = Context.getIncompleteArrayType(T, ASM, Quals);
2475     }
2476   } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2477     T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2478   } else {
2479     ExprResult R =
2480         checkArraySize(*this, ArraySize, ConstVal, VLADiag, VLAIsError);
2481     if (R.isInvalid())
2482       return QualType();
2483 
2484     if (!R.isUsable()) {
2485       // C99: an array with a non-ICE size is a VLA. We accept any expression
2486       // that we can fold to a non-zero positive value as a non-VLA as an
2487       // extension.
2488       T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2489     } else if (!T->isDependentType() && !T->isIncompleteType() &&
2490                !T->isConstantSizeType()) {
2491       // C99: an array with an element type that has a non-constant-size is a
2492       // VLA.
2493       // FIXME: Add a note to explain why this isn't a VLA.
2494       Diag(Loc, VLADiag);
2495       if (VLAIsError)
2496         return QualType();
2497       T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2498     } else {
2499       // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2500       // have a value greater than zero.
2501       // In C++, this follows from narrowing conversions being disallowed.
2502       if (ConstVal.isSigned() && ConstVal.isNegative()) {
2503         if (Entity)
2504           Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size)
2505               << getPrintableNameForEntity(Entity)
2506               << ArraySize->getSourceRange();
2507         else
2508           Diag(ArraySize->getBeginLoc(),
2509                diag::err_typecheck_negative_array_size)
2510               << ArraySize->getSourceRange();
2511         return QualType();
2512       }
2513       if (ConstVal == 0) {
2514         // GCC accepts zero sized static arrays. We allow them when
2515         // we're not in a SFINAE context.
2516         Diag(ArraySize->getBeginLoc(),
2517              isSFINAEContext() ? diag::err_typecheck_zero_array_size
2518                                : diag::ext_typecheck_zero_array_size)
2519             << ArraySize->getSourceRange();
2520       }
2521 
2522       // Is the array too large?
2523       unsigned ActiveSizeBits =
2524           (!T->isDependentType() && !T->isVariablyModifiedType() &&
2525            !T->isIncompleteType() && !T->isUndeducedType())
2526               ? ConstantArrayType::getNumAddressingBits(Context, T, ConstVal)
2527               : ConstVal.getActiveBits();
2528       if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2529         Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2530             << toString(ConstVal, 10) << ArraySize->getSourceRange();
2531         return QualType();
2532       }
2533 
2534       T = Context.getConstantArrayType(T, ConstVal, ArraySize, ASM, Quals);
2535     }
2536   }
2537 
2538   if (T->isVariableArrayType() && !Context.getTargetInfo().isVLASupported()) {
2539     // CUDA device code and some other targets don't support VLAs.
2540     targetDiag(Loc, (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
2541                         ? diag::err_cuda_vla
2542                         : diag::err_vla_unsupported)
2543         << ((getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
2544                 ? CurrentCUDATarget()
2545                 : CFT_InvalidTarget);
2546   }
2547 
2548   // If this is not C99, diagnose array size modifiers on non-VLAs.
2549   if (!getLangOpts().C99 && !T->isVariableArrayType() &&
2550       (ASM != ArrayType::Normal || Quals != 0)) {
2551     Diag(Loc, getLangOpts().CPlusPlus ? diag::err_c99_array_usage_cxx
2552                                       : diag::ext_c99_array_usage)
2553         << ASM;
2554   }
2555 
2556   // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2557   // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2558   // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2559   if (getLangOpts().OpenCL) {
2560     const QualType ArrType = Context.getBaseElementType(T);
2561     if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2562         ArrType->isSamplerT() || ArrType->isImageType()) {
2563       Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2564       return QualType();
2565     }
2566   }
2567 
2568   return T;
2569 }
2570 
BuildVectorType(QualType CurType,Expr * SizeExpr,SourceLocation AttrLoc)2571 QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr,
2572                                SourceLocation AttrLoc) {
2573   // The base type must be integer (not Boolean or enumeration) or float, and
2574   // can't already be a vector.
2575   if ((!CurType->isDependentType() &&
2576        (!CurType->isBuiltinType() || CurType->isBooleanType() ||
2577         (!CurType->isIntegerType() && !CurType->isRealFloatingType()))) ||
2578       CurType->isArrayType()) {
2579     Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType;
2580     return QualType();
2581   }
2582 
2583   if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
2584     return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2585                                                VectorType::GenericVector);
2586 
2587   Optional<llvm::APSInt> VecSize = SizeExpr->getIntegerConstantExpr(Context);
2588   if (!VecSize) {
2589     Diag(AttrLoc, diag::err_attribute_argument_type)
2590         << "vector_size" << AANT_ArgumentIntegerConstant
2591         << SizeExpr->getSourceRange();
2592     return QualType();
2593   }
2594 
2595   if (CurType->isDependentType())
2596     return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2597                                                VectorType::GenericVector);
2598 
2599   // vecSize is specified in bytes - convert to bits.
2600   if (!VecSize->isIntN(61)) {
2601     // Bit size will overflow uint64.
2602     Diag(AttrLoc, diag::err_attribute_size_too_large)
2603         << SizeExpr->getSourceRange() << "vector";
2604     return QualType();
2605   }
2606   uint64_t VectorSizeBits = VecSize->getZExtValue() * 8;
2607   unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
2608 
2609   if (VectorSizeBits == 0) {
2610     Diag(AttrLoc, diag::err_attribute_zero_size)
2611         << SizeExpr->getSourceRange() << "vector";
2612     return QualType();
2613   }
2614 
2615   if (VectorSizeBits % TypeSize) {
2616     Diag(AttrLoc, diag::err_attribute_invalid_size)
2617         << SizeExpr->getSourceRange();
2618     return QualType();
2619   }
2620 
2621   if (VectorSizeBits / TypeSize > std::numeric_limits<uint32_t>::max()) {
2622     Diag(AttrLoc, diag::err_attribute_size_too_large)
2623         << SizeExpr->getSourceRange() << "vector";
2624     return QualType();
2625   }
2626 
2627   return Context.getVectorType(CurType, VectorSizeBits / TypeSize,
2628                                VectorType::GenericVector);
2629 }
2630 
2631 /// Build an ext-vector type.
2632 ///
2633 /// Run the required checks for the extended vector type.
BuildExtVectorType(QualType T,Expr * ArraySize,SourceLocation AttrLoc)2634 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
2635                                   SourceLocation AttrLoc) {
2636   // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2637   // in conjunction with complex types (pointers, arrays, functions, etc.).
2638   //
2639   // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2640   // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2641   // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2642   // of bool aren't allowed.
2643   if ((!T->isDependentType() && !T->isIntegerType() &&
2644        !T->isRealFloatingType()) ||
2645       T->isBooleanType()) {
2646     Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2647     return QualType();
2648   }
2649 
2650   if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2651     Optional<llvm::APSInt> vecSize = ArraySize->getIntegerConstantExpr(Context);
2652     if (!vecSize) {
2653       Diag(AttrLoc, diag::err_attribute_argument_type)
2654         << "ext_vector_type" << AANT_ArgumentIntegerConstant
2655         << ArraySize->getSourceRange();
2656       return QualType();
2657     }
2658 
2659     if (!vecSize->isIntN(32)) {
2660       Diag(AttrLoc, diag::err_attribute_size_too_large)
2661           << ArraySize->getSourceRange() << "vector";
2662       return QualType();
2663     }
2664     // Unlike gcc's vector_size attribute, the size is specified as the
2665     // number of elements, not the number of bytes.
2666     unsigned vectorSize = static_cast<unsigned>(vecSize->getZExtValue());
2667 
2668     if (vectorSize == 0) {
2669       Diag(AttrLoc, diag::err_attribute_zero_size)
2670           << ArraySize->getSourceRange() << "vector";
2671       return QualType();
2672     }
2673 
2674     return Context.getExtVectorType(T, vectorSize);
2675   }
2676 
2677   return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2678 }
2679 
BuildMatrixType(QualType ElementTy,Expr * NumRows,Expr * NumCols,SourceLocation AttrLoc)2680 QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols,
2681                                SourceLocation AttrLoc) {
2682   assert(Context.getLangOpts().MatrixTypes &&
2683          "Should never build a matrix type when it is disabled");
2684 
2685   // Check element type, if it is not dependent.
2686   if (!ElementTy->isDependentType() &&
2687       !MatrixType::isValidElementType(ElementTy)) {
2688     Diag(AttrLoc, diag::err_attribute_invalid_matrix_type) << ElementTy;
2689     return QualType();
2690   }
2691 
2692   if (NumRows->isTypeDependent() || NumCols->isTypeDependent() ||
2693       NumRows->isValueDependent() || NumCols->isValueDependent())
2694     return Context.getDependentSizedMatrixType(ElementTy, NumRows, NumCols,
2695                                                AttrLoc);
2696 
2697   Optional<llvm::APSInt> ValueRows = NumRows->getIntegerConstantExpr(Context);
2698   Optional<llvm::APSInt> ValueColumns =
2699       NumCols->getIntegerConstantExpr(Context);
2700 
2701   auto const RowRange = NumRows->getSourceRange();
2702   auto const ColRange = NumCols->getSourceRange();
2703 
2704   // Both are row and column expressions are invalid.
2705   if (!ValueRows && !ValueColumns) {
2706     Diag(AttrLoc, diag::err_attribute_argument_type)
2707         << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange
2708         << ColRange;
2709     return QualType();
2710   }
2711 
2712   // Only the row expression is invalid.
2713   if (!ValueRows) {
2714     Diag(AttrLoc, diag::err_attribute_argument_type)
2715         << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange;
2716     return QualType();
2717   }
2718 
2719   // Only the column expression is invalid.
2720   if (!ValueColumns) {
2721     Diag(AttrLoc, diag::err_attribute_argument_type)
2722         << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange;
2723     return QualType();
2724   }
2725 
2726   // Check the matrix dimensions.
2727   unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue());
2728   unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue());
2729   if (MatrixRows == 0 && MatrixColumns == 0) {
2730     Diag(AttrLoc, diag::err_attribute_zero_size)
2731         << "matrix" << RowRange << ColRange;
2732     return QualType();
2733   }
2734   if (MatrixRows == 0) {
2735     Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << RowRange;
2736     return QualType();
2737   }
2738   if (MatrixColumns == 0) {
2739     Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << ColRange;
2740     return QualType();
2741   }
2742   if (!ConstantMatrixType::isDimensionValid(MatrixRows)) {
2743     Diag(AttrLoc, diag::err_attribute_size_too_large)
2744         << RowRange << "matrix row";
2745     return QualType();
2746   }
2747   if (!ConstantMatrixType::isDimensionValid(MatrixColumns)) {
2748     Diag(AttrLoc, diag::err_attribute_size_too_large)
2749         << ColRange << "matrix column";
2750     return QualType();
2751   }
2752   return Context.getConstantMatrixType(ElementTy, MatrixRows, MatrixColumns);
2753 }
2754 
CheckFunctionReturnType(QualType T,SourceLocation Loc)2755 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2756   if (T->isArrayType() || T->isFunctionType()) {
2757     Diag(Loc, diag::err_func_returning_array_function)
2758       << T->isFunctionType() << T;
2759     return true;
2760   }
2761 
2762   // Functions cannot return half FP.
2763   if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2764     Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2765       FixItHint::CreateInsertion(Loc, "*");
2766     return true;
2767   }
2768 
2769   // Methods cannot return interface types. All ObjC objects are
2770   // passed by reference.
2771   if (T->isObjCObjectType()) {
2772     Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2773         << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2774     return true;
2775   }
2776 
2777   if (T.hasNonTrivialToPrimitiveDestructCUnion() ||
2778       T.hasNonTrivialToPrimitiveCopyCUnion())
2779     checkNonTrivialCUnion(T, Loc, NTCUC_FunctionReturn,
2780                           NTCUK_Destruct|NTCUK_Copy);
2781 
2782   // C++2a [dcl.fct]p12:
2783   //   A volatile-qualified return type is deprecated
2784   if (T.isVolatileQualified() && getLangOpts().CPlusPlus20)
2785     Diag(Loc, diag::warn_deprecated_volatile_return) << T;
2786 
2787   return false;
2788 }
2789 
2790 /// Check the extended parameter information.  Most of the necessary
2791 /// checking should occur when applying the parameter attribute; the
2792 /// only other checks required are positional restrictions.
checkExtParameterInfos(Sema & S,ArrayRef<QualType> paramTypes,const FunctionProtoType::ExtProtoInfo & EPI,llvm::function_ref<SourceLocation (unsigned)> getParamLoc)2793 static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes,
2794                     const FunctionProtoType::ExtProtoInfo &EPI,
2795                     llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2796   assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2797 
2798   bool emittedError = false;
2799   auto actualCC = EPI.ExtInfo.getCC();
2800   enum class RequiredCC { OnlySwift, SwiftOrSwiftAsync };
2801   auto checkCompatible = [&](unsigned paramIndex, RequiredCC required) {
2802     bool isCompatible =
2803         (required == RequiredCC::OnlySwift)
2804             ? (actualCC == CC_Swift)
2805             : (actualCC == CC_Swift || actualCC == CC_SwiftAsync);
2806     if (isCompatible || emittedError)
2807       return;
2808     S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2809         << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI())
2810         << (required == RequiredCC::OnlySwift);
2811     emittedError = true;
2812   };
2813   for (size_t paramIndex = 0, numParams = paramTypes.size();
2814           paramIndex != numParams; ++paramIndex) {
2815     switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2816     // Nothing interesting to check for orindary-ABI parameters.
2817     case ParameterABI::Ordinary:
2818       continue;
2819 
2820     // swift_indirect_result parameters must be a prefix of the function
2821     // arguments.
2822     case ParameterABI::SwiftIndirectResult:
2823       checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2824       if (paramIndex != 0 &&
2825           EPI.ExtParameterInfos[paramIndex - 1].getABI()
2826             != ParameterABI::SwiftIndirectResult) {
2827         S.Diag(getParamLoc(paramIndex),
2828                diag::err_swift_indirect_result_not_first);
2829       }
2830       continue;
2831 
2832     case ParameterABI::SwiftContext:
2833       checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2834       continue;
2835 
2836     // SwiftAsyncContext is not limited to swiftasynccall functions.
2837     case ParameterABI::SwiftAsyncContext:
2838       continue;
2839 
2840     // swift_error parameters must be preceded by a swift_context parameter.
2841     case ParameterABI::SwiftErrorResult:
2842       checkCompatible(paramIndex, RequiredCC::OnlySwift);
2843       if (paramIndex == 0 ||
2844           EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2845               ParameterABI::SwiftContext) {
2846         S.Diag(getParamLoc(paramIndex),
2847                diag::err_swift_error_result_not_after_swift_context);
2848       }
2849       continue;
2850     }
2851     llvm_unreachable("bad ABI kind");
2852   }
2853 }
2854 
BuildFunctionType(QualType T,MutableArrayRef<QualType> ParamTypes,SourceLocation Loc,DeclarationName Entity,const FunctionProtoType::ExtProtoInfo & EPI)2855 QualType Sema::BuildFunctionType(QualType T,
2856                                  MutableArrayRef<QualType> ParamTypes,
2857                                  SourceLocation Loc, DeclarationName Entity,
2858                                  const FunctionProtoType::ExtProtoInfo &EPI) {
2859   bool Invalid = false;
2860 
2861   Invalid |= CheckFunctionReturnType(T, Loc);
2862 
2863   for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2864     // FIXME: Loc is too inprecise here, should use proper locations for args.
2865     QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2866     if (ParamType->isVoidType()) {
2867       Diag(Loc, diag::err_param_with_void_type);
2868       Invalid = true;
2869     } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2870       // Disallow half FP arguments.
2871       Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2872         FixItHint::CreateInsertion(Loc, "*");
2873       Invalid = true;
2874     }
2875 
2876     // C++2a [dcl.fct]p4:
2877     //   A parameter with volatile-qualified type is deprecated
2878     if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus20)
2879       Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType;
2880 
2881     ParamTypes[Idx] = ParamType;
2882   }
2883 
2884   if (EPI.ExtParameterInfos) {
2885     checkExtParameterInfos(*this, ParamTypes, EPI,
2886                            [=](unsigned i) { return Loc; });
2887   }
2888 
2889   if (EPI.ExtInfo.getProducesResult()) {
2890     // This is just a warning, so we can't fail to build if we see it.
2891     checkNSReturnsRetainedReturnType(Loc, T);
2892   }
2893 
2894   if (Invalid)
2895     return QualType();
2896 
2897   return Context.getFunctionType(T, ParamTypes, EPI);
2898 }
2899 
2900 /// Build a member pointer type \c T Class::*.
2901 ///
2902 /// \param T the type to which the member pointer refers.
2903 /// \param Class the class type into which the member pointer points.
2904 /// \param Loc the location where this type begins
2905 /// \param Entity the name of the entity that will have this member pointer type
2906 ///
2907 /// \returns a member pointer type, if successful, or a NULL type if there was
2908 /// an error.
BuildMemberPointerType(QualType T,QualType Class,SourceLocation Loc,DeclarationName Entity)2909 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
2910                                       SourceLocation Loc,
2911                                       DeclarationName Entity) {
2912   // Verify that we're not building a pointer to pointer to function with
2913   // exception specification.
2914   if (CheckDistantExceptionSpec(T)) {
2915     Diag(Loc, diag::err_distant_exception_spec);
2916     return QualType();
2917   }
2918 
2919   // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2920   //   with reference type, or "cv void."
2921   if (T->isReferenceType()) {
2922     Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2923       << getPrintableNameForEntity(Entity) << T;
2924     return QualType();
2925   }
2926 
2927   if (T->isVoidType()) {
2928     Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2929       << getPrintableNameForEntity(Entity);
2930     return QualType();
2931   }
2932 
2933   if (!Class->isDependentType() && !Class->isRecordType()) {
2934     Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
2935     return QualType();
2936   }
2937 
2938   if (T->isFunctionType() && getLangOpts().OpenCL &&
2939       !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2940                                             getLangOpts())) {
2941     Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
2942     return QualType();
2943   }
2944 
2945   // Adjust the default free function calling convention to the default method
2946   // calling convention.
2947   bool IsCtorOrDtor =
2948       (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
2949       (Entity.getNameKind() == DeclarationName::CXXDestructorName);
2950   if (T->isFunctionType())
2951     adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
2952 
2953   return Context.getMemberPointerType(T, Class.getTypePtr());
2954 }
2955 
2956 /// Build a block pointer type.
2957 ///
2958 /// \param T The type to which we'll be building a block pointer.
2959 ///
2960 /// \param Loc The source location, used for diagnostics.
2961 ///
2962 /// \param Entity The name of the entity that involves the block pointer
2963 /// type, if known.
2964 ///
2965 /// \returns A suitable block pointer type, if there are no
2966 /// errors. Otherwise, returns a NULL type.
BuildBlockPointerType(QualType T,SourceLocation Loc,DeclarationName Entity)2967 QualType Sema::BuildBlockPointerType(QualType T,
2968                                      SourceLocation Loc,
2969                                      DeclarationName Entity) {
2970   if (!T->isFunctionType()) {
2971     Diag(Loc, diag::err_nonfunction_block_type);
2972     return QualType();
2973   }
2974 
2975   if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2976     return QualType();
2977 
2978   if (getLangOpts().OpenCL)
2979     T = deduceOpenCLPointeeAddrSpace(*this, T);
2980 
2981   return Context.getBlockPointerType(T);
2982 }
2983 
GetTypeFromParser(ParsedType Ty,TypeSourceInfo ** TInfo)2984 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
2985   QualType QT = Ty.get();
2986   if (QT.isNull()) {
2987     if (TInfo) *TInfo = nullptr;
2988     return QualType();
2989   }
2990 
2991   TypeSourceInfo *DI = nullptr;
2992   if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2993     QT = LIT->getType();
2994     DI = LIT->getTypeSourceInfo();
2995   }
2996 
2997   if (TInfo) *TInfo = DI;
2998   return QT;
2999 }
3000 
3001 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
3002                                             Qualifiers::ObjCLifetime ownership,
3003                                             unsigned chunkIndex);
3004 
3005 /// Given that this is the declaration of a parameter under ARC,
3006 /// attempt to infer attributes and such for pointer-to-whatever
3007 /// types.
inferARCWriteback(TypeProcessingState & state,QualType & declSpecType)3008 static void inferARCWriteback(TypeProcessingState &state,
3009                               QualType &declSpecType) {
3010   Sema &S = state.getSema();
3011   Declarator &declarator = state.getDeclarator();
3012 
3013   // TODO: should we care about decl qualifiers?
3014 
3015   // Check whether the declarator has the expected form.  We walk
3016   // from the inside out in order to make the block logic work.
3017   unsigned outermostPointerIndex = 0;
3018   bool isBlockPointer = false;
3019   unsigned numPointers = 0;
3020   for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
3021     unsigned chunkIndex = i;
3022     DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
3023     switch (chunk.Kind) {
3024     case DeclaratorChunk::Paren:
3025       // Ignore parens.
3026       break;
3027 
3028     case DeclaratorChunk::Reference:
3029     case DeclaratorChunk::Pointer:
3030       // Count the number of pointers.  Treat references
3031       // interchangeably as pointers; if they're mis-ordered, normal
3032       // type building will discover that.
3033       outermostPointerIndex = chunkIndex;
3034       numPointers++;
3035       break;
3036 
3037     case DeclaratorChunk::BlockPointer:
3038       // If we have a pointer to block pointer, that's an acceptable
3039       // indirect reference; anything else is not an application of
3040       // the rules.
3041       if (numPointers != 1) return;
3042       numPointers++;
3043       outermostPointerIndex = chunkIndex;
3044       isBlockPointer = true;
3045 
3046       // We don't care about pointer structure in return values here.
3047       goto done;
3048 
3049     case DeclaratorChunk::Array: // suppress if written (id[])?
3050     case DeclaratorChunk::Function:
3051     case DeclaratorChunk::MemberPointer:
3052     case DeclaratorChunk::Pipe:
3053       return;
3054     }
3055   }
3056  done:
3057 
3058   // If we have *one* pointer, then we want to throw the qualifier on
3059   // the declaration-specifiers, which means that it needs to be a
3060   // retainable object type.
3061   if (numPointers == 1) {
3062     // If it's not a retainable object type, the rule doesn't apply.
3063     if (!declSpecType->isObjCRetainableType()) return;
3064 
3065     // If it already has lifetime, don't do anything.
3066     if (declSpecType.getObjCLifetime()) return;
3067 
3068     // Otherwise, modify the type in-place.
3069     Qualifiers qs;
3070 
3071     if (declSpecType->isObjCARCImplicitlyUnretainedType())
3072       qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
3073     else
3074       qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
3075     declSpecType = S.Context.getQualifiedType(declSpecType, qs);
3076 
3077   // If we have *two* pointers, then we want to throw the qualifier on
3078   // the outermost pointer.
3079   } else if (numPointers == 2) {
3080     // If we don't have a block pointer, we need to check whether the
3081     // declaration-specifiers gave us something that will turn into a
3082     // retainable object pointer after we slap the first pointer on it.
3083     if (!isBlockPointer && !declSpecType->isObjCObjectType())
3084       return;
3085 
3086     // Look for an explicit lifetime attribute there.
3087     DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
3088     if (chunk.Kind != DeclaratorChunk::Pointer &&
3089         chunk.Kind != DeclaratorChunk::BlockPointer)
3090       return;
3091     for (const ParsedAttr &AL : chunk.getAttrs())
3092       if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
3093         return;
3094 
3095     transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
3096                                           outermostPointerIndex);
3097 
3098   // Any other number of pointers/references does not trigger the rule.
3099   } else return;
3100 
3101   // TODO: mark whether we did this inference?
3102 }
3103 
diagnoseIgnoredQualifiers(unsigned DiagID,unsigned Quals,SourceLocation FallbackLoc,SourceLocation ConstQualLoc,SourceLocation VolatileQualLoc,SourceLocation RestrictQualLoc,SourceLocation AtomicQualLoc,SourceLocation UnalignedQualLoc)3104 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
3105                                      SourceLocation FallbackLoc,
3106                                      SourceLocation ConstQualLoc,
3107                                      SourceLocation VolatileQualLoc,
3108                                      SourceLocation RestrictQualLoc,
3109                                      SourceLocation AtomicQualLoc,
3110                                      SourceLocation UnalignedQualLoc) {
3111   if (!Quals)
3112     return;
3113 
3114   struct Qual {
3115     const char *Name;
3116     unsigned Mask;
3117     SourceLocation Loc;
3118   } const QualKinds[5] = {
3119     { "const", DeclSpec::TQ_const, ConstQualLoc },
3120     { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
3121     { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
3122     { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
3123     { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
3124   };
3125 
3126   SmallString<32> QualStr;
3127   unsigned NumQuals = 0;
3128   SourceLocation Loc;
3129   FixItHint FixIts[5];
3130 
3131   // Build a string naming the redundant qualifiers.
3132   for (auto &E : QualKinds) {
3133     if (Quals & E.Mask) {
3134       if (!QualStr.empty()) QualStr += ' ';
3135       QualStr += E.Name;
3136 
3137       // If we have a location for the qualifier, offer a fixit.
3138       SourceLocation QualLoc = E.Loc;
3139       if (QualLoc.isValid()) {
3140         FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
3141         if (Loc.isInvalid() ||
3142             getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
3143           Loc = QualLoc;
3144       }
3145 
3146       ++NumQuals;
3147     }
3148   }
3149 
3150   Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
3151     << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
3152 }
3153 
3154 // Diagnose pointless type qualifiers on the return type of a function.
diagnoseRedundantReturnTypeQualifiers(Sema & S,QualType RetTy,Declarator & D,unsigned FunctionChunkIndex)3155 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
3156                                                   Declarator &D,
3157                                                   unsigned FunctionChunkIndex) {
3158   const DeclaratorChunk::FunctionTypeInfo &FTI =
3159       D.getTypeObject(FunctionChunkIndex).Fun;
3160   if (FTI.hasTrailingReturnType()) {
3161     S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3162                                 RetTy.getLocalCVRQualifiers(),
3163                                 FTI.getTrailingReturnTypeLoc());
3164     return;
3165   }
3166 
3167   for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
3168                 End = D.getNumTypeObjects();
3169        OuterChunkIndex != End; ++OuterChunkIndex) {
3170     DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
3171     switch (OuterChunk.Kind) {
3172     case DeclaratorChunk::Paren:
3173       continue;
3174 
3175     case DeclaratorChunk::Pointer: {
3176       DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
3177       S.diagnoseIgnoredQualifiers(
3178           diag::warn_qual_return_type,
3179           PTI.TypeQuals,
3180           SourceLocation(),
3181           PTI.ConstQualLoc,
3182           PTI.VolatileQualLoc,
3183           PTI.RestrictQualLoc,
3184           PTI.AtomicQualLoc,
3185           PTI.UnalignedQualLoc);
3186       return;
3187     }
3188 
3189     case DeclaratorChunk::Function:
3190     case DeclaratorChunk::BlockPointer:
3191     case DeclaratorChunk::Reference:
3192     case DeclaratorChunk::Array:
3193     case DeclaratorChunk::MemberPointer:
3194     case DeclaratorChunk::Pipe:
3195       // FIXME: We can't currently provide an accurate source location and a
3196       // fix-it hint for these.
3197       unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
3198       S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3199                                   RetTy.getCVRQualifiers() | AtomicQual,
3200                                   D.getIdentifierLoc());
3201       return;
3202     }
3203 
3204     llvm_unreachable("unknown declarator chunk kind");
3205   }
3206 
3207   // If the qualifiers come from a conversion function type, don't diagnose
3208   // them -- they're not necessarily redundant, since such a conversion
3209   // operator can be explicitly called as "x.operator const int()".
3210   if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3211     return;
3212 
3213   // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
3214   // which are present there.
3215   S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3216                               D.getDeclSpec().getTypeQualifiers(),
3217                               D.getIdentifierLoc(),
3218                               D.getDeclSpec().getConstSpecLoc(),
3219                               D.getDeclSpec().getVolatileSpecLoc(),
3220                               D.getDeclSpec().getRestrictSpecLoc(),
3221                               D.getDeclSpec().getAtomicSpecLoc(),
3222                               D.getDeclSpec().getUnalignedSpecLoc());
3223 }
3224 
3225 static std::pair<QualType, TypeSourceInfo *>
InventTemplateParameter(TypeProcessingState & state,QualType T,TypeSourceInfo * TrailingTSI,AutoType * Auto,InventedTemplateParameterInfo & Info)3226 InventTemplateParameter(TypeProcessingState &state, QualType T,
3227                         TypeSourceInfo *TrailingTSI, AutoType *Auto,
3228                         InventedTemplateParameterInfo &Info) {
3229   Sema &S = state.getSema();
3230   Declarator &D = state.getDeclarator();
3231 
3232   const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth;
3233   const unsigned AutoParameterPosition = Info.TemplateParams.size();
3234   const bool IsParameterPack = D.hasEllipsis();
3235 
3236   // If auto is mentioned in a lambda parameter or abbreviated function
3237   // template context, convert it to a template parameter type.
3238 
3239   // Create the TemplateTypeParmDecl here to retrieve the corresponding
3240   // template parameter type. Template parameters are temporarily added
3241   // to the TU until the associated TemplateDecl is created.
3242   TemplateTypeParmDecl *InventedTemplateParam =
3243       TemplateTypeParmDecl::Create(
3244           S.Context, S.Context.getTranslationUnitDecl(),
3245           /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(),
3246           /*NameLoc=*/D.getIdentifierLoc(),
3247           TemplateParameterDepth, AutoParameterPosition,
3248           S.InventAbbreviatedTemplateParameterTypeName(
3249               D.getIdentifier(), AutoParameterPosition), false,
3250           IsParameterPack, /*HasTypeConstraint=*/Auto->isConstrained());
3251   InventedTemplateParam->setImplicit();
3252   Info.TemplateParams.push_back(InventedTemplateParam);
3253 
3254   // Attach type constraints to the new parameter.
3255   if (Auto->isConstrained()) {
3256     if (TrailingTSI) {
3257       // The 'auto' appears in a trailing return type we've already built;
3258       // extract its type constraints to attach to the template parameter.
3259       AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc();
3260       TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc());
3261       bool Invalid = false;
3262       for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx) {
3263         if (D.getEllipsisLoc().isInvalid() && !Invalid &&
3264             S.DiagnoseUnexpandedParameterPack(AutoLoc.getArgLoc(Idx),
3265                                               Sema::UPPC_TypeConstraint))
3266           Invalid = true;
3267         TAL.addArgument(AutoLoc.getArgLoc(Idx));
3268       }
3269 
3270       if (!Invalid) {
3271         S.AttachTypeConstraint(
3272             AutoLoc.getNestedNameSpecifierLoc(), AutoLoc.getConceptNameInfo(),
3273             AutoLoc.getNamedConcept(),
3274             AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr,
3275             InventedTemplateParam, D.getEllipsisLoc());
3276       }
3277     } else {
3278       // The 'auto' appears in the decl-specifiers; we've not finished forming
3279       // TypeSourceInfo for it yet.
3280       TemplateIdAnnotation *TemplateId = D.getDeclSpec().getRepAsTemplateId();
3281       TemplateArgumentListInfo TemplateArgsInfo;
3282       bool Invalid = false;
3283       if (TemplateId->LAngleLoc.isValid()) {
3284         ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
3285                                            TemplateId->NumArgs);
3286         S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
3287 
3288         if (D.getEllipsisLoc().isInvalid()) {
3289           for (TemplateArgumentLoc Arg : TemplateArgsInfo.arguments()) {
3290             if (S.DiagnoseUnexpandedParameterPack(Arg,
3291                                                   Sema::UPPC_TypeConstraint)) {
3292               Invalid = true;
3293               break;
3294             }
3295           }
3296         }
3297       }
3298       if (!Invalid) {
3299         S.AttachTypeConstraint(
3300             D.getDeclSpec().getTypeSpecScope().getWithLocInContext(S.Context),
3301             DeclarationNameInfo(DeclarationName(TemplateId->Name),
3302                                 TemplateId->TemplateNameLoc),
3303             cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl()),
3304             TemplateId->LAngleLoc.isValid() ? &TemplateArgsInfo : nullptr,
3305             InventedTemplateParam, D.getEllipsisLoc());
3306       }
3307     }
3308   }
3309 
3310   // Replace the 'auto' in the function parameter with this invented
3311   // template type parameter.
3312   // FIXME: Retain some type sugar to indicate that this was written
3313   //  as 'auto'?
3314   QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0);
3315   QualType NewT = state.ReplaceAutoType(T, Replacement);
3316   TypeSourceInfo *NewTSI =
3317       TrailingTSI ? S.ReplaceAutoTypeSourceInfo(TrailingTSI, Replacement)
3318                   : nullptr;
3319   return {NewT, NewTSI};
3320 }
3321 
3322 static TypeSourceInfo *
3323 GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3324                                QualType T, TypeSourceInfo *ReturnTypeInfo);
3325 
GetDeclSpecTypeForDeclarator(TypeProcessingState & state,TypeSourceInfo * & ReturnTypeInfo)3326 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
3327                                              TypeSourceInfo *&ReturnTypeInfo) {
3328   Sema &SemaRef = state.getSema();
3329   Declarator &D = state.getDeclarator();
3330   QualType T;
3331   ReturnTypeInfo = nullptr;
3332 
3333   // The TagDecl owned by the DeclSpec.
3334   TagDecl *OwnedTagDecl = nullptr;
3335 
3336   switch (D.getName().getKind()) {
3337   case UnqualifiedIdKind::IK_ImplicitSelfParam:
3338   case UnqualifiedIdKind::IK_OperatorFunctionId:
3339   case UnqualifiedIdKind::IK_Identifier:
3340   case UnqualifiedIdKind::IK_LiteralOperatorId:
3341   case UnqualifiedIdKind::IK_TemplateId:
3342     T = ConvertDeclSpecToType(state);
3343 
3344     if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
3345       OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3346       // Owned declaration is embedded in declarator.
3347       OwnedTagDecl->setEmbeddedInDeclarator(true);
3348     }
3349     break;
3350 
3351   case UnqualifiedIdKind::IK_ConstructorName:
3352   case UnqualifiedIdKind::IK_ConstructorTemplateId:
3353   case UnqualifiedIdKind::IK_DestructorName:
3354     // Constructors and destructors don't have return types. Use
3355     // "void" instead.
3356     T = SemaRef.Context.VoidTy;
3357     processTypeAttrs(state, T, TAL_DeclSpec,
3358                      D.getMutableDeclSpec().getAttributes());
3359     break;
3360 
3361   case UnqualifiedIdKind::IK_DeductionGuideName:
3362     // Deduction guides have a trailing return type and no type in their
3363     // decl-specifier sequence. Use a placeholder return type for now.
3364     T = SemaRef.Context.DependentTy;
3365     break;
3366 
3367   case UnqualifiedIdKind::IK_ConversionFunctionId:
3368     // The result type of a conversion function is the type that it
3369     // converts to.
3370     T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
3371                                   &ReturnTypeInfo);
3372     break;
3373   }
3374 
3375   if (!D.getAttributes().empty())
3376     distributeTypeAttrsFromDeclarator(state, T);
3377 
3378   // Find the deduced type in this type. Look in the trailing return type if we
3379   // have one, otherwise in the DeclSpec type.
3380   // FIXME: The standard wording doesn't currently describe this.
3381   DeducedType *Deduced = T->getContainedDeducedType();
3382   bool DeducedIsTrailingReturnType = false;
3383   if (Deduced && isa<AutoType>(Deduced) && D.hasTrailingReturnType()) {
3384     QualType T = SemaRef.GetTypeFromParser(D.getTrailingReturnType());
3385     Deduced = T.isNull() ? nullptr : T->getContainedDeducedType();
3386     DeducedIsTrailingReturnType = true;
3387   }
3388 
3389   // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
3390   if (Deduced) {
3391     AutoType *Auto = dyn_cast<AutoType>(Deduced);
3392     int Error = -1;
3393 
3394     // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
3395     // class template argument deduction)?
3396     bool IsCXXAutoType =
3397         (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
3398     bool IsDeducedReturnType = false;
3399 
3400     switch (D.getContext()) {
3401     case DeclaratorContext::LambdaExpr:
3402       // Declared return type of a lambda-declarator is implicit and is always
3403       // 'auto'.
3404       break;
3405     case DeclaratorContext::ObjCParameter:
3406     case DeclaratorContext::ObjCResult:
3407       Error = 0;
3408       break;
3409     case DeclaratorContext::RequiresExpr:
3410       Error = 22;
3411       break;
3412     case DeclaratorContext::Prototype:
3413     case DeclaratorContext::LambdaExprParameter: {
3414       InventedTemplateParameterInfo *Info = nullptr;
3415       if (D.getContext() == DeclaratorContext::Prototype) {
3416         // With concepts we allow 'auto' in function parameters.
3417         if (!SemaRef.getLangOpts().CPlusPlus20 || !Auto ||
3418             Auto->getKeyword() != AutoTypeKeyword::Auto) {
3419           Error = 0;
3420           break;
3421         } else if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) {
3422           Error = 21;
3423           break;
3424         }
3425 
3426         Info = &SemaRef.InventedParameterInfos.back();
3427       } else {
3428         // In C++14, generic lambdas allow 'auto' in their parameters.
3429         if (!SemaRef.getLangOpts().CPlusPlus14 || !Auto ||
3430             Auto->getKeyword() != AutoTypeKeyword::Auto) {
3431           Error = 16;
3432           break;
3433         }
3434         Info = SemaRef.getCurLambda();
3435         assert(Info && "No LambdaScopeInfo on the stack!");
3436       }
3437 
3438       // We'll deal with inventing template parameters for 'auto' in trailing
3439       // return types when we pick up the trailing return type when processing
3440       // the function chunk.
3441       if (!DeducedIsTrailingReturnType)
3442         T = InventTemplateParameter(state, T, nullptr, Auto, *Info).first;
3443       break;
3444     }
3445     case DeclaratorContext::Member: {
3446       if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
3447           D.isFunctionDeclarator())
3448         break;
3449       bool Cxx = SemaRef.getLangOpts().CPlusPlus;
3450       if (isa<ObjCContainerDecl>(SemaRef.CurContext)) {
3451         Error = 6; // Interface member.
3452       } else {
3453         switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
3454         case TTK_Enum: llvm_unreachable("unhandled tag kind");
3455         case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
3456         case TTK_Union:  Error = Cxx ? 3 : 4; /* Union member */ break;
3457         case TTK_Class:  Error = 5; /* Class member */ break;
3458         case TTK_Interface: Error = 6; /* Interface member */ break;
3459         }
3460       }
3461       if (D.getDeclSpec().isFriendSpecified())
3462         Error = 20; // Friend type
3463       break;
3464     }
3465     case DeclaratorContext::CXXCatch:
3466     case DeclaratorContext::ObjCCatch:
3467       Error = 7; // Exception declaration
3468       break;
3469     case DeclaratorContext::TemplateParam:
3470       if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3471           !SemaRef.getLangOpts().CPlusPlus20)
3472         Error = 19; // Template parameter (until C++20)
3473       else if (!SemaRef.getLangOpts().CPlusPlus17)
3474         Error = 8; // Template parameter (until C++17)
3475       break;
3476     case DeclaratorContext::BlockLiteral:
3477       Error = 9; // Block literal
3478       break;
3479     case DeclaratorContext::TemplateArg:
3480       // Within a template argument list, a deduced template specialization
3481       // type will be reinterpreted as a template template argument.
3482       if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3483           !D.getNumTypeObjects() &&
3484           D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier)
3485         break;
3486       LLVM_FALLTHROUGH;
3487     case DeclaratorContext::TemplateTypeArg:
3488       Error = 10; // Template type argument
3489       break;
3490     case DeclaratorContext::AliasDecl:
3491     case DeclaratorContext::AliasTemplate:
3492       Error = 12; // Type alias
3493       break;
3494     case DeclaratorContext::TrailingReturn:
3495     case DeclaratorContext::TrailingReturnVar:
3496       if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3497         Error = 13; // Function return type
3498       IsDeducedReturnType = true;
3499       break;
3500     case DeclaratorContext::ConversionId:
3501       if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3502         Error = 14; // conversion-type-id
3503       IsDeducedReturnType = true;
3504       break;
3505     case DeclaratorContext::FunctionalCast:
3506       if (isa<DeducedTemplateSpecializationType>(Deduced))
3507         break;
3508       LLVM_FALLTHROUGH;
3509     case DeclaratorContext::TypeName:
3510       Error = 15; // Generic
3511       break;
3512     case DeclaratorContext::File:
3513     case DeclaratorContext::Block:
3514     case DeclaratorContext::ForInit:
3515     case DeclaratorContext::SelectionInit:
3516     case DeclaratorContext::Condition:
3517       // FIXME: P0091R3 (erroneously) does not permit class template argument
3518       // deduction in conditions, for-init-statements, and other declarations
3519       // that are not simple-declarations.
3520       break;
3521     case DeclaratorContext::CXXNew:
3522       // FIXME: P0091R3 does not permit class template argument deduction here,
3523       // but we follow GCC and allow it anyway.
3524       if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
3525         Error = 17; // 'new' type
3526       break;
3527     case DeclaratorContext::KNRTypeList:
3528       Error = 18; // K&R function parameter
3529       break;
3530     }
3531 
3532     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3533       Error = 11;
3534 
3535     // In Objective-C it is an error to use 'auto' on a function declarator
3536     // (and everywhere for '__auto_type').
3537     if (D.isFunctionDeclarator() &&
3538         (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
3539       Error = 13;
3540 
3541     SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
3542     if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3543       AutoRange = D.getName().getSourceRange();
3544 
3545     if (Error != -1) {
3546       unsigned Kind;
3547       if (Auto) {
3548         switch (Auto->getKeyword()) {
3549         case AutoTypeKeyword::Auto: Kind = 0; break;
3550         case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3551         case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3552         }
3553       } else {
3554         assert(isa<DeducedTemplateSpecializationType>(Deduced) &&
3555                "unknown auto type");
3556         Kind = 3;
3557       }
3558 
3559       auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3560       TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
3561 
3562       SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3563         << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3564         << QualType(Deduced, 0) << AutoRange;
3565       if (auto *TD = TN.getAsTemplateDecl())
3566         SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
3567 
3568       T = SemaRef.Context.IntTy;
3569       D.setInvalidType(true);
3570     } else if (Auto && D.getContext() != DeclaratorContext::LambdaExpr) {
3571       // If there was a trailing return type, we already got
3572       // warn_cxx98_compat_trailing_return_type in the parser.
3573       SemaRef.Diag(AutoRange.getBegin(),
3574                    D.getContext() == DeclaratorContext::LambdaExprParameter
3575                        ? diag::warn_cxx11_compat_generic_lambda
3576                    : IsDeducedReturnType
3577                        ? diag::warn_cxx11_compat_deduced_return_type
3578                        : diag::warn_cxx98_compat_auto_type_specifier)
3579           << AutoRange;
3580     }
3581   }
3582 
3583   if (SemaRef.getLangOpts().CPlusPlus &&
3584       OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
3585     // Check the contexts where C++ forbids the declaration of a new class
3586     // or enumeration in a type-specifier-seq.
3587     unsigned DiagID = 0;
3588     switch (D.getContext()) {
3589     case DeclaratorContext::TrailingReturn:
3590     case DeclaratorContext::TrailingReturnVar:
3591       // Class and enumeration definitions are syntactically not allowed in
3592       // trailing return types.
3593       llvm_unreachable("parser should not have allowed this");
3594       break;
3595     case DeclaratorContext::File:
3596     case DeclaratorContext::Member:
3597     case DeclaratorContext::Block:
3598     case DeclaratorContext::ForInit:
3599     case DeclaratorContext::SelectionInit:
3600     case DeclaratorContext::BlockLiteral:
3601     case DeclaratorContext::LambdaExpr:
3602       // C++11 [dcl.type]p3:
3603       //   A type-specifier-seq shall not define a class or enumeration unless
3604       //   it appears in the type-id of an alias-declaration (7.1.3) that is not
3605       //   the declaration of a template-declaration.
3606     case DeclaratorContext::AliasDecl:
3607       break;
3608     case DeclaratorContext::AliasTemplate:
3609       DiagID = diag::err_type_defined_in_alias_template;
3610       break;
3611     case DeclaratorContext::TypeName:
3612     case DeclaratorContext::FunctionalCast:
3613     case DeclaratorContext::ConversionId:
3614     case DeclaratorContext::TemplateParam:
3615     case DeclaratorContext::CXXNew:
3616     case DeclaratorContext::CXXCatch:
3617     case DeclaratorContext::ObjCCatch:
3618     case DeclaratorContext::TemplateArg:
3619     case DeclaratorContext::TemplateTypeArg:
3620       DiagID = diag::err_type_defined_in_type_specifier;
3621       break;
3622     case DeclaratorContext::Prototype:
3623     case DeclaratorContext::LambdaExprParameter:
3624     case DeclaratorContext::ObjCParameter:
3625     case DeclaratorContext::ObjCResult:
3626     case DeclaratorContext::KNRTypeList:
3627     case DeclaratorContext::RequiresExpr:
3628       // C++ [dcl.fct]p6:
3629       //   Types shall not be defined in return or parameter types.
3630       DiagID = diag::err_type_defined_in_param_type;
3631       break;
3632     case DeclaratorContext::Condition:
3633       // C++ 6.4p2:
3634       // The type-specifier-seq shall not contain typedef and shall not declare
3635       // a new class or enumeration.
3636       DiagID = diag::err_type_defined_in_condition;
3637       break;
3638     }
3639 
3640     if (DiagID != 0) {
3641       SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3642           << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
3643       D.setInvalidType(true);
3644     }
3645   }
3646 
3647   assert(!T.isNull() && "This function should not return a null type");
3648   return T;
3649 }
3650 
3651 /// Produce an appropriate diagnostic for an ambiguity between a function
3652 /// declarator and a C++ direct-initializer.
warnAboutAmbiguousFunction(Sema & S,Declarator & D,DeclaratorChunk & DeclType,QualType RT)3653 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
3654                                        DeclaratorChunk &DeclType, QualType RT) {
3655   const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3656   assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3657 
3658   // If the return type is void there is no ambiguity.
3659   if (RT->isVoidType())
3660     return;
3661 
3662   // An initializer for a non-class type can have at most one argument.
3663   if (!RT->isRecordType() && FTI.NumParams > 1)
3664     return;
3665 
3666   // An initializer for a reference must have exactly one argument.
3667   if (RT->isReferenceType() && FTI.NumParams != 1)
3668     return;
3669 
3670   // Only warn if this declarator is declaring a function at block scope, and
3671   // doesn't have a storage class (such as 'extern') specified.
3672   if (!D.isFunctionDeclarator() ||
3673       D.getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration ||
3674       !S.CurContext->isFunctionOrMethod() ||
3675       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_unspecified)
3676     return;
3677 
3678   // Inside a condition, a direct initializer is not permitted. We allow one to
3679   // be parsed in order to give better diagnostics in condition parsing.
3680   if (D.getContext() == DeclaratorContext::Condition)
3681     return;
3682 
3683   SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3684 
3685   S.Diag(DeclType.Loc,
3686          FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3687                        : diag::warn_empty_parens_are_function_decl)
3688       << ParenRange;
3689 
3690   // If the declaration looks like:
3691   //   T var1,
3692   //   f();
3693   // and name lookup finds a function named 'f', then the ',' was
3694   // probably intended to be a ';'.
3695   if (!D.isFirstDeclarator() && D.getIdentifier()) {
3696     FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3697     FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
3698     if (Comma.getFileID() != Name.getFileID() ||
3699         Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3700       LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3701                           Sema::LookupOrdinaryName);
3702       if (S.LookupName(Result, S.getCurScope()))
3703         S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3704           << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
3705           << D.getIdentifier();
3706       Result.suppressDiagnostics();
3707     }
3708   }
3709 
3710   if (FTI.NumParams > 0) {
3711     // For a declaration with parameters, eg. "T var(T());", suggest adding
3712     // parens around the first parameter to turn the declaration into a
3713     // variable declaration.
3714     SourceRange Range = FTI.Params[0].Param->getSourceRange();
3715     SourceLocation B = Range.getBegin();
3716     SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3717     // FIXME: Maybe we should suggest adding braces instead of parens
3718     // in C++11 for classes that don't have an initializer_list constructor.
3719     S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3720       << FixItHint::CreateInsertion(B, "(")
3721       << FixItHint::CreateInsertion(E, ")");
3722   } else {
3723     // For a declaration without parameters, eg. "T var();", suggest replacing
3724     // the parens with an initializer to turn the declaration into a variable
3725     // declaration.
3726     const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3727 
3728     // Empty parens mean value-initialization, and no parens mean
3729     // default initialization. These are equivalent if the default
3730     // constructor is user-provided or if zero-initialization is a
3731     // no-op.
3732     if (RD && RD->hasDefinition() &&
3733         (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
3734       S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3735         << FixItHint::CreateRemoval(ParenRange);
3736     else {
3737       std::string Init =
3738           S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3739       if (Init.empty() && S.LangOpts.CPlusPlus11)
3740         Init = "{}";
3741       if (!Init.empty())
3742         S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3743           << FixItHint::CreateReplacement(ParenRange, Init);
3744     }
3745   }
3746 }
3747 
3748 /// Produce an appropriate diagnostic for a declarator with top-level
3749 /// parentheses.
warnAboutRedundantParens(Sema & S,Declarator & D,QualType T)3750 static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) {
3751   DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1);
3752   assert(Paren.Kind == DeclaratorChunk::Paren &&
3753          "do not have redundant top-level parentheses");
3754 
3755   // This is a syntactic check; we're not interested in cases that arise
3756   // during template instantiation.
3757   if (S.inTemplateInstantiation())
3758     return;
3759 
3760   // Check whether this could be intended to be a construction of a temporary
3761   // object in C++ via a function-style cast.
3762   bool CouldBeTemporaryObject =
3763       S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
3764       !D.isInvalidType() && D.getIdentifier() &&
3765       D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
3766       (T->isRecordType() || T->isDependentType()) &&
3767       D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator();
3768 
3769   bool StartsWithDeclaratorId = true;
3770   for (auto &C : D.type_objects()) {
3771     switch (C.Kind) {
3772     case DeclaratorChunk::Paren:
3773       if (&C == &Paren)
3774         continue;
3775       LLVM_FALLTHROUGH;
3776     case DeclaratorChunk::Pointer:
3777       StartsWithDeclaratorId = false;
3778       continue;
3779 
3780     case DeclaratorChunk::Array:
3781       if (!C.Arr.NumElts)
3782         CouldBeTemporaryObject = false;
3783       continue;
3784 
3785     case DeclaratorChunk::Reference:
3786       // FIXME: Suppress the warning here if there is no initializer; we're
3787       // going to give an error anyway.
3788       // We assume that something like 'T (&x) = y;' is highly likely to not
3789       // be intended to be a temporary object.
3790       CouldBeTemporaryObject = false;
3791       StartsWithDeclaratorId = false;
3792       continue;
3793 
3794     case DeclaratorChunk::Function:
3795       // In a new-type-id, function chunks require parentheses.
3796       if (D.getContext() == DeclaratorContext::CXXNew)
3797         return;
3798       // FIXME: "A(f())" deserves a vexing-parse warning, not just a
3799       // redundant-parens warning, but we don't know whether the function
3800       // chunk was syntactically valid as an expression here.
3801       CouldBeTemporaryObject = false;
3802       continue;
3803 
3804     case DeclaratorChunk::BlockPointer:
3805     case DeclaratorChunk::MemberPointer:
3806     case DeclaratorChunk::Pipe:
3807       // These cannot appear in expressions.
3808       CouldBeTemporaryObject = false;
3809       StartsWithDeclaratorId = false;
3810       continue;
3811     }
3812   }
3813 
3814   // FIXME: If there is an initializer, assume that this is not intended to be
3815   // a construction of a temporary object.
3816 
3817   // Check whether the name has already been declared; if not, this is not a
3818   // function-style cast.
3819   if (CouldBeTemporaryObject) {
3820     LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3821                         Sema::LookupOrdinaryName);
3822     if (!S.LookupName(Result, S.getCurScope()))
3823       CouldBeTemporaryObject = false;
3824     Result.suppressDiagnostics();
3825   }
3826 
3827   SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
3828 
3829   if (!CouldBeTemporaryObject) {
3830     // If we have A (::B), the parentheses affect the meaning of the program.
3831     // Suppress the warning in that case. Don't bother looking at the DeclSpec
3832     // here: even (e.g.) "int ::x" is visually ambiguous even though it's
3833     // formally unambiguous.
3834     if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
3835       for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS;
3836            NNS = NNS->getPrefix()) {
3837         if (NNS->getKind() == NestedNameSpecifier::Global)
3838           return;
3839       }
3840     }
3841 
3842     S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
3843         << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
3844         << FixItHint::CreateRemoval(Paren.EndLoc);
3845     return;
3846   }
3847 
3848   S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
3849       << ParenRange << D.getIdentifier();
3850   auto *RD = T->getAsCXXRecordDecl();
3851   if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
3852     S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
3853         << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
3854         << D.getIdentifier();
3855   // FIXME: A cast to void is probably a better suggestion in cases where it's
3856   // valid (when there is no initializer and we're not in a condition).
3857   S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses)
3858       << FixItHint::CreateInsertion(D.getBeginLoc(), "(")
3859       << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getEndLoc()), ")");
3860   S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
3861       << FixItHint::CreateRemoval(Paren.Loc)
3862       << FixItHint::CreateRemoval(Paren.EndLoc);
3863 }
3864 
3865 /// Helper for figuring out the default CC for a function declarator type.  If
3866 /// this is the outermost chunk, then we can determine the CC from the
3867 /// declarator context.  If not, then this could be either a member function
3868 /// type or normal function type.
getCCForDeclaratorChunk(Sema & S,Declarator & D,const ParsedAttributesView & AttrList,const DeclaratorChunk::FunctionTypeInfo & FTI,unsigned ChunkIndex)3869 static CallingConv getCCForDeclaratorChunk(
3870     Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
3871     const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
3872   assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3873 
3874   // Check for an explicit CC attribute.
3875   for (const ParsedAttr &AL : AttrList) {
3876     switch (AL.getKind()) {
3877     CALLING_CONV_ATTRS_CASELIST : {
3878       // Ignore attributes that don't validate or can't apply to the
3879       // function type.  We'll diagnose the failure to apply them in
3880       // handleFunctionTypeAttr.
3881       CallingConv CC;
3882       if (!S.CheckCallingConvAttr(AL, CC) &&
3883           (!FTI.isVariadic || supportsVariadicCall(CC))) {
3884         return CC;
3885       }
3886       break;
3887     }
3888 
3889     default:
3890       break;
3891     }
3892   }
3893 
3894   bool IsCXXInstanceMethod = false;
3895 
3896   if (S.getLangOpts().CPlusPlus) {
3897     // Look inwards through parentheses to see if this chunk will form a
3898     // member pointer type or if we're the declarator.  Any type attributes
3899     // between here and there will override the CC we choose here.
3900     unsigned I = ChunkIndex;
3901     bool FoundNonParen = false;
3902     while (I && !FoundNonParen) {
3903       --I;
3904       if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
3905         FoundNonParen = true;
3906     }
3907 
3908     if (FoundNonParen) {
3909       // If we're not the declarator, we're a regular function type unless we're
3910       // in a member pointer.
3911       IsCXXInstanceMethod =
3912           D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
3913     } else if (D.getContext() == DeclaratorContext::LambdaExpr) {
3914       // This can only be a call operator for a lambda, which is an instance
3915       // method.
3916       IsCXXInstanceMethod = true;
3917     } else {
3918       // We're the innermost decl chunk, so must be a function declarator.
3919       assert(D.isFunctionDeclarator());
3920 
3921       // If we're inside a record, we're declaring a method, but it could be
3922       // explicitly or implicitly static.
3923       IsCXXInstanceMethod =
3924           D.isFirstDeclarationOfMember() &&
3925           D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
3926           !D.isStaticMember();
3927     }
3928   }
3929 
3930   CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
3931                                                          IsCXXInstanceMethod);
3932 
3933   // Attribute AT_OpenCLKernel affects the calling convention for SPIR
3934   // and AMDGPU targets, hence it cannot be treated as a calling
3935   // convention attribute. This is the simplest place to infer
3936   // calling convention for OpenCL kernels.
3937   if (S.getLangOpts().OpenCL) {
3938     for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
3939       if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) {
3940         CC = CC_OpenCLKernel;
3941         break;
3942       }
3943     }
3944   }
3945 
3946   return CC;
3947 }
3948 
3949 namespace {
3950   /// A simple notion of pointer kinds, which matches up with the various
3951   /// pointer declarators.
3952   enum class SimplePointerKind {
3953     Pointer,
3954     BlockPointer,
3955     MemberPointer,
3956     Array,
3957   };
3958 } // end anonymous namespace
3959 
getNullabilityKeyword(NullabilityKind nullability)3960 IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
3961   switch (nullability) {
3962   case NullabilityKind::NonNull:
3963     if (!Ident__Nonnull)
3964       Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3965     return Ident__Nonnull;
3966 
3967   case NullabilityKind::Nullable:
3968     if (!Ident__Nullable)
3969       Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3970     return Ident__Nullable;
3971 
3972   case NullabilityKind::NullableResult:
3973     if (!Ident__Nullable_result)
3974       Ident__Nullable_result = PP.getIdentifierInfo("_Nullable_result");
3975     return Ident__Nullable_result;
3976 
3977   case NullabilityKind::Unspecified:
3978     if (!Ident__Null_unspecified)
3979       Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3980     return Ident__Null_unspecified;
3981   }
3982   llvm_unreachable("Unknown nullability kind.");
3983 }
3984 
3985 /// Retrieve the identifier "NSError".
getNSErrorIdent()3986 IdentifierInfo *Sema::getNSErrorIdent() {
3987   if (!Ident_NSError)
3988     Ident_NSError = PP.getIdentifierInfo("NSError");
3989 
3990   return Ident_NSError;
3991 }
3992 
3993 /// Check whether there is a nullability attribute of any kind in the given
3994 /// attribute list.
hasNullabilityAttr(const ParsedAttributesView & attrs)3995 static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
3996   for (const ParsedAttr &AL : attrs) {
3997     if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
3998         AL.getKind() == ParsedAttr::AT_TypeNullable ||
3999         AL.getKind() == ParsedAttr::AT_TypeNullableResult ||
4000         AL.getKind() == ParsedAttr::AT_TypeNullUnspecified)
4001       return true;
4002   }
4003 
4004   return false;
4005 }
4006 
4007 namespace {
4008   /// Describes the kind of a pointer a declarator describes.
4009   enum class PointerDeclaratorKind {
4010     // Not a pointer.
4011     NonPointer,
4012     // Single-level pointer.
4013     SingleLevelPointer,
4014     // Multi-level pointer (of any pointer kind).
4015     MultiLevelPointer,
4016     // CFFooRef*
4017     MaybePointerToCFRef,
4018     // CFErrorRef*
4019     CFErrorRefPointer,
4020     // NSError**
4021     NSErrorPointerPointer,
4022   };
4023 
4024   /// Describes a declarator chunk wrapping a pointer that marks inference as
4025   /// unexpected.
4026   // These values must be kept in sync with diagnostics.
4027   enum class PointerWrappingDeclaratorKind {
4028     /// Pointer is top-level.
4029     None = -1,
4030     /// Pointer is an array element.
4031     Array = 0,
4032     /// Pointer is the referent type of a C++ reference.
4033     Reference = 1
4034   };
4035 } // end anonymous namespace
4036 
4037 /// Classify the given declarator, whose type-specified is \c type, based on
4038 /// what kind of pointer it refers to.
4039 ///
4040 /// This is used to determine the default nullability.
4041 static PointerDeclaratorKind
classifyPointerDeclarator(Sema & S,QualType type,Declarator & declarator,PointerWrappingDeclaratorKind & wrappingKind)4042 classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator,
4043                           PointerWrappingDeclaratorKind &wrappingKind) {
4044   unsigned numNormalPointers = 0;
4045 
4046   // For any dependent type, we consider it a non-pointer.
4047   if (type->isDependentType())
4048     return PointerDeclaratorKind::NonPointer;
4049 
4050   // Look through the declarator chunks to identify pointers.
4051   for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
4052     DeclaratorChunk &chunk = declarator.getTypeObject(i);
4053     switch (chunk.Kind) {
4054     case DeclaratorChunk::Array:
4055       if (numNormalPointers == 0)
4056         wrappingKind = PointerWrappingDeclaratorKind::Array;
4057       break;
4058 
4059     case DeclaratorChunk::Function:
4060     case DeclaratorChunk::Pipe:
4061       break;
4062 
4063     case DeclaratorChunk::BlockPointer:
4064     case DeclaratorChunk::MemberPointer:
4065       return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4066                                    : PointerDeclaratorKind::SingleLevelPointer;
4067 
4068     case DeclaratorChunk::Paren:
4069       break;
4070 
4071     case DeclaratorChunk::Reference:
4072       if (numNormalPointers == 0)
4073         wrappingKind = PointerWrappingDeclaratorKind::Reference;
4074       break;
4075 
4076     case DeclaratorChunk::Pointer:
4077       ++numNormalPointers;
4078       if (numNormalPointers > 2)
4079         return PointerDeclaratorKind::MultiLevelPointer;
4080       break;
4081     }
4082   }
4083 
4084   // Then, dig into the type specifier itself.
4085   unsigned numTypeSpecifierPointers = 0;
4086   do {
4087     // Decompose normal pointers.
4088     if (auto ptrType = type->getAs<PointerType>()) {
4089       ++numNormalPointers;
4090 
4091       if (numNormalPointers > 2)
4092         return PointerDeclaratorKind::MultiLevelPointer;
4093 
4094       type = ptrType->getPointeeType();
4095       ++numTypeSpecifierPointers;
4096       continue;
4097     }
4098 
4099     // Decompose block pointers.
4100     if (type->getAs<BlockPointerType>()) {
4101       return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4102                                    : PointerDeclaratorKind::SingleLevelPointer;
4103     }
4104 
4105     // Decompose member pointers.
4106     if (type->getAs<MemberPointerType>()) {
4107       return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4108                                    : PointerDeclaratorKind::SingleLevelPointer;
4109     }
4110 
4111     // Look at Objective-C object pointers.
4112     if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
4113       ++numNormalPointers;
4114       ++numTypeSpecifierPointers;
4115 
4116       // If this is NSError**, report that.
4117       if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
4118         if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
4119             numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
4120           return PointerDeclaratorKind::NSErrorPointerPointer;
4121         }
4122       }
4123 
4124       break;
4125     }
4126 
4127     // Look at Objective-C class types.
4128     if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
4129       if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
4130         if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
4131           return PointerDeclaratorKind::NSErrorPointerPointer;
4132       }
4133 
4134       break;
4135     }
4136 
4137     // If at this point we haven't seen a pointer, we won't see one.
4138     if (numNormalPointers == 0)
4139       return PointerDeclaratorKind::NonPointer;
4140 
4141     if (auto recordType = type->getAs<RecordType>()) {
4142       RecordDecl *recordDecl = recordType->getDecl();
4143 
4144       // If this is CFErrorRef*, report it as such.
4145       if (numNormalPointers == 2 && numTypeSpecifierPointers < 2 &&
4146           S.isCFError(recordDecl)) {
4147         return PointerDeclaratorKind::CFErrorRefPointer;
4148       }
4149       break;
4150     }
4151 
4152     break;
4153   } while (true);
4154 
4155   switch (numNormalPointers) {
4156   case 0:
4157     return PointerDeclaratorKind::NonPointer;
4158 
4159   case 1:
4160     return PointerDeclaratorKind::SingleLevelPointer;
4161 
4162   case 2:
4163     return PointerDeclaratorKind::MaybePointerToCFRef;
4164 
4165   default:
4166     return PointerDeclaratorKind::MultiLevelPointer;
4167   }
4168 }
4169 
isCFError(RecordDecl * RD)4170 bool Sema::isCFError(RecordDecl *RD) {
4171   // If we already know about CFError, test it directly.
4172   if (CFError)
4173     return CFError == RD;
4174 
4175   // Check whether this is CFError, which we identify based on its bridge to
4176   // NSError. CFErrorRef used to be declared with "objc_bridge" but is now
4177   // declared with "objc_bridge_mutable", so look for either one of the two
4178   // attributes.
4179   if (RD->getTagKind() == TTK_Struct) {
4180     IdentifierInfo *bridgedType = nullptr;
4181     if (auto bridgeAttr = RD->getAttr<ObjCBridgeAttr>())
4182       bridgedType = bridgeAttr->getBridgedType();
4183     else if (auto bridgeAttr = RD->getAttr<ObjCBridgeMutableAttr>())
4184       bridgedType = bridgeAttr->getBridgedType();
4185 
4186     if (bridgedType == getNSErrorIdent()) {
4187       CFError = RD;
4188       return true;
4189     }
4190   }
4191 
4192   return false;
4193 }
4194 
getNullabilityCompletenessCheckFileID(Sema & S,SourceLocation loc)4195 static FileID getNullabilityCompletenessCheckFileID(Sema &S,
4196                                                     SourceLocation loc) {
4197   // If we're anywhere in a function, method, or closure context, don't perform
4198   // completeness checks.
4199   for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
4200     if (ctx->isFunctionOrMethod())
4201       return FileID();
4202 
4203     if (ctx->isFileContext())
4204       break;
4205   }
4206 
4207   // We only care about the expansion location.
4208   loc = S.SourceMgr.getExpansionLoc(loc);
4209   FileID file = S.SourceMgr.getFileID(loc);
4210   if (file.isInvalid())
4211     return FileID();
4212 
4213   // Retrieve file information.
4214   bool invalid = false;
4215   const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
4216   if (invalid || !sloc.isFile())
4217     return FileID();
4218 
4219   // We don't want to perform completeness checks on the main file or in
4220   // system headers.
4221   const SrcMgr::FileInfo &fileInfo = sloc.getFile();
4222   if (fileInfo.getIncludeLoc().isInvalid())
4223     return FileID();
4224   if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
4225       S.Diags.getSuppressSystemWarnings()) {
4226     return FileID();
4227   }
4228 
4229   return file;
4230 }
4231 
4232 /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
4233 /// taking into account whitespace before and after.
4234 template <typename DiagBuilderT>
fixItNullability(Sema & S,DiagBuilderT & Diag,SourceLocation PointerLoc,NullabilityKind Nullability)4235 static void fixItNullability(Sema &S, DiagBuilderT &Diag,
4236                              SourceLocation PointerLoc,
4237                              NullabilityKind Nullability) {
4238   assert(PointerLoc.isValid());
4239   if (PointerLoc.isMacroID())
4240     return;
4241 
4242   SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
4243   if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
4244     return;
4245 
4246   const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
4247   if (!NextChar)
4248     return;
4249 
4250   SmallString<32> InsertionTextBuf{" "};
4251   InsertionTextBuf += getNullabilitySpelling(Nullability);
4252   InsertionTextBuf += " ";
4253   StringRef InsertionText = InsertionTextBuf.str();
4254 
4255   if (isWhitespace(*NextChar)) {
4256     InsertionText = InsertionText.drop_back();
4257   } else if (NextChar[-1] == '[') {
4258     if (NextChar[0] == ']')
4259       InsertionText = InsertionText.drop_back().drop_front();
4260     else
4261       InsertionText = InsertionText.drop_front();
4262   } else if (!isAsciiIdentifierContinue(NextChar[0], /*allow dollar*/ true) &&
4263              !isAsciiIdentifierContinue(NextChar[-1], /*allow dollar*/ true)) {
4264     InsertionText = InsertionText.drop_back().drop_front();
4265   }
4266 
4267   Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
4268 }
4269 
emitNullabilityConsistencyWarning(Sema & S,SimplePointerKind PointerKind,SourceLocation PointerLoc,SourceLocation PointerEndLoc)4270 static void emitNullabilityConsistencyWarning(Sema &S,
4271                                               SimplePointerKind PointerKind,
4272                                               SourceLocation PointerLoc,
4273                                               SourceLocation PointerEndLoc) {
4274   assert(PointerLoc.isValid());
4275 
4276   if (PointerKind == SimplePointerKind::Array) {
4277     S.Diag(PointerLoc, diag::warn_nullability_missing_array);
4278   } else {
4279     S.Diag(PointerLoc, diag::warn_nullability_missing)
4280       << static_cast<unsigned>(PointerKind);
4281   }
4282 
4283   auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
4284   if (FixItLoc.isMacroID())
4285     return;
4286 
4287   auto addFixIt = [&](NullabilityKind Nullability) {
4288     auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
4289     Diag << static_cast<unsigned>(Nullability);
4290     Diag << static_cast<unsigned>(PointerKind);
4291     fixItNullability(S, Diag, FixItLoc, Nullability);
4292   };
4293   addFixIt(NullabilityKind::Nullable);
4294   addFixIt(NullabilityKind::NonNull);
4295 }
4296 
4297 /// Complains about missing nullability if the file containing \p pointerLoc
4298 /// has other uses of nullability (either the keywords or the \c assume_nonnull
4299 /// pragma).
4300 ///
4301 /// If the file has \e not seen other uses of nullability, this particular
4302 /// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
4303 static void
checkNullabilityConsistency(Sema & S,SimplePointerKind pointerKind,SourceLocation pointerLoc,SourceLocation pointerEndLoc=SourceLocation ())4304 checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
4305                             SourceLocation pointerLoc,
4306                             SourceLocation pointerEndLoc = SourceLocation()) {
4307   // Determine which file we're performing consistency checking for.
4308   FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
4309   if (file.isInvalid())
4310     return;
4311 
4312   // If we haven't seen any type nullability in this file, we won't warn now
4313   // about anything.
4314   FileNullability &fileNullability = S.NullabilityMap[file];
4315   if (!fileNullability.SawTypeNullability) {
4316     // If this is the first pointer declarator in the file, and the appropriate
4317     // warning is on, record it in case we need to diagnose it retroactively.
4318     diag::kind diagKind;
4319     if (pointerKind == SimplePointerKind::Array)
4320       diagKind = diag::warn_nullability_missing_array;
4321     else
4322       diagKind = diag::warn_nullability_missing;
4323 
4324     if (fileNullability.PointerLoc.isInvalid() &&
4325         !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
4326       fileNullability.PointerLoc = pointerLoc;
4327       fileNullability.PointerEndLoc = pointerEndLoc;
4328       fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
4329     }
4330 
4331     return;
4332   }
4333 
4334   // Complain about missing nullability.
4335   emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
4336 }
4337 
4338 /// Marks that a nullability feature has been used in the file containing
4339 /// \p loc.
4340 ///
4341 /// If this file already had pointer types in it that were missing nullability,
4342 /// the first such instance is retroactively diagnosed.
4343 ///
4344 /// \sa checkNullabilityConsistency
recordNullabilitySeen(Sema & S,SourceLocation loc)4345 static void recordNullabilitySeen(Sema &S, SourceLocation loc) {
4346   FileID file = getNullabilityCompletenessCheckFileID(S, loc);
4347   if (file.isInvalid())
4348     return;
4349 
4350   FileNullability &fileNullability = S.NullabilityMap[file];
4351   if (fileNullability.SawTypeNullability)
4352     return;
4353   fileNullability.SawTypeNullability = true;
4354 
4355   // If we haven't seen any type nullability before, now we have. Retroactively
4356   // diagnose the first unannotated pointer, if there was one.
4357   if (fileNullability.PointerLoc.isInvalid())
4358     return;
4359 
4360   auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
4361   emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc,
4362                                     fileNullability.PointerEndLoc);
4363 }
4364 
4365 /// Returns true if any of the declarator chunks before \p endIndex include a
4366 /// level of indirection: array, pointer, reference, or pointer-to-member.
4367 ///
4368 /// Because declarator chunks are stored in outer-to-inner order, testing
4369 /// every chunk before \p endIndex is testing all chunks that embed the current
4370 /// chunk as part of their type.
4371 ///
4372 /// It is legal to pass the result of Declarator::getNumTypeObjects() as the
4373 /// end index, in which case all chunks are tested.
hasOuterPointerLikeChunk(const Declarator & D,unsigned endIndex)4374 static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
4375   unsigned i = endIndex;
4376   while (i != 0) {
4377     // Walk outwards along the declarator chunks.
4378     --i;
4379     const DeclaratorChunk &DC = D.getTypeObject(i);
4380     switch (DC.Kind) {
4381     case DeclaratorChunk::Paren:
4382       break;
4383     case DeclaratorChunk::Array:
4384     case DeclaratorChunk::Pointer:
4385     case DeclaratorChunk::Reference:
4386     case DeclaratorChunk::MemberPointer:
4387       return true;
4388     case DeclaratorChunk::Function:
4389     case DeclaratorChunk::BlockPointer:
4390     case DeclaratorChunk::Pipe:
4391       // These are invalid anyway, so just ignore.
4392       break;
4393     }
4394   }
4395   return false;
4396 }
4397 
IsNoDerefableChunk(DeclaratorChunk Chunk)4398 static bool IsNoDerefableChunk(DeclaratorChunk Chunk) {
4399   return (Chunk.Kind == DeclaratorChunk::Pointer ||
4400           Chunk.Kind == DeclaratorChunk::Array);
4401 }
4402 
4403 template<typename AttrT>
createSimpleAttr(ASTContext & Ctx,ParsedAttr & AL)4404 static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4405   AL.setUsedAsTypeAttr();
4406   return ::new (Ctx) AttrT(Ctx, AL);
4407 }
4408 
createNullabilityAttr(ASTContext & Ctx,ParsedAttr & Attr,NullabilityKind NK)4409 static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr,
4410                                    NullabilityKind NK) {
4411   switch (NK) {
4412   case NullabilityKind::NonNull:
4413     return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr);
4414 
4415   case NullabilityKind::Nullable:
4416     return createSimpleAttr<TypeNullableAttr>(Ctx, Attr);
4417 
4418   case NullabilityKind::NullableResult:
4419     return createSimpleAttr<TypeNullableResultAttr>(Ctx, Attr);
4420 
4421   case NullabilityKind::Unspecified:
4422     return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr);
4423   }
4424   llvm_unreachable("unknown NullabilityKind");
4425 }
4426 
4427 // Diagnose whether this is a case with the multiple addr spaces.
4428 // Returns true if this is an invalid case.
4429 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
4430 // by qualifiers for two or more different address spaces."
DiagnoseMultipleAddrSpaceAttributes(Sema & S,LangAS ASOld,LangAS ASNew,SourceLocation AttrLoc)4431 static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld,
4432                                                 LangAS ASNew,
4433                                                 SourceLocation AttrLoc) {
4434   if (ASOld != LangAS::Default) {
4435     if (ASOld != ASNew) {
4436       S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
4437       return true;
4438     }
4439     // Emit a warning if they are identical; it's likely unintended.
4440     S.Diag(AttrLoc,
4441            diag::warn_attribute_address_multiple_identical_qualifiers);
4442   }
4443   return false;
4444 }
4445 
GetFullTypeForDeclarator(TypeProcessingState & state,QualType declSpecType,TypeSourceInfo * TInfo)4446 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
4447                                                 QualType declSpecType,
4448                                                 TypeSourceInfo *TInfo) {
4449   // The TypeSourceInfo that this function returns will not be a null type.
4450   // If there is an error, this function will fill in a dummy type as fallback.
4451   QualType T = declSpecType;
4452   Declarator &D = state.getDeclarator();
4453   Sema &S = state.getSema();
4454   ASTContext &Context = S.Context;
4455   const LangOptions &LangOpts = S.getLangOpts();
4456 
4457   // The name we're declaring, if any.
4458   DeclarationName Name;
4459   if (D.getIdentifier())
4460     Name = D.getIdentifier();
4461 
4462   // Does this declaration declare a typedef-name?
4463   bool IsTypedefName =
4464       D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
4465       D.getContext() == DeclaratorContext::AliasDecl ||
4466       D.getContext() == DeclaratorContext::AliasTemplate;
4467 
4468   // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
4469   bool IsQualifiedFunction = T->isFunctionProtoType() &&
4470       (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() ||
4471        T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
4472 
4473   // If T is 'decltype(auto)', the only declarators we can have are parens
4474   // and at most one function declarator if this is a function declaration.
4475   // If T is a deduced class template specialization type, we can have no
4476   // declarator chunks at all.
4477   if (auto *DT = T->getAs<DeducedType>()) {
4478     const AutoType *AT = T->getAs<AutoType>();
4479     bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
4480     if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
4481       for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4482         unsigned Index = E - I - 1;
4483         DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
4484         unsigned DiagId = IsClassTemplateDeduction
4485                               ? diag::err_deduced_class_template_compound_type
4486                               : diag::err_decltype_auto_compound_type;
4487         unsigned DiagKind = 0;
4488         switch (DeclChunk.Kind) {
4489         case DeclaratorChunk::Paren:
4490           // FIXME: Rejecting this is a little silly.
4491           if (IsClassTemplateDeduction) {
4492             DiagKind = 4;
4493             break;
4494           }
4495           continue;
4496         case DeclaratorChunk::Function: {
4497           if (IsClassTemplateDeduction) {
4498             DiagKind = 3;
4499             break;
4500           }
4501           unsigned FnIndex;
4502           if (D.isFunctionDeclarationContext() &&
4503               D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
4504             continue;
4505           DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
4506           break;
4507         }
4508         case DeclaratorChunk::Pointer:
4509         case DeclaratorChunk::BlockPointer:
4510         case DeclaratorChunk::MemberPointer:
4511           DiagKind = 0;
4512           break;
4513         case DeclaratorChunk::Reference:
4514           DiagKind = 1;
4515           break;
4516         case DeclaratorChunk::Array:
4517           DiagKind = 2;
4518           break;
4519         case DeclaratorChunk::Pipe:
4520           break;
4521         }
4522 
4523         S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
4524         D.setInvalidType(true);
4525         break;
4526       }
4527     }
4528   }
4529 
4530   // Determine whether we should infer _Nonnull on pointer types.
4531   Optional<NullabilityKind> inferNullability;
4532   bool inferNullabilityCS = false;
4533   bool inferNullabilityInnerOnly = false;
4534   bool inferNullabilityInnerOnlyComplete = false;
4535 
4536   // Are we in an assume-nonnull region?
4537   bool inAssumeNonNullRegion = false;
4538   SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4539   if (assumeNonNullLoc.isValid()) {
4540     inAssumeNonNullRegion = true;
4541     recordNullabilitySeen(S, assumeNonNullLoc);
4542   }
4543 
4544   // Whether to complain about missing nullability specifiers or not.
4545   enum {
4546     /// Never complain.
4547     CAMN_No,
4548     /// Complain on the inner pointers (but not the outermost
4549     /// pointer).
4550     CAMN_InnerPointers,
4551     /// Complain about any pointers that don't have nullability
4552     /// specified or inferred.
4553     CAMN_Yes
4554   } complainAboutMissingNullability = CAMN_No;
4555   unsigned NumPointersRemaining = 0;
4556   auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4557 
4558   if (IsTypedefName) {
4559     // For typedefs, we do not infer any nullability (the default),
4560     // and we only complain about missing nullability specifiers on
4561     // inner pointers.
4562     complainAboutMissingNullability = CAMN_InnerPointers;
4563 
4564     if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
4565         !T->getNullability(S.Context)) {
4566       // Note that we allow but don't require nullability on dependent types.
4567       ++NumPointersRemaining;
4568     }
4569 
4570     for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
4571       DeclaratorChunk &chunk = D.getTypeObject(i);
4572       switch (chunk.Kind) {
4573       case DeclaratorChunk::Array:
4574       case DeclaratorChunk::Function:
4575       case DeclaratorChunk::Pipe:
4576         break;
4577 
4578       case DeclaratorChunk::BlockPointer:
4579       case DeclaratorChunk::MemberPointer:
4580         ++NumPointersRemaining;
4581         break;
4582 
4583       case DeclaratorChunk::Paren:
4584       case DeclaratorChunk::Reference:
4585         continue;
4586 
4587       case DeclaratorChunk::Pointer:
4588         ++NumPointersRemaining;
4589         continue;
4590       }
4591     }
4592   } else {
4593     bool isFunctionOrMethod = false;
4594     switch (auto context = state.getDeclarator().getContext()) {
4595     case DeclaratorContext::ObjCParameter:
4596     case DeclaratorContext::ObjCResult:
4597     case DeclaratorContext::Prototype:
4598     case DeclaratorContext::TrailingReturn:
4599     case DeclaratorContext::TrailingReturnVar:
4600       isFunctionOrMethod = true;
4601       LLVM_FALLTHROUGH;
4602 
4603     case DeclaratorContext::Member:
4604       if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
4605         complainAboutMissingNullability = CAMN_No;
4606         break;
4607       }
4608 
4609       // Weak properties are inferred to be nullable.
4610       if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) {
4611         inferNullability = NullabilityKind::Nullable;
4612         break;
4613       }
4614 
4615       LLVM_FALLTHROUGH;
4616 
4617     case DeclaratorContext::File:
4618     case DeclaratorContext::KNRTypeList: {
4619       complainAboutMissingNullability = CAMN_Yes;
4620 
4621       // Nullability inference depends on the type and declarator.
4622       auto wrappingKind = PointerWrappingDeclaratorKind::None;
4623       switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4624       case PointerDeclaratorKind::NonPointer:
4625       case PointerDeclaratorKind::MultiLevelPointer:
4626         // Cannot infer nullability.
4627         break;
4628 
4629       case PointerDeclaratorKind::SingleLevelPointer:
4630         // Infer _Nonnull if we are in an assumes-nonnull region.
4631         if (inAssumeNonNullRegion) {
4632           complainAboutInferringWithinChunk = wrappingKind;
4633           inferNullability = NullabilityKind::NonNull;
4634           inferNullabilityCS = (context == DeclaratorContext::ObjCParameter ||
4635                                 context == DeclaratorContext::ObjCResult);
4636         }
4637         break;
4638 
4639       case PointerDeclaratorKind::CFErrorRefPointer:
4640       case PointerDeclaratorKind::NSErrorPointerPointer:
4641         // Within a function or method signature, infer _Nullable at both
4642         // levels.
4643         if (isFunctionOrMethod && inAssumeNonNullRegion)
4644           inferNullability = NullabilityKind::Nullable;
4645         break;
4646 
4647       case PointerDeclaratorKind::MaybePointerToCFRef:
4648         if (isFunctionOrMethod) {
4649           // On pointer-to-pointer parameters marked cf_returns_retained or
4650           // cf_returns_not_retained, if the outer pointer is explicit then
4651           // infer the inner pointer as _Nullable.
4652           auto hasCFReturnsAttr =
4653               [](const ParsedAttributesView &AttrList) -> bool {
4654             return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
4655                    AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained);
4656           };
4657           if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4658             if (hasCFReturnsAttr(D.getAttributes()) ||
4659                 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
4660                 hasCFReturnsAttr(D.getDeclSpec().getAttributes())) {
4661               inferNullability = NullabilityKind::Nullable;
4662               inferNullabilityInnerOnly = true;
4663             }
4664           }
4665         }
4666         break;
4667       }
4668       break;
4669     }
4670 
4671     case DeclaratorContext::ConversionId:
4672       complainAboutMissingNullability = CAMN_Yes;
4673       break;
4674 
4675     case DeclaratorContext::AliasDecl:
4676     case DeclaratorContext::AliasTemplate:
4677     case DeclaratorContext::Block:
4678     case DeclaratorContext::BlockLiteral:
4679     case DeclaratorContext::Condition:
4680     case DeclaratorContext::CXXCatch:
4681     case DeclaratorContext::CXXNew:
4682     case DeclaratorContext::ForInit:
4683     case DeclaratorContext::SelectionInit:
4684     case DeclaratorContext::LambdaExpr:
4685     case DeclaratorContext::LambdaExprParameter:
4686     case DeclaratorContext::ObjCCatch:
4687     case DeclaratorContext::TemplateParam:
4688     case DeclaratorContext::TemplateArg:
4689     case DeclaratorContext::TemplateTypeArg:
4690     case DeclaratorContext::TypeName:
4691     case DeclaratorContext::FunctionalCast:
4692     case DeclaratorContext::RequiresExpr:
4693       // Don't infer in these contexts.
4694       break;
4695     }
4696   }
4697 
4698   // Local function that returns true if its argument looks like a va_list.
4699   auto isVaList = [&S](QualType T) -> bool {
4700     auto *typedefTy = T->getAs<TypedefType>();
4701     if (!typedefTy)
4702       return false;
4703     TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4704     do {
4705       if (typedefTy->getDecl() == vaListTypedef)
4706         return true;
4707       if (auto *name = typedefTy->getDecl()->getIdentifier())
4708         if (name->isStr("va_list"))
4709           return true;
4710       typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4711     } while (typedefTy);
4712     return false;
4713   };
4714 
4715   // Local function that checks the nullability for a given pointer declarator.
4716   // Returns true if _Nonnull was inferred.
4717   auto inferPointerNullability =
4718       [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4719           SourceLocation pointerEndLoc,
4720           ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * {
4721     // We've seen a pointer.
4722     if (NumPointersRemaining > 0)
4723       --NumPointersRemaining;
4724 
4725     // If a nullability attribute is present, there's nothing to do.
4726     if (hasNullabilityAttr(attrs))
4727       return nullptr;
4728 
4729     // If we're supposed to infer nullability, do so now.
4730     if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4731       ParsedAttr::Syntax syntax = inferNullabilityCS
4732                                       ? ParsedAttr::AS_ContextSensitiveKeyword
4733                                       : ParsedAttr::AS_Keyword;
4734       ParsedAttr *nullabilityAttr = Pool.create(
4735           S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
4736           nullptr, SourceLocation(), nullptr, 0, syntax);
4737 
4738       attrs.addAtEnd(nullabilityAttr);
4739 
4740       if (inferNullabilityCS) {
4741         state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4742           ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4743       }
4744 
4745       if (pointerLoc.isValid() &&
4746           complainAboutInferringWithinChunk !=
4747             PointerWrappingDeclaratorKind::None) {
4748         auto Diag =
4749             S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
4750         Diag << static_cast<int>(complainAboutInferringWithinChunk);
4751         fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull);
4752       }
4753 
4754       if (inferNullabilityInnerOnly)
4755         inferNullabilityInnerOnlyComplete = true;
4756       return nullabilityAttr;
4757     }
4758 
4759     // If we're supposed to complain about missing nullability, do so
4760     // now if it's truly missing.
4761     switch (complainAboutMissingNullability) {
4762     case CAMN_No:
4763       break;
4764 
4765     case CAMN_InnerPointers:
4766       if (NumPointersRemaining == 0)
4767         break;
4768       LLVM_FALLTHROUGH;
4769 
4770     case CAMN_Yes:
4771       checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4772     }
4773     return nullptr;
4774   };
4775 
4776   // If the type itself could have nullability but does not, infer pointer
4777   // nullability and perform consistency checking.
4778   if (S.CodeSynthesisContexts.empty()) {
4779     if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
4780         !T->getNullability(S.Context)) {
4781       if (isVaList(T)) {
4782         // Record that we've seen a pointer, but do nothing else.
4783         if (NumPointersRemaining > 0)
4784           --NumPointersRemaining;
4785       } else {
4786         SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4787         if (T->isBlockPointerType())
4788           pointerKind = SimplePointerKind::BlockPointer;
4789         else if (T->isMemberPointerType())
4790           pointerKind = SimplePointerKind::MemberPointer;
4791 
4792         if (auto *attr = inferPointerNullability(
4793                 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4794                 D.getDeclSpec().getEndLoc(),
4795                 D.getMutableDeclSpec().getAttributes(),
4796                 D.getMutableDeclSpec().getAttributePool())) {
4797           T = state.getAttributedType(
4798               createNullabilityAttr(Context, *attr, *inferNullability), T, T);
4799         }
4800       }
4801     }
4802 
4803     if (complainAboutMissingNullability == CAMN_Yes &&
4804         T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) &&
4805         D.isPrototypeContext() &&
4806         !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) {
4807       checkNullabilityConsistency(S, SimplePointerKind::Array,
4808                                   D.getDeclSpec().getTypeSpecTypeLoc());
4809     }
4810   }
4811 
4812   bool ExpectNoDerefChunk =
4813       state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref);
4814 
4815   // Walk the DeclTypeInfo, building the recursive type as we go.
4816   // DeclTypeInfos are ordered from the identifier out, which is
4817   // opposite of what we want :).
4818   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4819     unsigned chunkIndex = e - i - 1;
4820     state.setCurrentChunkIndex(chunkIndex);
4821     DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4822     IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4823     switch (DeclType.Kind) {
4824     case DeclaratorChunk::Paren:
4825       if (i == 0)
4826         warnAboutRedundantParens(S, D, T);
4827       T = S.BuildParenType(T);
4828       break;
4829     case DeclaratorChunk::BlockPointer:
4830       // If blocks are disabled, emit an error.
4831       if (!LangOpts.Blocks)
4832         S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4833 
4834       // Handle pointer nullability.
4835       inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
4836                               DeclType.EndLoc, DeclType.getAttrs(),
4837                               state.getDeclarator().getAttributePool());
4838 
4839       T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4840       if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4841         // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4842         // qualified with const.
4843         if (LangOpts.OpenCL)
4844           DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4845         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4846       }
4847       break;
4848     case DeclaratorChunk::Pointer:
4849       // Verify that we're not building a pointer to pointer to function with
4850       // exception specification.
4851       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4852         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4853         D.setInvalidType(true);
4854         // Build the type anyway.
4855       }
4856 
4857       // Handle pointer nullability
4858       inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4859                               DeclType.EndLoc, DeclType.getAttrs(),
4860                               state.getDeclarator().getAttributePool());
4861 
4862       if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) {
4863         T = Context.getObjCObjectPointerType(T);
4864         if (DeclType.Ptr.TypeQuals)
4865           T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4866         break;
4867       }
4868 
4869       // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4870       // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4871       // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4872       if (LangOpts.OpenCL) {
4873         if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4874             T->isBlockPointerType()) {
4875           S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4876           D.setInvalidType(true);
4877         }
4878       }
4879 
4880       T = S.BuildPointerType(T, DeclType.Loc, Name);
4881       if (DeclType.Ptr.TypeQuals)
4882         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4883       break;
4884     case DeclaratorChunk::Reference: {
4885       // Verify that we're not building a reference to pointer to function with
4886       // exception specification.
4887       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4888         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4889         D.setInvalidType(true);
4890         // Build the type anyway.
4891       }
4892       T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
4893 
4894       if (DeclType.Ref.HasRestrict)
4895         T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
4896       break;
4897     }
4898     case DeclaratorChunk::Array: {
4899       // Verify that we're not building an array of pointers to function with
4900       // exception specification.
4901       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4902         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4903         D.setInvalidType(true);
4904         // Build the type anyway.
4905       }
4906       DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4907       Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
4908       ArrayType::ArraySizeModifier ASM;
4909       if (ATI.isStar)
4910         ASM = ArrayType::Star;
4911       else if (ATI.hasStatic)
4912         ASM = ArrayType::Static;
4913       else
4914         ASM = ArrayType::Normal;
4915       if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
4916         // FIXME: This check isn't quite right: it allows star in prototypes
4917         // for function definitions, and disallows some edge cases detailed
4918         // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4919         S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
4920         ASM = ArrayType::Normal;
4921         D.setInvalidType(true);
4922       }
4923 
4924       // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4925       // shall appear only in a declaration of a function parameter with an
4926       // array type, ...
4927       if (ASM == ArrayType::Static || ATI.TypeQuals) {
4928         if (!(D.isPrototypeContext() ||
4929               D.getContext() == DeclaratorContext::KNRTypeList)) {
4930           S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
4931               (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4932           // Remove the 'static' and the type qualifiers.
4933           if (ASM == ArrayType::Static)
4934             ASM = ArrayType::Normal;
4935           ATI.TypeQuals = 0;
4936           D.setInvalidType(true);
4937         }
4938 
4939         // C99 6.7.5.2p1: ... and then only in the outermost array type
4940         // derivation.
4941         if (hasOuterPointerLikeChunk(D, chunkIndex)) {
4942           S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
4943             (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4944           if (ASM == ArrayType::Static)
4945             ASM = ArrayType::Normal;
4946           ATI.TypeQuals = 0;
4947           D.setInvalidType(true);
4948         }
4949       }
4950       const AutoType *AT = T->getContainedAutoType();
4951       // Allow arrays of auto if we are a generic lambda parameter.
4952       // i.e. [](auto (&array)[5]) { return array[0]; }; OK
4953       if (AT && D.getContext() != DeclaratorContext::LambdaExprParameter) {
4954         // We've already diagnosed this for decltype(auto).
4955         if (!AT->isDecltypeAuto())
4956           S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
4957               << getPrintableNameForEntity(Name) << T;
4958         T = QualType();
4959         break;
4960       }
4961 
4962       // Array parameters can be marked nullable as well, although it's not
4963       // necessary if they're marked 'static'.
4964       if (complainAboutMissingNullability == CAMN_Yes &&
4965           !hasNullabilityAttr(DeclType.getAttrs()) &&
4966           ASM != ArrayType::Static &&
4967           D.isPrototypeContext() &&
4968           !hasOuterPointerLikeChunk(D, chunkIndex)) {
4969         checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
4970       }
4971 
4972       T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
4973                            SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
4974       break;
4975     }
4976     case DeclaratorChunk::Function: {
4977       // If the function declarator has a prototype (i.e. it is not () and
4978       // does not have a K&R-style identifier list), then the arguments are part
4979       // of the type, otherwise the argument list is ().
4980       DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4981       IsQualifiedFunction =
4982           FTI.hasMethodTypeQualifiers() || FTI.hasRefQualifier();
4983 
4984       // Check for auto functions and trailing return type and adjust the
4985       // return type accordingly.
4986       if (!D.isInvalidType()) {
4987         // trailing-return-type is only required if we're declaring a function,
4988         // and not, for instance, a pointer to a function.
4989         if (D.getDeclSpec().hasAutoTypeSpec() &&
4990             !FTI.hasTrailingReturnType() && chunkIndex == 0) {
4991           if (!S.getLangOpts().CPlusPlus14) {
4992             S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4993                    D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
4994                        ? diag::err_auto_missing_trailing_return
4995                        : diag::err_deduced_return_type);
4996             T = Context.IntTy;
4997             D.setInvalidType(true);
4998           } else {
4999             S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
5000                    diag::warn_cxx11_compat_deduced_return_type);
5001           }
5002         } else if (FTI.hasTrailingReturnType()) {
5003           // T must be exactly 'auto' at this point. See CWG issue 681.
5004           if (isa<ParenType>(T)) {
5005             S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens)
5006                 << T << D.getSourceRange();
5007             D.setInvalidType(true);
5008           } else if (D.getName().getKind() ==
5009                      UnqualifiedIdKind::IK_DeductionGuideName) {
5010             if (T != Context.DependentTy) {
5011               S.Diag(D.getDeclSpec().getBeginLoc(),
5012                      diag::err_deduction_guide_with_complex_decl)
5013                   << D.getSourceRange();
5014               D.setInvalidType(true);
5015             }
5016           } else if (D.getContext() != DeclaratorContext::LambdaExpr &&
5017                      (T.hasQualifiers() || !isa<AutoType>(T) ||
5018                       cast<AutoType>(T)->getKeyword() !=
5019                           AutoTypeKeyword::Auto ||
5020                       cast<AutoType>(T)->isConstrained())) {
5021             S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
5022                    diag::err_trailing_return_without_auto)
5023                 << T << D.getDeclSpec().getSourceRange();
5024             D.setInvalidType(true);
5025           }
5026           T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
5027           if (T.isNull()) {
5028             // An error occurred parsing the trailing return type.
5029             T = Context.IntTy;
5030             D.setInvalidType(true);
5031           } else if (AutoType *Auto = T->getContainedAutoType()) {
5032             // If the trailing return type contains an `auto`, we may need to
5033             // invent a template parameter for it, for cases like
5034             // `auto f() -> C auto` or `[](auto (*p) -> auto) {}`.
5035             InventedTemplateParameterInfo *InventedParamInfo = nullptr;
5036             if (D.getContext() == DeclaratorContext::Prototype)
5037               InventedParamInfo = &S.InventedParameterInfos.back();
5038             else if (D.getContext() == DeclaratorContext::LambdaExprParameter)
5039               InventedParamInfo = S.getCurLambda();
5040             if (InventedParamInfo) {
5041               std::tie(T, TInfo) = InventTemplateParameter(
5042                   state, T, TInfo, Auto, *InventedParamInfo);
5043             }
5044           }
5045         } else {
5046           // This function type is not the type of the entity being declared,
5047           // so checking the 'auto' is not the responsibility of this chunk.
5048         }
5049       }
5050 
5051       // C99 6.7.5.3p1: The return type may not be a function or array type.
5052       // For conversion functions, we'll diagnose this particular error later.
5053       if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) &&
5054           (D.getName().getKind() !=
5055            UnqualifiedIdKind::IK_ConversionFunctionId)) {
5056         unsigned diagID = diag::err_func_returning_array_function;
5057         // Last processing chunk in block context means this function chunk
5058         // represents the block.
5059         if (chunkIndex == 0 &&
5060             D.getContext() == DeclaratorContext::BlockLiteral)
5061           diagID = diag::err_block_returning_array_function;
5062         S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
5063         T = Context.IntTy;
5064         D.setInvalidType(true);
5065       }
5066 
5067       // Do not allow returning half FP value.
5068       // FIXME: This really should be in BuildFunctionType.
5069       if (T->isHalfType()) {
5070         if (S.getLangOpts().OpenCL) {
5071           if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5072                                                       S.getLangOpts())) {
5073             S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5074                 << T << 0 /*pointer hint*/;
5075             D.setInvalidType(true);
5076           }
5077         } else if (!S.getLangOpts().HalfArgsAndReturns) {
5078           S.Diag(D.getIdentifierLoc(),
5079             diag::err_parameters_retval_cannot_have_fp16_type) << 1;
5080           D.setInvalidType(true);
5081         }
5082       }
5083 
5084       if (LangOpts.OpenCL) {
5085         // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
5086         // function.
5087         if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
5088             T->isPipeType()) {
5089           S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5090               << T << 1 /*hint off*/;
5091           D.setInvalidType(true);
5092         }
5093         // OpenCL doesn't support variadic functions and blocks
5094         // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
5095         // We also allow here any toolchain reserved identifiers.
5096         if (FTI.isVariadic &&
5097             !S.getOpenCLOptions().isAvailableOption(
5098                 "__cl_clang_variadic_functions", S.getLangOpts()) &&
5099             !(D.getIdentifier() &&
5100               ((D.getIdentifier()->getName() == "printf" &&
5101                 LangOpts.getOpenCLCompatibleVersion() >= 120) ||
5102                D.getIdentifier()->getName().startswith("__")))) {
5103           S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
5104           D.setInvalidType(true);
5105         }
5106       }
5107 
5108       // Methods cannot return interface types. All ObjC objects are
5109       // passed by reference.
5110       if (T->isObjCObjectType()) {
5111         SourceLocation DiagLoc, FixitLoc;
5112         if (TInfo) {
5113           DiagLoc = TInfo->getTypeLoc().getBeginLoc();
5114           FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc());
5115         } else {
5116           DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
5117           FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc());
5118         }
5119         S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
5120           << 0 << T
5121           << FixItHint::CreateInsertion(FixitLoc, "*");
5122 
5123         T = Context.getObjCObjectPointerType(T);
5124         if (TInfo) {
5125           TypeLocBuilder TLB;
5126           TLB.pushFullCopy(TInfo->getTypeLoc());
5127           ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
5128           TLoc.setStarLoc(FixitLoc);
5129           TInfo = TLB.getTypeSourceInfo(Context, T);
5130         }
5131 
5132         D.setInvalidType(true);
5133       }
5134 
5135       // cv-qualifiers on return types are pointless except when the type is a
5136       // class type in C++.
5137       if ((T.getCVRQualifiers() || T->isAtomicType()) &&
5138           !(S.getLangOpts().CPlusPlus &&
5139             (T->isDependentType() || T->isRecordType()))) {
5140         if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
5141             D.getFunctionDefinitionKind() ==
5142                 FunctionDefinitionKind::Definition) {
5143           // [6.9.1/3] qualified void return is invalid on a C
5144           // function definition.  Apparently ok on declarations and
5145           // in C++ though (!)
5146           S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
5147         } else
5148           diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
5149 
5150         // C++2a [dcl.fct]p12:
5151         //   A volatile-qualified return type is deprecated
5152         if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20)
5153           S.Diag(DeclType.Loc, diag::warn_deprecated_volatile_return) << T;
5154       }
5155 
5156       // Objective-C ARC ownership qualifiers are ignored on the function
5157       // return type (by type canonicalization). Complain if this attribute
5158       // was written here.
5159       if (T.getQualifiers().hasObjCLifetime()) {
5160         SourceLocation AttrLoc;
5161         if (chunkIndex + 1 < D.getNumTypeObjects()) {
5162           DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
5163           for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) {
5164             if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5165               AttrLoc = AL.getLoc();
5166               break;
5167             }
5168           }
5169         }
5170         if (AttrLoc.isInvalid()) {
5171           for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
5172             if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5173               AttrLoc = AL.getLoc();
5174               break;
5175             }
5176           }
5177         }
5178 
5179         if (AttrLoc.isValid()) {
5180           // The ownership attributes are almost always written via
5181           // the predefined
5182           // __strong/__weak/__autoreleasing/__unsafe_unretained.
5183           if (AttrLoc.isMacroID())
5184             AttrLoc =
5185                 S.SourceMgr.getImmediateExpansionRange(AttrLoc).getBegin();
5186 
5187           S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
5188             << T.getQualifiers().getObjCLifetime();
5189         }
5190       }
5191 
5192       if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
5193         // C++ [dcl.fct]p6:
5194         //   Types shall not be defined in return or parameter types.
5195         TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
5196         S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
5197           << Context.getTypeDeclType(Tag);
5198       }
5199 
5200       // Exception specs are not allowed in typedefs. Complain, but add it
5201       // anyway.
5202       if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
5203         S.Diag(FTI.getExceptionSpecLocBeg(),
5204                diag::err_exception_spec_in_typedef)
5205             << (D.getContext() == DeclaratorContext::AliasDecl ||
5206                 D.getContext() == DeclaratorContext::AliasTemplate);
5207 
5208       // If we see "T var();" or "T var(T());" at block scope, it is probably
5209       // an attempt to initialize a variable, not a function declaration.
5210       if (FTI.isAmbiguous)
5211         warnAboutAmbiguousFunction(S, D, DeclType, T);
5212 
5213       FunctionType::ExtInfo EI(
5214           getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex));
5215 
5216       if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus
5217                                             && !LangOpts.OpenCL) {
5218         // Simple void foo(), where the incoming T is the result type.
5219         T = Context.getFunctionNoProtoType(T, EI);
5220       } else {
5221         // We allow a zero-parameter variadic function in C if the
5222         // function is marked with the "overloadable" attribute. Scan
5223         // for this attribute now.
5224         if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus)
5225           if (!D.getAttributes().hasAttribute(ParsedAttr::AT_Overloadable))
5226             S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
5227 
5228         if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
5229           // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
5230           // definition.
5231           S.Diag(FTI.Params[0].IdentLoc,
5232                  diag::err_ident_list_in_fn_declaration);
5233           D.setInvalidType(true);
5234           // Recover by creating a K&R-style function type.
5235           T = Context.getFunctionNoProtoType(T, EI);
5236           break;
5237         }
5238 
5239         FunctionProtoType::ExtProtoInfo EPI;
5240         EPI.ExtInfo = EI;
5241         EPI.Variadic = FTI.isVariadic;
5242         EPI.EllipsisLoc = FTI.getEllipsisLoc();
5243         EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
5244         EPI.TypeQuals.addCVRUQualifiers(
5245             FTI.MethodQualifiers ? FTI.MethodQualifiers->getTypeQualifiers()
5246                                  : 0);
5247         EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
5248                     : FTI.RefQualifierIsLValueRef? RQ_LValue
5249                     : RQ_RValue;
5250 
5251         // Otherwise, we have a function with a parameter list that is
5252         // potentially variadic.
5253         SmallVector<QualType, 16> ParamTys;
5254         ParamTys.reserve(FTI.NumParams);
5255 
5256         SmallVector<FunctionProtoType::ExtParameterInfo, 16>
5257           ExtParameterInfos(FTI.NumParams);
5258         bool HasAnyInterestingExtParameterInfos = false;
5259 
5260         for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
5261           ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5262           QualType ParamTy = Param->getType();
5263           assert(!ParamTy.isNull() && "Couldn't parse type?");
5264 
5265           // Look for 'void'.  void is allowed only as a single parameter to a
5266           // function with no other parameters (C99 6.7.5.3p10).  We record
5267           // int(void) as a FunctionProtoType with an empty parameter list.
5268           if (ParamTy->isVoidType()) {
5269             // If this is something like 'float(int, void)', reject it.  'void'
5270             // is an incomplete type (C99 6.2.5p19) and function decls cannot
5271             // have parameters of incomplete type.
5272             if (FTI.NumParams != 1 || FTI.isVariadic) {
5273               S.Diag(FTI.Params[i].IdentLoc, diag::err_void_only_param);
5274               ParamTy = Context.IntTy;
5275               Param->setType(ParamTy);
5276             } else if (FTI.Params[i].Ident) {
5277               // Reject, but continue to parse 'int(void abc)'.
5278               S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
5279               ParamTy = Context.IntTy;
5280               Param->setType(ParamTy);
5281             } else {
5282               // Reject, but continue to parse 'float(const void)'.
5283               if (ParamTy.hasQualifiers())
5284                 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
5285 
5286               // Do not add 'void' to the list.
5287               break;
5288             }
5289           } else if (ParamTy->isHalfType()) {
5290             // Disallow half FP parameters.
5291             // FIXME: This really should be in BuildFunctionType.
5292             if (S.getLangOpts().OpenCL) {
5293               if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5294                                                           S.getLangOpts())) {
5295                 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5296                     << ParamTy << 0;
5297                 D.setInvalidType();
5298                 Param->setInvalidDecl();
5299               }
5300             } else if (!S.getLangOpts().HalfArgsAndReturns) {
5301               S.Diag(Param->getLocation(),
5302                 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
5303               D.setInvalidType();
5304             }
5305           } else if (!FTI.hasPrototype) {
5306             if (ParamTy->isPromotableIntegerType()) {
5307               ParamTy = Context.getPromotedIntegerType(ParamTy);
5308               Param->setKNRPromoted(true);
5309             } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
5310               if (BTy->getKind() == BuiltinType::Float) {
5311                 ParamTy = Context.DoubleTy;
5312                 Param->setKNRPromoted(true);
5313               }
5314             }
5315           } else if (S.getLangOpts().OpenCL && ParamTy->isBlockPointerType()) {
5316             // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function.
5317             S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5318                 << ParamTy << 1 /*hint off*/;
5319             D.setInvalidType();
5320           }
5321 
5322           if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
5323             ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
5324             HasAnyInterestingExtParameterInfos = true;
5325           }
5326 
5327           if (auto attr = Param->getAttr<ParameterABIAttr>()) {
5328             ExtParameterInfos[i] =
5329               ExtParameterInfos[i].withABI(attr->getABI());
5330             HasAnyInterestingExtParameterInfos = true;
5331           }
5332 
5333           if (Param->hasAttr<PassObjectSizeAttr>()) {
5334             ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
5335             HasAnyInterestingExtParameterInfos = true;
5336           }
5337 
5338           if (Param->hasAttr<NoEscapeAttr>()) {
5339             ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
5340             HasAnyInterestingExtParameterInfos = true;
5341           }
5342 
5343           ParamTys.push_back(ParamTy);
5344         }
5345 
5346         if (HasAnyInterestingExtParameterInfos) {
5347           EPI.ExtParameterInfos = ExtParameterInfos.data();
5348           checkExtParameterInfos(S, ParamTys, EPI,
5349               [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
5350         }
5351 
5352         SmallVector<QualType, 4> Exceptions;
5353         SmallVector<ParsedType, 2> DynamicExceptions;
5354         SmallVector<SourceRange, 2> DynamicExceptionRanges;
5355         Expr *NoexceptExpr = nullptr;
5356 
5357         if (FTI.getExceptionSpecType() == EST_Dynamic) {
5358           // FIXME: It's rather inefficient to have to split into two vectors
5359           // here.
5360           unsigned N = FTI.getNumExceptions();
5361           DynamicExceptions.reserve(N);
5362           DynamicExceptionRanges.reserve(N);
5363           for (unsigned I = 0; I != N; ++I) {
5364             DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
5365             DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
5366           }
5367         } else if (isComputedNoexcept(FTI.getExceptionSpecType())) {
5368           NoexceptExpr = FTI.NoexceptExpr;
5369         }
5370 
5371         S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
5372                                       FTI.getExceptionSpecType(),
5373                                       DynamicExceptions,
5374                                       DynamicExceptionRanges,
5375                                       NoexceptExpr,
5376                                       Exceptions,
5377                                       EPI.ExceptionSpec);
5378 
5379         // FIXME: Set address space from attrs for C++ mode here.
5380         // OpenCLCPlusPlus: A class member function has an address space.
5381         auto IsClassMember = [&]() {
5382           return (!state.getDeclarator().getCXXScopeSpec().isEmpty() &&
5383                   state.getDeclarator()
5384                           .getCXXScopeSpec()
5385                           .getScopeRep()
5386                           ->getKind() == NestedNameSpecifier::TypeSpec) ||
5387                  state.getDeclarator().getContext() ==
5388                      DeclaratorContext::Member ||
5389                  state.getDeclarator().getContext() ==
5390                      DeclaratorContext::LambdaExpr;
5391         };
5392 
5393         if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) {
5394           LangAS ASIdx = LangAS::Default;
5395           // Take address space attr if any and mark as invalid to avoid adding
5396           // them later while creating QualType.
5397           if (FTI.MethodQualifiers)
5398             for (ParsedAttr &attr : FTI.MethodQualifiers->getAttributes()) {
5399               LangAS ASIdxNew = attr.asOpenCLLangAS();
5400               if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew,
5401                                                       attr.getLoc()))
5402                 D.setInvalidType(true);
5403               else
5404                 ASIdx = ASIdxNew;
5405             }
5406           // If a class member function's address space is not set, set it to
5407           // __generic.
5408           LangAS AS =
5409               (ASIdx == LangAS::Default ? S.getDefaultCXXMethodAddrSpace()
5410                                         : ASIdx);
5411           EPI.TypeQuals.addAddressSpace(AS);
5412         }
5413         T = Context.getFunctionType(T, ParamTys, EPI);
5414       }
5415       break;
5416     }
5417     case DeclaratorChunk::MemberPointer: {
5418       // The scope spec must refer to a class, or be dependent.
5419       CXXScopeSpec &SS = DeclType.Mem.Scope();
5420       QualType ClsType;
5421 
5422       // Handle pointer nullability.
5423       inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
5424                               DeclType.EndLoc, DeclType.getAttrs(),
5425                               state.getDeclarator().getAttributePool());
5426 
5427       if (SS.isInvalid()) {
5428         // Avoid emitting extra errors if we already errored on the scope.
5429         D.setInvalidType(true);
5430       } else if (S.isDependentScopeSpecifier(SS) ||
5431                  dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
5432         NestedNameSpecifier *NNS = SS.getScopeRep();
5433         NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
5434         switch (NNS->getKind()) {
5435         case NestedNameSpecifier::Identifier:
5436           ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
5437                                                  NNS->getAsIdentifier());
5438           break;
5439 
5440         case NestedNameSpecifier::Namespace:
5441         case NestedNameSpecifier::NamespaceAlias:
5442         case NestedNameSpecifier::Global:
5443         case NestedNameSpecifier::Super:
5444           llvm_unreachable("Nested-name-specifier must name a type");
5445 
5446         case NestedNameSpecifier::TypeSpec:
5447         case NestedNameSpecifier::TypeSpecWithTemplate:
5448           ClsType = QualType(NNS->getAsType(), 0);
5449           // Note: if the NNS has a prefix and ClsType is a nondependent
5450           // TemplateSpecializationType, then the NNS prefix is NOT included
5451           // in ClsType; hence we wrap ClsType into an ElaboratedType.
5452           // NOTE: in particular, no wrap occurs if ClsType already is an
5453           // Elaborated, DependentName, or DependentTemplateSpecialization.
5454           if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
5455             ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
5456           break;
5457         }
5458       } else {
5459         S.Diag(DeclType.Mem.Scope().getBeginLoc(),
5460              diag::err_illegal_decl_mempointer_in_nonclass)
5461           << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
5462           << DeclType.Mem.Scope().getRange();
5463         D.setInvalidType(true);
5464       }
5465 
5466       if (!ClsType.isNull())
5467         T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
5468                                      D.getIdentifier());
5469       if (T.isNull()) {
5470         T = Context.IntTy;
5471         D.setInvalidType(true);
5472       } else if (DeclType.Mem.TypeQuals) {
5473         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
5474       }
5475       break;
5476     }
5477 
5478     case DeclaratorChunk::Pipe: {
5479       T = S.BuildReadPipeType(T, DeclType.Loc);
5480       processTypeAttrs(state, T, TAL_DeclSpec,
5481                        D.getMutableDeclSpec().getAttributes());
5482       break;
5483     }
5484     }
5485 
5486     if (T.isNull()) {
5487       D.setInvalidType(true);
5488       T = Context.IntTy;
5489     }
5490 
5491     // See if there are any attributes on this declarator chunk.
5492     processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs());
5493 
5494     if (DeclType.Kind != DeclaratorChunk::Paren) {
5495       if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType))
5496         S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array);
5497 
5498       ExpectNoDerefChunk = state.didParseNoDeref();
5499     }
5500   }
5501 
5502   if (ExpectNoDerefChunk)
5503     S.Diag(state.getDeclarator().getBeginLoc(),
5504            diag::warn_noderef_on_non_pointer_or_array);
5505 
5506   // GNU warning -Wstrict-prototypes
5507   //   Warn if a function declaration is without a prototype.
5508   //   This warning is issued for all kinds of unprototyped function
5509   //   declarations (i.e. function type typedef, function pointer etc.)
5510   //   C99 6.7.5.3p14:
5511   //   The empty list in a function declarator that is not part of a definition
5512   //   of that function specifies that no information about the number or types
5513   //   of the parameters is supplied.
5514   if (!LangOpts.CPlusPlus &&
5515       D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration) {
5516     bool IsBlock = false;
5517     for (const DeclaratorChunk &DeclType : D.type_objects()) {
5518       switch (DeclType.Kind) {
5519       case DeclaratorChunk::BlockPointer:
5520         IsBlock = true;
5521         break;
5522       case DeclaratorChunk::Function: {
5523         const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5524         // We suppress the warning when there's no LParen location, as this
5525         // indicates the declaration was an implicit declaration, which gets
5526         // warned about separately via -Wimplicit-function-declaration.
5527         if (FTI.NumParams == 0 && !FTI.isVariadic && FTI.getLParenLoc().isValid())
5528           S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
5529               << IsBlock
5530               << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
5531         IsBlock = false;
5532         break;
5533       }
5534       default:
5535         break;
5536       }
5537     }
5538   }
5539 
5540   assert(!T.isNull() && "T must not be null after this point");
5541 
5542   if (LangOpts.CPlusPlus && T->isFunctionType()) {
5543     const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
5544     assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
5545 
5546     // C++ 8.3.5p4:
5547     //   A cv-qualifier-seq shall only be part of the function type
5548     //   for a nonstatic member function, the function type to which a pointer
5549     //   to member refers, or the top-level function type of a function typedef
5550     //   declaration.
5551     //
5552     // Core issue 547 also allows cv-qualifiers on function types that are
5553     // top-level template type arguments.
5554     enum { NonMember, Member, DeductionGuide } Kind = NonMember;
5555     if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
5556       Kind = DeductionGuide;
5557     else if (!D.getCXXScopeSpec().isSet()) {
5558       if ((D.getContext() == DeclaratorContext::Member ||
5559            D.getContext() == DeclaratorContext::LambdaExpr) &&
5560           !D.getDeclSpec().isFriendSpecified())
5561         Kind = Member;
5562     } else {
5563       DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
5564       if (!DC || DC->isRecord())
5565         Kind = Member;
5566     }
5567 
5568     // C++11 [dcl.fct]p6 (w/DR1417):
5569     // An attempt to specify a function type with a cv-qualifier-seq or a
5570     // ref-qualifier (including by typedef-name) is ill-formed unless it is:
5571     //  - the function type for a non-static member function,
5572     //  - the function type to which a pointer to member refers,
5573     //  - the top-level function type of a function typedef declaration or
5574     //    alias-declaration,
5575     //  - the type-id in the default argument of a type-parameter, or
5576     //  - the type-id of a template-argument for a type-parameter
5577     //
5578     // FIXME: Checking this here is insufficient. We accept-invalid on:
5579     //
5580     //   template<typename T> struct S { void f(T); };
5581     //   S<int() const> s;
5582     //
5583     // ... for instance.
5584     if (IsQualifiedFunction &&
5585         !(Kind == Member &&
5586           D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
5587         !IsTypedefName && D.getContext() != DeclaratorContext::TemplateArg &&
5588         D.getContext() != DeclaratorContext::TemplateTypeArg) {
5589       SourceLocation Loc = D.getBeginLoc();
5590       SourceRange RemovalRange;
5591       unsigned I;
5592       if (D.isFunctionDeclarator(I)) {
5593         SmallVector<SourceLocation, 4> RemovalLocs;
5594         const DeclaratorChunk &Chunk = D.getTypeObject(I);
5595         assert(Chunk.Kind == DeclaratorChunk::Function);
5596 
5597         if (Chunk.Fun.hasRefQualifier())
5598           RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
5599 
5600         if (Chunk.Fun.hasMethodTypeQualifiers())
5601           Chunk.Fun.MethodQualifiers->forEachQualifier(
5602               [&](DeclSpec::TQ TypeQual, StringRef QualName,
5603                   SourceLocation SL) { RemovalLocs.push_back(SL); });
5604 
5605         if (!RemovalLocs.empty()) {
5606           llvm::sort(RemovalLocs,
5607                      BeforeThanCompare<SourceLocation>(S.getSourceManager()));
5608           RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
5609           Loc = RemovalLocs.front();
5610         }
5611       }
5612 
5613       S.Diag(Loc, diag::err_invalid_qualified_function_type)
5614         << Kind << D.isFunctionDeclarator() << T
5615         << getFunctionQualifiersAsString(FnTy)
5616         << FixItHint::CreateRemoval(RemovalRange);
5617 
5618       // Strip the cv-qualifiers and ref-qualifiers from the type.
5619       FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
5620       EPI.TypeQuals.removeCVRQualifiers();
5621       EPI.RefQualifier = RQ_None;
5622 
5623       T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
5624                                   EPI);
5625       // Rebuild any parens around the identifier in the function type.
5626       for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5627         if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
5628           break;
5629         T = S.BuildParenType(T);
5630       }
5631     }
5632   }
5633 
5634   // Apply any undistributed attributes from the declarator.
5635   processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
5636 
5637   // Diagnose any ignored type attributes.
5638   state.diagnoseIgnoredTypeAttrs(T);
5639 
5640   // C++0x [dcl.constexpr]p9:
5641   //  A constexpr specifier used in an object declaration declares the object
5642   //  as const.
5643   if (D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr &&
5644       T->isObjectType())
5645     T.addConst();
5646 
5647   // C++2a [dcl.fct]p4:
5648   //   A parameter with volatile-qualified type is deprecated
5649   if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20 &&
5650       (D.getContext() == DeclaratorContext::Prototype ||
5651        D.getContext() == DeclaratorContext::LambdaExprParameter))
5652     S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T;
5653 
5654   // If there was an ellipsis in the declarator, the declaration declares a
5655   // parameter pack whose type may be a pack expansion type.
5656   if (D.hasEllipsis()) {
5657     // C++0x [dcl.fct]p13:
5658     //   A declarator-id or abstract-declarator containing an ellipsis shall
5659     //   only be used in a parameter-declaration. Such a parameter-declaration
5660     //   is a parameter pack (14.5.3). [...]
5661     switch (D.getContext()) {
5662     case DeclaratorContext::Prototype:
5663     case DeclaratorContext::LambdaExprParameter:
5664     case DeclaratorContext::RequiresExpr:
5665       // C++0x [dcl.fct]p13:
5666       //   [...] When it is part of a parameter-declaration-clause, the
5667       //   parameter pack is a function parameter pack (14.5.3). The type T
5668       //   of the declarator-id of the function parameter pack shall contain
5669       //   a template parameter pack; each template parameter pack in T is
5670       //   expanded by the function parameter pack.
5671       //
5672       // We represent function parameter packs as function parameters whose
5673       // type is a pack expansion.
5674       if (!T->containsUnexpandedParameterPack() &&
5675           (!LangOpts.CPlusPlus20 || !T->getContainedAutoType())) {
5676         S.Diag(D.getEllipsisLoc(),
5677              diag::err_function_parameter_pack_without_parameter_packs)
5678           << T <<  D.getSourceRange();
5679         D.setEllipsisLoc(SourceLocation());
5680       } else {
5681         T = Context.getPackExpansionType(T, None, /*ExpectPackInType=*/false);
5682       }
5683       break;
5684     case DeclaratorContext::TemplateParam:
5685       // C++0x [temp.param]p15:
5686       //   If a template-parameter is a [...] is a parameter-declaration that
5687       //   declares a parameter pack (8.3.5), then the template-parameter is a
5688       //   template parameter pack (14.5.3).
5689       //
5690       // Note: core issue 778 clarifies that, if there are any unexpanded
5691       // parameter packs in the type of the non-type template parameter, then
5692       // it expands those parameter packs.
5693       if (T->containsUnexpandedParameterPack())
5694         T = Context.getPackExpansionType(T, None);
5695       else
5696         S.Diag(D.getEllipsisLoc(),
5697                LangOpts.CPlusPlus11
5698                  ? diag::warn_cxx98_compat_variadic_templates
5699                  : diag::ext_variadic_templates);
5700       break;
5701 
5702     case DeclaratorContext::File:
5703     case DeclaratorContext::KNRTypeList:
5704     case DeclaratorContext::ObjCParameter: // FIXME: special diagnostic here?
5705     case DeclaratorContext::ObjCResult:    // FIXME: special diagnostic here?
5706     case DeclaratorContext::TypeName:
5707     case DeclaratorContext::FunctionalCast:
5708     case DeclaratorContext::CXXNew:
5709     case DeclaratorContext::AliasDecl:
5710     case DeclaratorContext::AliasTemplate:
5711     case DeclaratorContext::Member:
5712     case DeclaratorContext::Block:
5713     case DeclaratorContext::ForInit:
5714     case DeclaratorContext::SelectionInit:
5715     case DeclaratorContext::Condition:
5716     case DeclaratorContext::CXXCatch:
5717     case DeclaratorContext::ObjCCatch:
5718     case DeclaratorContext::BlockLiteral:
5719     case DeclaratorContext::LambdaExpr:
5720     case DeclaratorContext::ConversionId:
5721     case DeclaratorContext::TrailingReturn:
5722     case DeclaratorContext::TrailingReturnVar:
5723     case DeclaratorContext::TemplateArg:
5724     case DeclaratorContext::TemplateTypeArg:
5725       // FIXME: We may want to allow parameter packs in block-literal contexts
5726       // in the future.
5727       S.Diag(D.getEllipsisLoc(),
5728              diag::err_ellipsis_in_declarator_not_parameter);
5729       D.setEllipsisLoc(SourceLocation());
5730       break;
5731     }
5732   }
5733 
5734   assert(!T.isNull() && "T must not be null at the end of this function");
5735   if (D.isInvalidType())
5736     return Context.getTrivialTypeSourceInfo(T);
5737 
5738   return GetTypeSourceInfoForDeclarator(state, T, TInfo);
5739 }
5740 
5741 /// GetTypeForDeclarator - Convert the type for the specified
5742 /// declarator to Type instances.
5743 ///
5744 /// The result of this call will never be null, but the associated
5745 /// type may be a null type if there's an unrecoverable error.
GetTypeForDeclarator(Declarator & D,Scope * S)5746 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
5747   // Determine the type of the declarator. Not all forms of declarator
5748   // have a type.
5749 
5750   TypeProcessingState state(*this, D);
5751 
5752   TypeSourceInfo *ReturnTypeInfo = nullptr;
5753   QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5754   if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
5755     inferARCWriteback(state, T);
5756 
5757   return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
5758 }
5759 
transferARCOwnershipToDeclSpec(Sema & S,QualType & declSpecTy,Qualifiers::ObjCLifetime ownership)5760 static void transferARCOwnershipToDeclSpec(Sema &S,
5761                                            QualType &declSpecTy,
5762                                            Qualifiers::ObjCLifetime ownership) {
5763   if (declSpecTy->isObjCRetainableType() &&
5764       declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
5765     Qualifiers qs;
5766     qs.addObjCLifetime(ownership);
5767     declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
5768   }
5769 }
5770 
transferARCOwnershipToDeclaratorChunk(TypeProcessingState & state,Qualifiers::ObjCLifetime ownership,unsigned chunkIndex)5771 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
5772                                             Qualifiers::ObjCLifetime ownership,
5773                                             unsigned chunkIndex) {
5774   Sema &S = state.getSema();
5775   Declarator &D = state.getDeclarator();
5776 
5777   // Look for an explicit lifetime attribute.
5778   DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
5779   if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership))
5780     return;
5781 
5782   const char *attrStr = nullptr;
5783   switch (ownership) {
5784   case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
5785   case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
5786   case Qualifiers::OCL_Strong: attrStr = "strong"; break;
5787   case Qualifiers::OCL_Weak: attrStr = "weak"; break;
5788   case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
5789   }
5790 
5791   IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
5792   Arg->Ident = &S.Context.Idents.get(attrStr);
5793   Arg->Loc = SourceLocation();
5794 
5795   ArgsUnion Args(Arg);
5796 
5797   // If there wasn't one, add one (with an invalid source location
5798   // so that we don't make an AttributedType for it).
5799   ParsedAttr *attr = D.getAttributePool().create(
5800       &S.Context.Idents.get("objc_ownership"), SourceLocation(),
5801       /*scope*/ nullptr, SourceLocation(),
5802       /*args*/ &Args, 1, ParsedAttr::AS_GNU);
5803   chunk.getAttrs().addAtEnd(attr);
5804   // TODO: mark whether we did this inference?
5805 }
5806 
5807 /// Used for transferring ownership in casts resulting in l-values.
transferARCOwnership(TypeProcessingState & state,QualType & declSpecTy,Qualifiers::ObjCLifetime ownership)5808 static void transferARCOwnership(TypeProcessingState &state,
5809                                  QualType &declSpecTy,
5810                                  Qualifiers::ObjCLifetime ownership) {
5811   Sema &S = state.getSema();
5812   Declarator &D = state.getDeclarator();
5813 
5814   int inner = -1;
5815   bool hasIndirection = false;
5816   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5817     DeclaratorChunk &chunk = D.getTypeObject(i);
5818     switch (chunk.Kind) {
5819     case DeclaratorChunk::Paren:
5820       // Ignore parens.
5821       break;
5822 
5823     case DeclaratorChunk::Array:
5824     case DeclaratorChunk::Reference:
5825     case DeclaratorChunk::Pointer:
5826       if (inner != -1)
5827         hasIndirection = true;
5828       inner = i;
5829       break;
5830 
5831     case DeclaratorChunk::BlockPointer:
5832       if (inner != -1)
5833         transferARCOwnershipToDeclaratorChunk(state, ownership, i);
5834       return;
5835 
5836     case DeclaratorChunk::Function:
5837     case DeclaratorChunk::MemberPointer:
5838     case DeclaratorChunk::Pipe:
5839       return;
5840     }
5841   }
5842 
5843   if (inner == -1)
5844     return;
5845 
5846   DeclaratorChunk &chunk = D.getTypeObject(inner);
5847   if (chunk.Kind == DeclaratorChunk::Pointer) {
5848     if (declSpecTy->isObjCRetainableType())
5849       return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5850     if (declSpecTy->isObjCObjectType() && hasIndirection)
5851       return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
5852   } else {
5853     assert(chunk.Kind == DeclaratorChunk::Array ||
5854            chunk.Kind == DeclaratorChunk::Reference);
5855     return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5856   }
5857 }
5858 
GetTypeForDeclaratorCast(Declarator & D,QualType FromTy)5859 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
5860   TypeProcessingState state(*this, D);
5861 
5862   TypeSourceInfo *ReturnTypeInfo = nullptr;
5863   QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5864 
5865   if (getLangOpts().ObjC) {
5866     Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
5867     if (ownership != Qualifiers::OCL_None)
5868       transferARCOwnership(state, declSpecTy, ownership);
5869   }
5870 
5871   return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
5872 }
5873 
fillAttributedTypeLoc(AttributedTypeLoc TL,TypeProcessingState & State)5874 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
5875                                   TypeProcessingState &State) {
5876   TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr()));
5877 }
5878 
5879 namespace {
5880   class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
5881     Sema &SemaRef;
5882     ASTContext &Context;
5883     TypeProcessingState &State;
5884     const DeclSpec &DS;
5885 
5886   public:
TypeSpecLocFiller(Sema & S,ASTContext & Context,TypeProcessingState & State,const DeclSpec & DS)5887     TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State,
5888                       const DeclSpec &DS)
5889         : SemaRef(S), Context(Context), State(State), DS(DS) {}
5890 
VisitAttributedTypeLoc(AttributedTypeLoc TL)5891     void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5892       Visit(TL.getModifiedLoc());
5893       fillAttributedTypeLoc(TL, State);
5894     }
VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL)5895     void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
5896       Visit(TL.getInnerLoc());
5897       TL.setExpansionLoc(
5898           State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
5899     }
VisitQualifiedTypeLoc(QualifiedTypeLoc TL)5900     void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5901       Visit(TL.getUnqualifiedLoc());
5902     }
VisitTypedefTypeLoc(TypedefTypeLoc TL)5903     void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5904       TL.setNameLoc(DS.getTypeSpecTypeLoc());
5905     }
VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL)5906     void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5907       TL.setNameLoc(DS.getTypeSpecTypeLoc());
5908       // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
5909       // addition field. What we have is good enough for display of location
5910       // of 'fixit' on interface name.
5911       TL.setNameEndLoc(DS.getEndLoc());
5912     }
VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL)5913     void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5914       TypeSourceInfo *RepTInfo = nullptr;
5915       Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5916       TL.copy(RepTInfo->getTypeLoc());
5917     }
VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL)5918     void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5919       TypeSourceInfo *RepTInfo = nullptr;
5920       Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5921       TL.copy(RepTInfo->getTypeLoc());
5922     }
VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL)5923     void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
5924       TypeSourceInfo *TInfo = nullptr;
5925       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5926 
5927       // If we got no declarator info from previous Sema routines,
5928       // just fill with the typespec loc.
5929       if (!TInfo) {
5930         TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
5931         return;
5932       }
5933 
5934       TypeLoc OldTL = TInfo->getTypeLoc();
5935       if (TInfo->getType()->getAs<ElaboratedType>()) {
5936         ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
5937         TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
5938             .castAs<TemplateSpecializationTypeLoc>();
5939         TL.copy(NamedTL);
5940       } else {
5941         TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
5942         assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
5943       }
5944 
5945     }
VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL)5946     void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5947       assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
5948       TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5949       TL.setParensRange(DS.getTypeofParensRange());
5950     }
VisitTypeOfTypeLoc(TypeOfTypeLoc TL)5951     void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5952       assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
5953       TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5954       TL.setParensRange(DS.getTypeofParensRange());
5955       assert(DS.getRepAsType());
5956       TypeSourceInfo *TInfo = nullptr;
5957       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5958       TL.setUnderlyingTInfo(TInfo);
5959     }
VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL)5960     void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5961       // FIXME: This holds only because we only have one unary transform.
5962       assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
5963       TL.setKWLoc(DS.getTypeSpecTypeLoc());
5964       TL.setParensRange(DS.getTypeofParensRange());
5965       assert(DS.getRepAsType());
5966       TypeSourceInfo *TInfo = nullptr;
5967       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5968       TL.setUnderlyingTInfo(TInfo);
5969     }
VisitBuiltinTypeLoc(BuiltinTypeLoc TL)5970     void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5971       // By default, use the source location of the type specifier.
5972       TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
5973       if (TL.needsExtraLocalData()) {
5974         // Set info for the written builtin specifiers.
5975         TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
5976         // Try to have a meaningful source location.
5977         if (TL.getWrittenSignSpec() != TypeSpecifierSign::Unspecified)
5978           TL.expandBuiltinRange(DS.getTypeSpecSignLoc());
5979         if (TL.getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified)
5980           TL.expandBuiltinRange(DS.getTypeSpecWidthRange());
5981       }
5982     }
VisitElaboratedTypeLoc(ElaboratedTypeLoc TL)5983     void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5984       ElaboratedTypeKeyword Keyword
5985         = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
5986       if (DS.getTypeSpecType() == TST_typename) {
5987         TypeSourceInfo *TInfo = nullptr;
5988         Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5989         if (TInfo) {
5990           TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
5991           return;
5992         }
5993       }
5994       TL.setElaboratedKeywordLoc(Keyword != ETK_None
5995                                  ? DS.getTypeSpecTypeLoc()
5996                                  : SourceLocation());
5997       const CXXScopeSpec& SS = DS.getTypeSpecScope();
5998       TL.setQualifierLoc(SS.getWithLocInContext(Context));
5999       Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
6000     }
VisitDependentNameTypeLoc(DependentNameTypeLoc TL)6001     void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6002       assert(DS.getTypeSpecType() == TST_typename);
6003       TypeSourceInfo *TInfo = nullptr;
6004       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6005       assert(TInfo);
6006       TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
6007     }
VisitDependentTemplateSpecializationTypeLoc(DependentTemplateSpecializationTypeLoc TL)6008     void VisitDependentTemplateSpecializationTypeLoc(
6009                                  DependentTemplateSpecializationTypeLoc TL) {
6010       assert(DS.getTypeSpecType() == TST_typename);
6011       TypeSourceInfo *TInfo = nullptr;
6012       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6013       assert(TInfo);
6014       TL.copy(
6015           TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
6016     }
VisitAutoTypeLoc(AutoTypeLoc TL)6017     void VisitAutoTypeLoc(AutoTypeLoc TL) {
6018       assert(DS.getTypeSpecType() == TST_auto ||
6019              DS.getTypeSpecType() == TST_decltype_auto ||
6020              DS.getTypeSpecType() == TST_auto_type ||
6021              DS.getTypeSpecType() == TST_unspecified);
6022       TL.setNameLoc(DS.getTypeSpecTypeLoc());
6023       if (!DS.isConstrainedAuto())
6024         return;
6025       TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId();
6026       if (!TemplateId)
6027         return;
6028       if (DS.getTypeSpecScope().isNotEmpty())
6029         TL.setNestedNameSpecifierLoc(
6030             DS.getTypeSpecScope().getWithLocInContext(Context));
6031       else
6032         TL.setNestedNameSpecifierLoc(NestedNameSpecifierLoc());
6033       TL.setTemplateKWLoc(TemplateId->TemplateKWLoc);
6034       TL.setConceptNameLoc(TemplateId->TemplateNameLoc);
6035       TL.setFoundDecl(nullptr);
6036       TL.setLAngleLoc(TemplateId->LAngleLoc);
6037       TL.setRAngleLoc(TemplateId->RAngleLoc);
6038       if (TemplateId->NumArgs == 0)
6039         return;
6040       TemplateArgumentListInfo TemplateArgsInfo;
6041       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6042                                          TemplateId->NumArgs);
6043       SemaRef.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
6044       for (unsigned I = 0; I < TemplateId->NumArgs; ++I)
6045         TL.setArgLocInfo(I, TemplateArgsInfo.arguments()[I].getLocInfo());
6046     }
VisitTagTypeLoc(TagTypeLoc TL)6047     void VisitTagTypeLoc(TagTypeLoc TL) {
6048       TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
6049     }
VisitAtomicTypeLoc(AtomicTypeLoc TL)6050     void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6051       // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
6052       // or an _Atomic qualifier.
6053       if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
6054         TL.setKWLoc(DS.getTypeSpecTypeLoc());
6055         TL.setParensRange(DS.getTypeofParensRange());
6056 
6057         TypeSourceInfo *TInfo = nullptr;
6058         Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6059         assert(TInfo);
6060         TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
6061       } else {
6062         TL.setKWLoc(DS.getAtomicSpecLoc());
6063         // No parens, to indicate this was spelled as an _Atomic qualifier.
6064         TL.setParensRange(SourceRange());
6065         Visit(TL.getValueLoc());
6066       }
6067     }
6068 
VisitPipeTypeLoc(PipeTypeLoc TL)6069     void VisitPipeTypeLoc(PipeTypeLoc TL) {
6070       TL.setKWLoc(DS.getTypeSpecTypeLoc());
6071 
6072       TypeSourceInfo *TInfo = nullptr;
6073       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6074       TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
6075     }
6076 
VisitExtIntTypeLoc(ExtIntTypeLoc TL)6077     void VisitExtIntTypeLoc(ExtIntTypeLoc TL) {
6078       TL.setNameLoc(DS.getTypeSpecTypeLoc());
6079     }
6080 
VisitDependentExtIntTypeLoc(DependentExtIntTypeLoc TL)6081     void VisitDependentExtIntTypeLoc(DependentExtIntTypeLoc TL) {
6082       TL.setNameLoc(DS.getTypeSpecTypeLoc());
6083     }
6084 
VisitTypeLoc(TypeLoc TL)6085     void VisitTypeLoc(TypeLoc TL) {
6086       // FIXME: add other typespec types and change this to an assert.
6087       TL.initialize(Context, DS.getTypeSpecTypeLoc());
6088     }
6089   };
6090 
6091   class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
6092     ASTContext &Context;
6093     TypeProcessingState &State;
6094     const DeclaratorChunk &Chunk;
6095 
6096   public:
DeclaratorLocFiller(ASTContext & Context,TypeProcessingState & State,const DeclaratorChunk & Chunk)6097     DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State,
6098                         const DeclaratorChunk &Chunk)
6099         : Context(Context), State(State), Chunk(Chunk) {}
6100 
VisitQualifiedTypeLoc(QualifiedTypeLoc TL)6101     void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6102       llvm_unreachable("qualified type locs not expected here!");
6103     }
VisitDecayedTypeLoc(DecayedTypeLoc TL)6104     void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6105       llvm_unreachable("decayed type locs not expected here!");
6106     }
6107 
VisitAttributedTypeLoc(AttributedTypeLoc TL)6108     void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6109       fillAttributedTypeLoc(TL, State);
6110     }
VisitAdjustedTypeLoc(AdjustedTypeLoc TL)6111     void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6112       // nothing
6113     }
VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL)6114     void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6115       assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
6116       TL.setCaretLoc(Chunk.Loc);
6117     }
VisitPointerTypeLoc(PointerTypeLoc TL)6118     void VisitPointerTypeLoc(PointerTypeLoc TL) {
6119       assert(Chunk.Kind == DeclaratorChunk::Pointer);
6120       TL.setStarLoc(Chunk.Loc);
6121     }
VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL)6122     void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6123       assert(Chunk.Kind == DeclaratorChunk::Pointer);
6124       TL.setStarLoc(Chunk.Loc);
6125     }
VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL)6126     void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6127       assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
6128       const CXXScopeSpec& SS = Chunk.Mem.Scope();
6129       NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
6130 
6131       const Type* ClsTy = TL.getClass();
6132       QualType ClsQT = QualType(ClsTy, 0);
6133       TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
6134       // Now copy source location info into the type loc component.
6135       TypeLoc ClsTL = ClsTInfo->getTypeLoc();
6136       switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
6137       case NestedNameSpecifier::Identifier:
6138         assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
6139         {
6140           DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
6141           DNTLoc.setElaboratedKeywordLoc(SourceLocation());
6142           DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
6143           DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
6144         }
6145         break;
6146 
6147       case NestedNameSpecifier::TypeSpec:
6148       case NestedNameSpecifier::TypeSpecWithTemplate:
6149         if (isa<ElaboratedType>(ClsTy)) {
6150           ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
6151           ETLoc.setElaboratedKeywordLoc(SourceLocation());
6152           ETLoc.setQualifierLoc(NNSLoc.getPrefix());
6153           TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
6154           NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
6155         } else {
6156           ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
6157         }
6158         break;
6159 
6160       case NestedNameSpecifier::Namespace:
6161       case NestedNameSpecifier::NamespaceAlias:
6162       case NestedNameSpecifier::Global:
6163       case NestedNameSpecifier::Super:
6164         llvm_unreachable("Nested-name-specifier must name a type");
6165       }
6166 
6167       // Finally fill in MemberPointerLocInfo fields.
6168       TL.setStarLoc(Chunk.Mem.StarLoc);
6169       TL.setClassTInfo(ClsTInfo);
6170     }
VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL)6171     void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6172       assert(Chunk.Kind == DeclaratorChunk::Reference);
6173       // 'Amp' is misleading: this might have been originally
6174       /// spelled with AmpAmp.
6175       TL.setAmpLoc(Chunk.Loc);
6176     }
VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL)6177     void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6178       assert(Chunk.Kind == DeclaratorChunk::Reference);
6179       assert(!Chunk.Ref.LValueRef);
6180       TL.setAmpAmpLoc(Chunk.Loc);
6181     }
VisitArrayTypeLoc(ArrayTypeLoc TL)6182     void VisitArrayTypeLoc(ArrayTypeLoc TL) {
6183       assert(Chunk.Kind == DeclaratorChunk::Array);
6184       TL.setLBracketLoc(Chunk.Loc);
6185       TL.setRBracketLoc(Chunk.EndLoc);
6186       TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
6187     }
VisitFunctionTypeLoc(FunctionTypeLoc TL)6188     void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6189       assert(Chunk.Kind == DeclaratorChunk::Function);
6190       TL.setLocalRangeBegin(Chunk.Loc);
6191       TL.setLocalRangeEnd(Chunk.EndLoc);
6192 
6193       const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
6194       TL.setLParenLoc(FTI.getLParenLoc());
6195       TL.setRParenLoc(FTI.getRParenLoc());
6196       for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
6197         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
6198         TL.setParam(tpi++, Param);
6199       }
6200       TL.setExceptionSpecRange(FTI.getExceptionSpecRange());
6201     }
VisitParenTypeLoc(ParenTypeLoc TL)6202     void VisitParenTypeLoc(ParenTypeLoc TL) {
6203       assert(Chunk.Kind == DeclaratorChunk::Paren);
6204       TL.setLParenLoc(Chunk.Loc);
6205       TL.setRParenLoc(Chunk.EndLoc);
6206     }
VisitPipeTypeLoc(PipeTypeLoc TL)6207     void VisitPipeTypeLoc(PipeTypeLoc TL) {
6208       assert(Chunk.Kind == DeclaratorChunk::Pipe);
6209       TL.setKWLoc(Chunk.Loc);
6210     }
VisitExtIntTypeLoc(ExtIntTypeLoc TL)6211     void VisitExtIntTypeLoc(ExtIntTypeLoc TL) {
6212       TL.setNameLoc(Chunk.Loc);
6213     }
VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL)6214     void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6215       TL.setExpansionLoc(Chunk.Loc);
6216     }
VisitVectorTypeLoc(VectorTypeLoc TL)6217     void VisitVectorTypeLoc(VectorTypeLoc TL) { TL.setNameLoc(Chunk.Loc); }
VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL)6218     void VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL) {
6219       TL.setNameLoc(Chunk.Loc);
6220     }
VisitExtVectorTypeLoc(ExtVectorTypeLoc TL)6221     void VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6222       TL.setNameLoc(Chunk.Loc);
6223     }
6224     void
VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL)6225     VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL) {
6226       TL.setNameLoc(Chunk.Loc);
6227     }
6228 
VisitTypeLoc(TypeLoc TL)6229     void VisitTypeLoc(TypeLoc TL) {
6230       llvm_unreachable("unsupported TypeLoc kind in declarator!");
6231     }
6232   };
6233 } // end anonymous namespace
6234 
fillAtomicQualLoc(AtomicTypeLoc ATL,const DeclaratorChunk & Chunk)6235 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
6236   SourceLocation Loc;
6237   switch (Chunk.Kind) {
6238   case DeclaratorChunk::Function:
6239   case DeclaratorChunk::Array:
6240   case DeclaratorChunk::Paren:
6241   case DeclaratorChunk::Pipe:
6242     llvm_unreachable("cannot be _Atomic qualified");
6243 
6244   case DeclaratorChunk::Pointer:
6245     Loc = Chunk.Ptr.AtomicQualLoc;
6246     break;
6247 
6248   case DeclaratorChunk::BlockPointer:
6249   case DeclaratorChunk::Reference:
6250   case DeclaratorChunk::MemberPointer:
6251     // FIXME: Provide a source location for the _Atomic keyword.
6252     break;
6253   }
6254 
6255   ATL.setKWLoc(Loc);
6256   ATL.setParensRange(SourceRange());
6257 }
6258 
6259 static void
fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL,const ParsedAttributesView & Attrs)6260 fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL,
6261                                  const ParsedAttributesView &Attrs) {
6262   for (const ParsedAttr &AL : Attrs) {
6263     if (AL.getKind() == ParsedAttr::AT_AddressSpace) {
6264       DASTL.setAttrNameLoc(AL.getLoc());
6265       DASTL.setAttrExprOperand(AL.getArgAsExpr(0));
6266       DASTL.setAttrOperandParensRange(SourceRange());
6267       return;
6268     }
6269   }
6270 
6271   llvm_unreachable(
6272       "no address_space attribute found at the expected location!");
6273 }
6274 
fillMatrixTypeLoc(MatrixTypeLoc MTL,const ParsedAttributesView & Attrs)6275 static void fillMatrixTypeLoc(MatrixTypeLoc MTL,
6276                               const ParsedAttributesView &Attrs) {
6277   for (const ParsedAttr &AL : Attrs) {
6278     if (AL.getKind() == ParsedAttr::AT_MatrixType) {
6279       MTL.setAttrNameLoc(AL.getLoc());
6280       MTL.setAttrRowOperand(AL.getArgAsExpr(0));
6281       MTL.setAttrColumnOperand(AL.getArgAsExpr(1));
6282       MTL.setAttrOperandParensRange(SourceRange());
6283       return;
6284     }
6285   }
6286 
6287   llvm_unreachable("no matrix_type attribute found at the expected location!");
6288 }
6289 
6290 /// Create and instantiate a TypeSourceInfo with type source information.
6291 ///
6292 /// \param T QualType referring to the type as written in source code.
6293 ///
6294 /// \param ReturnTypeInfo For declarators whose return type does not show
6295 /// up in the normal place in the declaration specifiers (such as a C++
6296 /// conversion function), this pointer will refer to a type source information
6297 /// for that return type.
6298 static TypeSourceInfo *
GetTypeSourceInfoForDeclarator(TypeProcessingState & State,QualType T,TypeSourceInfo * ReturnTypeInfo)6299 GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
6300                                QualType T, TypeSourceInfo *ReturnTypeInfo) {
6301   Sema &S = State.getSema();
6302   Declarator &D = State.getDeclarator();
6303 
6304   TypeSourceInfo *TInfo = S.Context.CreateTypeSourceInfo(T);
6305   UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
6306 
6307   // Handle parameter packs whose type is a pack expansion.
6308   if (isa<PackExpansionType>(T)) {
6309     CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
6310     CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6311   }
6312 
6313   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
6314     // An AtomicTypeLoc might be produced by an atomic qualifier in this
6315     // declarator chunk.
6316     if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
6317       fillAtomicQualLoc(ATL, D.getTypeObject(i));
6318       CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
6319     }
6320 
6321     while (MacroQualifiedTypeLoc TL = CurrTL.getAs<MacroQualifiedTypeLoc>()) {
6322       TL.setExpansionLoc(
6323           State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
6324       CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6325     }
6326 
6327     while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
6328       fillAttributedTypeLoc(TL, State);
6329       CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6330     }
6331 
6332     while (DependentAddressSpaceTypeLoc TL =
6333                CurrTL.getAs<DependentAddressSpaceTypeLoc>()) {
6334       fillDependentAddressSpaceTypeLoc(TL, D.getTypeObject(i).getAttrs());
6335       CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc();
6336     }
6337 
6338     if (MatrixTypeLoc TL = CurrTL.getAs<MatrixTypeLoc>())
6339       fillMatrixTypeLoc(TL, D.getTypeObject(i).getAttrs());
6340 
6341     // FIXME: Ordering here?
6342     while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
6343       CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6344 
6345     DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL);
6346     CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6347   }
6348 
6349   // If we have different source information for the return type, use
6350   // that.  This really only applies to C++ conversion functions.
6351   if (ReturnTypeInfo) {
6352     TypeLoc TL = ReturnTypeInfo->getTypeLoc();
6353     assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
6354     memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
6355   } else {
6356     TypeSpecLocFiller(S, S.Context, State, D.getDeclSpec()).Visit(CurrTL);
6357   }
6358 
6359   return TInfo;
6360 }
6361 
6362 /// Create a LocInfoType to hold the given QualType and TypeSourceInfo.
CreateParsedType(QualType T,TypeSourceInfo * TInfo)6363 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
6364   // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
6365   // and Sema during declaration parsing. Try deallocating/caching them when
6366   // it's appropriate, instead of allocating them and keeping them around.
6367   LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
6368                                                        TypeAlignment);
6369   new (LocT) LocInfoType(T, TInfo);
6370   assert(LocT->getTypeClass() != T->getTypeClass() &&
6371          "LocInfoType's TypeClass conflicts with an existing Type class");
6372   return ParsedType::make(QualType(LocT, 0));
6373 }
6374 
getAsStringInternal(std::string & Str,const PrintingPolicy & Policy) const6375 void LocInfoType::getAsStringInternal(std::string &Str,
6376                                       const PrintingPolicy &Policy) const {
6377   llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
6378          " was used directly instead of getting the QualType through"
6379          " GetTypeFromParser");
6380 }
6381 
ActOnTypeName(Scope * S,Declarator & D)6382 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
6383   // C99 6.7.6: Type names have no identifier.  This is already validated by
6384   // the parser.
6385   assert(D.getIdentifier() == nullptr &&
6386          "Type name should have no identifier!");
6387 
6388   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6389   QualType T = TInfo->getType();
6390   if (D.isInvalidType())
6391     return true;
6392 
6393   // Make sure there are no unused decl attributes on the declarator.
6394   // We don't want to do this for ObjC parameters because we're going
6395   // to apply them to the actual parameter declaration.
6396   // Likewise, we don't want to do this for alias declarations, because
6397   // we are actually going to build a declaration from this eventually.
6398   if (D.getContext() != DeclaratorContext::ObjCParameter &&
6399       D.getContext() != DeclaratorContext::AliasDecl &&
6400       D.getContext() != DeclaratorContext::AliasTemplate)
6401     checkUnusedDeclAttributes(D);
6402 
6403   if (getLangOpts().CPlusPlus) {
6404     // Check that there are no default arguments (C++ only).
6405     CheckExtraCXXDefaultArguments(D);
6406   }
6407 
6408   return CreateParsedType(T, TInfo);
6409 }
6410 
ActOnObjCInstanceType(SourceLocation Loc)6411 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
6412   QualType T = Context.getObjCInstanceType();
6413   TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
6414   return CreateParsedType(T, TInfo);
6415 }
6416 
6417 //===----------------------------------------------------------------------===//
6418 // Type Attribute Processing
6419 //===----------------------------------------------------------------------===//
6420 
6421 /// Build an AddressSpace index from a constant expression and diagnose any
6422 /// errors related to invalid address_spaces. Returns true on successfully
6423 /// building an AddressSpace index.
BuildAddressSpaceIndex(Sema & S,LangAS & ASIdx,const Expr * AddrSpace,SourceLocation AttrLoc)6424 static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx,
6425                                    const Expr *AddrSpace,
6426                                    SourceLocation AttrLoc) {
6427   if (!AddrSpace->isValueDependent()) {
6428     Optional<llvm::APSInt> OptAddrSpace =
6429         AddrSpace->getIntegerConstantExpr(S.Context);
6430     if (!OptAddrSpace) {
6431       S.Diag(AttrLoc, diag::err_attribute_argument_type)
6432           << "'address_space'" << AANT_ArgumentIntegerConstant
6433           << AddrSpace->getSourceRange();
6434       return false;
6435     }
6436     llvm::APSInt &addrSpace = *OptAddrSpace;
6437 
6438     // Bounds checking.
6439     if (addrSpace.isSigned()) {
6440       if (addrSpace.isNegative()) {
6441         S.Diag(AttrLoc, diag::err_attribute_address_space_negative)
6442             << AddrSpace->getSourceRange();
6443         return false;
6444       }
6445       addrSpace.setIsSigned(false);
6446     }
6447 
6448     llvm::APSInt max(addrSpace.getBitWidth());
6449     max =
6450         Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace;
6451 
6452     if (addrSpace > max) {
6453       S.Diag(AttrLoc, diag::err_attribute_address_space_too_high)
6454           << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange();
6455       return false;
6456     }
6457 
6458     ASIdx =
6459         getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue()));
6460     return true;
6461   }
6462 
6463   // Default value for DependentAddressSpaceTypes
6464   ASIdx = LangAS::Default;
6465   return true;
6466 }
6467 
6468 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression
6469 /// is uninstantiated. If instantiated it will apply the appropriate address
6470 /// space to the type. This function allows dependent template variables to be
6471 /// used in conjunction with the address_space attribute
BuildAddressSpaceAttr(QualType & T,LangAS ASIdx,Expr * AddrSpace,SourceLocation AttrLoc)6472 QualType Sema::BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
6473                                      SourceLocation AttrLoc) {
6474   if (!AddrSpace->isValueDependent()) {
6475     if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx,
6476                                             AttrLoc))
6477       return QualType();
6478 
6479     return Context.getAddrSpaceQualType(T, ASIdx);
6480   }
6481 
6482   // A check with similar intentions as checking if a type already has an
6483   // address space except for on a dependent types, basically if the
6484   // current type is already a DependentAddressSpaceType then its already
6485   // lined up to have another address space on it and we can't have
6486   // multiple address spaces on the one pointer indirection
6487   if (T->getAs<DependentAddressSpaceType>()) {
6488     Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
6489     return QualType();
6490   }
6491 
6492   return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc);
6493 }
6494 
BuildAddressSpaceAttr(QualType & T,Expr * AddrSpace,SourceLocation AttrLoc)6495 QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
6496                                      SourceLocation AttrLoc) {
6497   LangAS ASIdx;
6498   if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc))
6499     return QualType();
6500   return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc);
6501 }
6502 
6503 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
6504 /// specified type.  The attribute contains 1 argument, the id of the address
6505 /// space for the type.
HandleAddressSpaceTypeAttribute(QualType & Type,const ParsedAttr & Attr,TypeProcessingState & State)6506 static void HandleAddressSpaceTypeAttribute(QualType &Type,
6507                                             const ParsedAttr &Attr,
6508                                             TypeProcessingState &State) {
6509   Sema &S = State.getSema();
6510 
6511   // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
6512   // qualified by an address-space qualifier."
6513   if (Type->isFunctionType()) {
6514     S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
6515     Attr.setInvalid();
6516     return;
6517   }
6518 
6519   LangAS ASIdx;
6520   if (Attr.getKind() == ParsedAttr::AT_AddressSpace) {
6521 
6522     // Check the attribute arguments.
6523     if (Attr.getNumArgs() != 1) {
6524       S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
6525                                                                         << 1;
6526       Attr.setInvalid();
6527       return;
6528     }
6529 
6530     Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6531     LangAS ASIdx;
6532     if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) {
6533       Attr.setInvalid();
6534       return;
6535     }
6536 
6537     ASTContext &Ctx = S.Context;
6538     auto *ASAttr =
6539         ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx));
6540 
6541     // If the expression is not value dependent (not templated), then we can
6542     // apply the address space qualifiers just to the equivalent type.
6543     // Otherwise, we make an AttributedType with the modified and equivalent
6544     // type the same, and wrap it in a DependentAddressSpaceType. When this
6545     // dependent type is resolved, the qualifier is added to the equivalent type
6546     // later.
6547     QualType T;
6548     if (!ASArgExpr->isValueDependent()) {
6549       QualType EquivType =
6550           S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc());
6551       if (EquivType.isNull()) {
6552         Attr.setInvalid();
6553         return;
6554       }
6555       T = State.getAttributedType(ASAttr, Type, EquivType);
6556     } else {
6557       T = State.getAttributedType(ASAttr, Type, Type);
6558       T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc());
6559     }
6560 
6561     if (!T.isNull())
6562       Type = T;
6563     else
6564       Attr.setInvalid();
6565   } else {
6566     // The keyword-based type attributes imply which address space to use.
6567     ASIdx = S.getLangOpts().SYCLIsDevice ? Attr.asSYCLLangAS()
6568                                          : Attr.asOpenCLLangAS();
6569 
6570     if (ASIdx == LangAS::Default)
6571       llvm_unreachable("Invalid address space");
6572 
6573     if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx,
6574                                             Attr.getLoc())) {
6575       Attr.setInvalid();
6576       return;
6577     }
6578 
6579     Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
6580   }
6581 }
6582 
6583 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
6584 /// attribute on the specified type.
6585 ///
6586 /// Returns 'true' if the attribute was handled.
handleObjCOwnershipTypeAttr(TypeProcessingState & state,ParsedAttr & attr,QualType & type)6587 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
6588                                         ParsedAttr &attr, QualType &type) {
6589   bool NonObjCPointer = false;
6590 
6591   if (!type->isDependentType() && !type->isUndeducedType()) {
6592     if (const PointerType *ptr = type->getAs<PointerType>()) {
6593       QualType pointee = ptr->getPointeeType();
6594       if (pointee->isObjCRetainableType() || pointee->isPointerType())
6595         return false;
6596       // It is important not to lose the source info that there was an attribute
6597       // applied to non-objc pointer. We will create an attributed type but
6598       // its type will be the same as the original type.
6599       NonObjCPointer = true;
6600     } else if (!type->isObjCRetainableType()) {
6601       return false;
6602     }
6603 
6604     // Don't accept an ownership attribute in the declspec if it would
6605     // just be the return type of a block pointer.
6606     if (state.isProcessingDeclSpec()) {
6607       Declarator &D = state.getDeclarator();
6608       if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
6609                                   /*onlyBlockPointers=*/true))
6610         return false;
6611     }
6612   }
6613 
6614   Sema &S = state.getSema();
6615   SourceLocation AttrLoc = attr.getLoc();
6616   if (AttrLoc.isMacroID())
6617     AttrLoc =
6618         S.getSourceManager().getImmediateExpansionRange(AttrLoc).getBegin();
6619 
6620   if (!attr.isArgIdent(0)) {
6621     S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr
6622                                                        << AANT_ArgumentString;
6623     attr.setInvalid();
6624     return true;
6625   }
6626 
6627   IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
6628   Qualifiers::ObjCLifetime lifetime;
6629   if (II->isStr("none"))
6630     lifetime = Qualifiers::OCL_ExplicitNone;
6631   else if (II->isStr("strong"))
6632     lifetime = Qualifiers::OCL_Strong;
6633   else if (II->isStr("weak"))
6634     lifetime = Qualifiers::OCL_Weak;
6635   else if (II->isStr("autoreleasing"))
6636     lifetime = Qualifiers::OCL_Autoreleasing;
6637   else {
6638     S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II;
6639     attr.setInvalid();
6640     return true;
6641   }
6642 
6643   // Just ignore lifetime attributes other than __weak and __unsafe_unretained
6644   // outside of ARC mode.
6645   if (!S.getLangOpts().ObjCAutoRefCount &&
6646       lifetime != Qualifiers::OCL_Weak &&
6647       lifetime != Qualifiers::OCL_ExplicitNone) {
6648     return true;
6649   }
6650 
6651   SplitQualType underlyingType = type.split();
6652 
6653   // Check for redundant/conflicting ownership qualifiers.
6654   if (Qualifiers::ObjCLifetime previousLifetime
6655         = type.getQualifiers().getObjCLifetime()) {
6656     // If it's written directly, that's an error.
6657     if (S.Context.hasDirectOwnershipQualifier(type)) {
6658       S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
6659         << type;
6660       return true;
6661     }
6662 
6663     // Otherwise, if the qualifiers actually conflict, pull sugar off
6664     // and remove the ObjCLifetime qualifiers.
6665     if (previousLifetime != lifetime) {
6666       // It's possible to have multiple local ObjCLifetime qualifiers. We
6667       // can't stop after we reach a type that is directly qualified.
6668       const Type *prevTy = nullptr;
6669       while (!prevTy || prevTy != underlyingType.Ty) {
6670         prevTy = underlyingType.Ty;
6671         underlyingType = underlyingType.getSingleStepDesugaredType();
6672       }
6673       underlyingType.Quals.removeObjCLifetime();
6674     }
6675   }
6676 
6677   underlyingType.Quals.addObjCLifetime(lifetime);
6678 
6679   if (NonObjCPointer) {
6680     StringRef name = attr.getAttrName()->getName();
6681     switch (lifetime) {
6682     case Qualifiers::OCL_None:
6683     case Qualifiers::OCL_ExplicitNone:
6684       break;
6685     case Qualifiers::OCL_Strong: name = "__strong"; break;
6686     case Qualifiers::OCL_Weak: name = "__weak"; break;
6687     case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
6688     }
6689     S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
6690       << TDS_ObjCObjOrBlock << type;
6691   }
6692 
6693   // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
6694   // because having both 'T' and '__unsafe_unretained T' exist in the type
6695   // system causes unfortunate widespread consistency problems.  (For example,
6696   // they're not considered compatible types, and we mangle them identicially
6697   // as template arguments.)  These problems are all individually fixable,
6698   // but it's easier to just not add the qualifier and instead sniff it out
6699   // in specific places using isObjCInertUnsafeUnretainedType().
6700   //
6701   // Doing this does means we miss some trivial consistency checks that
6702   // would've triggered in ARC, but that's better than trying to solve all
6703   // the coexistence problems with __unsafe_unretained.
6704   if (!S.getLangOpts().ObjCAutoRefCount &&
6705       lifetime == Qualifiers::OCL_ExplicitNone) {
6706     type = state.getAttributedType(
6707         createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(S.Context, attr),
6708         type, type);
6709     return true;
6710   }
6711 
6712   QualType origType = type;
6713   if (!NonObjCPointer)
6714     type = S.Context.getQualifiedType(underlyingType);
6715 
6716   // If we have a valid source location for the attribute, use an
6717   // AttributedType instead.
6718   if (AttrLoc.isValid()) {
6719     type = state.getAttributedType(::new (S.Context)
6720                                        ObjCOwnershipAttr(S.Context, attr, II),
6721                                    origType, type);
6722   }
6723 
6724   auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
6725                             unsigned diagnostic, QualType type) {
6726     if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
6727       S.DelayedDiagnostics.add(
6728           sema::DelayedDiagnostic::makeForbiddenType(
6729               S.getSourceManager().getExpansionLoc(loc),
6730               diagnostic, type, /*ignored*/ 0));
6731     } else {
6732       S.Diag(loc, diagnostic);
6733     }
6734   };
6735 
6736   // Sometimes, __weak isn't allowed.
6737   if (lifetime == Qualifiers::OCL_Weak &&
6738       !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
6739 
6740     // Use a specialized diagnostic if the runtime just doesn't support them.
6741     unsigned diagnostic =
6742       (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
6743                                        : diag::err_arc_weak_no_runtime);
6744 
6745     // In any case, delay the diagnostic until we know what we're parsing.
6746     diagnoseOrDelay(S, AttrLoc, diagnostic, type);
6747 
6748     attr.setInvalid();
6749     return true;
6750   }
6751 
6752   // Forbid __weak for class objects marked as
6753   // objc_arc_weak_reference_unavailable
6754   if (lifetime == Qualifiers::OCL_Weak) {
6755     if (const ObjCObjectPointerType *ObjT =
6756           type->getAs<ObjCObjectPointerType>()) {
6757       if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
6758         if (Class->isArcWeakrefUnavailable()) {
6759           S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
6760           S.Diag(ObjT->getInterfaceDecl()->getLocation(),
6761                  diag::note_class_declared);
6762         }
6763       }
6764     }
6765   }
6766 
6767   return true;
6768 }
6769 
6770 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
6771 /// attribute on the specified type.  Returns true to indicate that
6772 /// the attribute was handled, false to indicate that the type does
6773 /// not permit the attribute.
handleObjCGCTypeAttr(TypeProcessingState & state,ParsedAttr & attr,QualType & type)6774 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
6775                                  QualType &type) {
6776   Sema &S = state.getSema();
6777 
6778   // Delay if this isn't some kind of pointer.
6779   if (!type->isPointerType() &&
6780       !type->isObjCObjectPointerType() &&
6781       !type->isBlockPointerType())
6782     return false;
6783 
6784   if (type.getObjCGCAttr() != Qualifiers::GCNone) {
6785     S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
6786     attr.setInvalid();
6787     return true;
6788   }
6789 
6790   // Check the attribute arguments.
6791   if (!attr.isArgIdent(0)) {
6792     S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
6793         << attr << AANT_ArgumentString;
6794     attr.setInvalid();
6795     return true;
6796   }
6797   Qualifiers::GC GCAttr;
6798   if (attr.getNumArgs() > 1) {
6799     S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr
6800                                                                       << 1;
6801     attr.setInvalid();
6802     return true;
6803   }
6804 
6805   IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
6806   if (II->isStr("weak"))
6807     GCAttr = Qualifiers::Weak;
6808   else if (II->isStr("strong"))
6809     GCAttr = Qualifiers::Strong;
6810   else {
6811     S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
6812         << attr << II;
6813     attr.setInvalid();
6814     return true;
6815   }
6816 
6817   QualType origType = type;
6818   type = S.Context.getObjCGCQualType(origType, GCAttr);
6819 
6820   // Make an attributed type to preserve the source information.
6821   if (attr.getLoc().isValid())
6822     type = state.getAttributedType(
6823         ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type);
6824 
6825   return true;
6826 }
6827 
6828 namespace {
6829   /// A helper class to unwrap a type down to a function for the
6830   /// purposes of applying attributes there.
6831   ///
6832   /// Use:
6833   ///   FunctionTypeUnwrapper unwrapped(SemaRef, T);
6834   ///   if (unwrapped.isFunctionType()) {
6835   ///     const FunctionType *fn = unwrapped.get();
6836   ///     // change fn somehow
6837   ///     T = unwrapped.wrap(fn);
6838   ///   }
6839   struct FunctionTypeUnwrapper {
6840     enum WrapKind {
6841       Desugar,
6842       Attributed,
6843       Parens,
6844       Array,
6845       Pointer,
6846       BlockPointer,
6847       Reference,
6848       MemberPointer,
6849       MacroQualified,
6850     };
6851 
6852     QualType Original;
6853     const FunctionType *Fn;
6854     SmallVector<unsigned char /*WrapKind*/, 8> Stack;
6855 
FunctionTypeUnwrapper__anone2590ed01311::FunctionTypeUnwrapper6856     FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
6857       while (true) {
6858         const Type *Ty = T.getTypePtr();
6859         if (isa<FunctionType>(Ty)) {
6860           Fn = cast<FunctionType>(Ty);
6861           return;
6862         } else if (isa<ParenType>(Ty)) {
6863           T = cast<ParenType>(Ty)->getInnerType();
6864           Stack.push_back(Parens);
6865         } else if (isa<ConstantArrayType>(Ty) || isa<VariableArrayType>(Ty) ||
6866                    isa<IncompleteArrayType>(Ty)) {
6867           T = cast<ArrayType>(Ty)->getElementType();
6868           Stack.push_back(Array);
6869         } else if (isa<PointerType>(Ty)) {
6870           T = cast<PointerType>(Ty)->getPointeeType();
6871           Stack.push_back(Pointer);
6872         } else if (isa<BlockPointerType>(Ty)) {
6873           T = cast<BlockPointerType>(Ty)->getPointeeType();
6874           Stack.push_back(BlockPointer);
6875         } else if (isa<MemberPointerType>(Ty)) {
6876           T = cast<MemberPointerType>(Ty)->getPointeeType();
6877           Stack.push_back(MemberPointer);
6878         } else if (isa<ReferenceType>(Ty)) {
6879           T = cast<ReferenceType>(Ty)->getPointeeType();
6880           Stack.push_back(Reference);
6881         } else if (isa<AttributedType>(Ty)) {
6882           T = cast<AttributedType>(Ty)->getEquivalentType();
6883           Stack.push_back(Attributed);
6884         } else if (isa<MacroQualifiedType>(Ty)) {
6885           T = cast<MacroQualifiedType>(Ty)->getUnderlyingType();
6886           Stack.push_back(MacroQualified);
6887         } else {
6888           const Type *DTy = Ty->getUnqualifiedDesugaredType();
6889           if (Ty == DTy) {
6890             Fn = nullptr;
6891             return;
6892           }
6893 
6894           T = QualType(DTy, 0);
6895           Stack.push_back(Desugar);
6896         }
6897       }
6898     }
6899 
isFunctionType__anone2590ed01311::FunctionTypeUnwrapper6900     bool isFunctionType() const { return (Fn != nullptr); }
get__anone2590ed01311::FunctionTypeUnwrapper6901     const FunctionType *get() const { return Fn; }
6902 
wrap__anone2590ed01311::FunctionTypeUnwrapper6903     QualType wrap(Sema &S, const FunctionType *New) {
6904       // If T wasn't modified from the unwrapped type, do nothing.
6905       if (New == get()) return Original;
6906 
6907       Fn = New;
6908       return wrap(S.Context, Original, 0);
6909     }
6910 
6911   private:
wrap__anone2590ed01311::FunctionTypeUnwrapper6912     QualType wrap(ASTContext &C, QualType Old, unsigned I) {
6913       if (I == Stack.size())
6914         return C.getQualifiedType(Fn, Old.getQualifiers());
6915 
6916       // Build up the inner type, applying the qualifiers from the old
6917       // type to the new type.
6918       SplitQualType SplitOld = Old.split();
6919 
6920       // As a special case, tail-recurse if there are no qualifiers.
6921       if (SplitOld.Quals.empty())
6922         return wrap(C, SplitOld.Ty, I);
6923       return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
6924     }
6925 
wrap__anone2590ed01311::FunctionTypeUnwrapper6926     QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
6927       if (I == Stack.size()) return QualType(Fn, 0);
6928 
6929       switch (static_cast<WrapKind>(Stack[I++])) {
6930       case Desugar:
6931         // This is the point at which we potentially lose source
6932         // information.
6933         return wrap(C, Old->getUnqualifiedDesugaredType(), I);
6934 
6935       case Attributed:
6936         return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
6937 
6938       case Parens: {
6939         QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
6940         return C.getParenType(New);
6941       }
6942 
6943       case MacroQualified:
6944         return wrap(C, cast<MacroQualifiedType>(Old)->getUnderlyingType(), I);
6945 
6946       case Array: {
6947         if (const auto *CAT = dyn_cast<ConstantArrayType>(Old)) {
6948           QualType New = wrap(C, CAT->getElementType(), I);
6949           return C.getConstantArrayType(New, CAT->getSize(), CAT->getSizeExpr(),
6950                                         CAT->getSizeModifier(),
6951                                         CAT->getIndexTypeCVRQualifiers());
6952         }
6953 
6954         if (const auto *VAT = dyn_cast<VariableArrayType>(Old)) {
6955           QualType New = wrap(C, VAT->getElementType(), I);
6956           return C.getVariableArrayType(
6957               New, VAT->getSizeExpr(), VAT->getSizeModifier(),
6958               VAT->getIndexTypeCVRQualifiers(), VAT->getBracketsRange());
6959         }
6960 
6961         const auto *IAT = cast<IncompleteArrayType>(Old);
6962         QualType New = wrap(C, IAT->getElementType(), I);
6963         return C.getIncompleteArrayType(New, IAT->getSizeModifier(),
6964                                         IAT->getIndexTypeCVRQualifiers());
6965       }
6966 
6967       case Pointer: {
6968         QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
6969         return C.getPointerType(New);
6970       }
6971 
6972       case BlockPointer: {
6973         QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
6974         return C.getBlockPointerType(New);
6975       }
6976 
6977       case MemberPointer: {
6978         const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
6979         QualType New = wrap(C, OldMPT->getPointeeType(), I);
6980         return C.getMemberPointerType(New, OldMPT->getClass());
6981       }
6982 
6983       case Reference: {
6984         const ReferenceType *OldRef = cast<ReferenceType>(Old);
6985         QualType New = wrap(C, OldRef->getPointeeType(), I);
6986         if (isa<LValueReferenceType>(OldRef))
6987           return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
6988         else
6989           return C.getRValueReferenceType(New);
6990       }
6991       }
6992 
6993       llvm_unreachable("unknown wrapping kind");
6994     }
6995   };
6996 } // end anonymous namespace
6997 
handleMSPointerTypeQualifierAttr(TypeProcessingState & State,ParsedAttr & PAttr,QualType & Type)6998 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
6999                                              ParsedAttr &PAttr, QualType &Type) {
7000   Sema &S = State.getSema();
7001 
7002   Attr *A;
7003   switch (PAttr.getKind()) {
7004   default: llvm_unreachable("Unknown attribute kind");
7005   case ParsedAttr::AT_Ptr32:
7006     A = createSimpleAttr<Ptr32Attr>(S.Context, PAttr);
7007     break;
7008   case ParsedAttr::AT_Ptr64:
7009     A = createSimpleAttr<Ptr64Attr>(S.Context, PAttr);
7010     break;
7011   case ParsedAttr::AT_SPtr:
7012     A = createSimpleAttr<SPtrAttr>(S.Context, PAttr);
7013     break;
7014   case ParsedAttr::AT_UPtr:
7015     A = createSimpleAttr<UPtrAttr>(S.Context, PAttr);
7016     break;
7017   }
7018 
7019   std::bitset<attr::LastAttr> Attrs;
7020   attr::Kind NewAttrKind = A->getKind();
7021   QualType Desugared = Type;
7022   const AttributedType *AT = dyn_cast<AttributedType>(Type);
7023   while (AT) {
7024     Attrs[AT->getAttrKind()] = true;
7025     Desugared = AT->getModifiedType();
7026     AT = dyn_cast<AttributedType>(Desugared);
7027   }
7028 
7029   // You cannot specify duplicate type attributes, so if the attribute has
7030   // already been applied, flag it.
7031   if (Attrs[NewAttrKind]) {
7032     S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7033     return true;
7034   }
7035   Attrs[NewAttrKind] = true;
7036 
7037   // You cannot have both __sptr and __uptr on the same type, nor can you
7038   // have __ptr32 and __ptr64.
7039   if (Attrs[attr::Ptr32] && Attrs[attr::Ptr64]) {
7040     S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7041         << "'__ptr32'"
7042         << "'__ptr64'";
7043     return true;
7044   } else if (Attrs[attr::SPtr] && Attrs[attr::UPtr]) {
7045     S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7046         << "'__sptr'"
7047         << "'__uptr'";
7048     return true;
7049   }
7050 
7051   // Pointer type qualifiers can only operate on pointer types, but not
7052   // pointer-to-member types.
7053   //
7054   // FIXME: Should we really be disallowing this attribute if there is any
7055   // type sugar between it and the pointer (other than attributes)? Eg, this
7056   // disallows the attribute on a parenthesized pointer.
7057   // And if so, should we really allow *any* type attribute?
7058   if (!isa<PointerType>(Desugared)) {
7059     if (Type->isMemberPointerType())
7060       S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr;
7061     else
7062       S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0;
7063     return true;
7064   }
7065 
7066   // Add address space to type based on its attributes.
7067   LangAS ASIdx = LangAS::Default;
7068   uint64_t PtrWidth = S.Context.getTargetInfo().getPointerWidth(0);
7069   if (PtrWidth == 32) {
7070     if (Attrs[attr::Ptr64])
7071       ASIdx = LangAS::ptr64;
7072     else if (Attrs[attr::UPtr])
7073       ASIdx = LangAS::ptr32_uptr;
7074   } else if (PtrWidth == 64 && Attrs[attr::Ptr32]) {
7075     if (Attrs[attr::UPtr])
7076       ASIdx = LangAS::ptr32_uptr;
7077     else
7078       ASIdx = LangAS::ptr32_sptr;
7079   }
7080 
7081   QualType Pointee = Type->getPointeeType();
7082   if (ASIdx != LangAS::Default)
7083     Pointee = S.Context.getAddrSpaceQualType(
7084         S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7085   Type = State.getAttributedType(A, Type, S.Context.getPointerType(Pointee));
7086   return false;
7087 }
7088 
7089 /// Map a nullability attribute kind to a nullability kind.
mapNullabilityAttrKind(ParsedAttr::Kind kind)7090 static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind) {
7091   switch (kind) {
7092   case ParsedAttr::AT_TypeNonNull:
7093     return NullabilityKind::NonNull;
7094 
7095   case ParsedAttr::AT_TypeNullable:
7096     return NullabilityKind::Nullable;
7097 
7098   case ParsedAttr::AT_TypeNullableResult:
7099     return NullabilityKind::NullableResult;
7100 
7101   case ParsedAttr::AT_TypeNullUnspecified:
7102     return NullabilityKind::Unspecified;
7103 
7104   default:
7105     llvm_unreachable("not a nullability attribute kind");
7106   }
7107 }
7108 
7109 /// Applies a nullability type specifier to the given type, if possible.
7110 ///
7111 /// \param state The type processing state.
7112 ///
7113 /// \param type The type to which the nullability specifier will be
7114 /// added. On success, this type will be updated appropriately.
7115 ///
7116 /// \param attr The attribute as written on the type.
7117 ///
7118 /// \param allowOnArrayType Whether to accept nullability specifiers on an
7119 /// array type (e.g., because it will decay to a pointer).
7120 ///
7121 /// \returns true if a problem has been diagnosed, false on success.
checkNullabilityTypeSpecifier(TypeProcessingState & state,QualType & type,ParsedAttr & attr,bool allowOnArrayType)7122 static bool checkNullabilityTypeSpecifier(TypeProcessingState &state,
7123                                           QualType &type,
7124                                           ParsedAttr &attr,
7125                                           bool allowOnArrayType) {
7126   Sema &S = state.getSema();
7127 
7128   NullabilityKind nullability = mapNullabilityAttrKind(attr.getKind());
7129   SourceLocation nullabilityLoc = attr.getLoc();
7130   bool isContextSensitive = attr.isContextSensitiveKeywordAttribute();
7131 
7132   recordNullabilitySeen(S, nullabilityLoc);
7133 
7134   // Check for existing nullability attributes on the type.
7135   QualType desugared = type;
7136   while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
7137     // Check whether there is already a null
7138     if (auto existingNullability = attributed->getImmediateNullability()) {
7139       // Duplicated nullability.
7140       if (nullability == *existingNullability) {
7141         S.Diag(nullabilityLoc, diag::warn_nullability_duplicate)
7142           << DiagNullabilityKind(nullability, isContextSensitive)
7143           << FixItHint::CreateRemoval(nullabilityLoc);
7144 
7145         break;
7146       }
7147 
7148       // Conflicting nullability.
7149       S.Diag(nullabilityLoc, diag::err_nullability_conflicting)
7150         << DiagNullabilityKind(nullability, isContextSensitive)
7151         << DiagNullabilityKind(*existingNullability, false);
7152       return true;
7153     }
7154 
7155     desugared = attributed->getModifiedType();
7156   }
7157 
7158   // If there is already a different nullability specifier, complain.
7159   // This (unlike the code above) looks through typedefs that might
7160   // have nullability specifiers on them, which means we cannot
7161   // provide a useful Fix-It.
7162   if (auto existingNullability = desugared->getNullability(S.Context)) {
7163     if (nullability != *existingNullability) {
7164       S.Diag(nullabilityLoc, diag::err_nullability_conflicting)
7165         << DiagNullabilityKind(nullability, isContextSensitive)
7166         << DiagNullabilityKind(*existingNullability, false);
7167 
7168       // Try to find the typedef with the existing nullability specifier.
7169       if (auto typedefType = desugared->getAs<TypedefType>()) {
7170         TypedefNameDecl *typedefDecl = typedefType->getDecl();
7171         QualType underlyingType = typedefDecl->getUnderlyingType();
7172         if (auto typedefNullability
7173               = AttributedType::stripOuterNullability(underlyingType)) {
7174           if (*typedefNullability == *existingNullability) {
7175             S.Diag(typedefDecl->getLocation(), diag::note_nullability_here)
7176               << DiagNullabilityKind(*existingNullability, false);
7177           }
7178         }
7179       }
7180 
7181       return true;
7182     }
7183   }
7184 
7185   // If this definitely isn't a pointer type, reject the specifier.
7186   if (!desugared->canHaveNullability() &&
7187       !(allowOnArrayType && desugared->isArrayType())) {
7188     S.Diag(nullabilityLoc, diag::err_nullability_nonpointer)
7189       << DiagNullabilityKind(nullability, isContextSensitive) << type;
7190     return true;
7191   }
7192 
7193   // For the context-sensitive keywords/Objective-C property
7194   // attributes, require that the type be a single-level pointer.
7195   if (isContextSensitive) {
7196     // Make sure that the pointee isn't itself a pointer type.
7197     const Type *pointeeType = nullptr;
7198     if (desugared->isArrayType())
7199       pointeeType = desugared->getArrayElementTypeNoTypeQual();
7200     else if (desugared->isAnyPointerType())
7201       pointeeType = desugared->getPointeeType().getTypePtr();
7202 
7203     if (pointeeType && (pointeeType->isAnyPointerType() ||
7204                         pointeeType->isObjCObjectPointerType() ||
7205                         pointeeType->isMemberPointerType())) {
7206       S.Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
7207         << DiagNullabilityKind(nullability, true)
7208         << type;
7209       S.Diag(nullabilityLoc, diag::note_nullability_type_specifier)
7210         << DiagNullabilityKind(nullability, false)
7211         << type
7212         << FixItHint::CreateReplacement(nullabilityLoc,
7213                                         getNullabilitySpelling(nullability));
7214       return true;
7215     }
7216   }
7217 
7218   // Form the attributed type.
7219   type = state.getAttributedType(
7220       createNullabilityAttr(S.Context, attr, nullability), type, type);
7221   return false;
7222 }
7223 
7224 /// Check the application of the Objective-C '__kindof' qualifier to
7225 /// the given type.
checkObjCKindOfType(TypeProcessingState & state,QualType & type,ParsedAttr & attr)7226 static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type,
7227                                 ParsedAttr &attr) {
7228   Sema &S = state.getSema();
7229 
7230   if (isa<ObjCTypeParamType>(type)) {
7231     // Build the attributed type to record where __kindof occurred.
7232     type = state.getAttributedType(
7233         createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, type);
7234     return false;
7235   }
7236 
7237   // Find out if it's an Objective-C object or object pointer type;
7238   const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
7239   const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
7240                                           : type->getAs<ObjCObjectType>();
7241 
7242   // If not, we can't apply __kindof.
7243   if (!objType) {
7244     // FIXME: Handle dependent types that aren't yet object types.
7245     S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject)
7246       << type;
7247     return true;
7248   }
7249 
7250   // Rebuild the "equivalent" type, which pushes __kindof down into
7251   // the object type.
7252   // There is no need to apply kindof on an unqualified id type.
7253   QualType equivType = S.Context.getObjCObjectType(
7254       objType->getBaseType(), objType->getTypeArgsAsWritten(),
7255       objType->getProtocols(),
7256       /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
7257 
7258   // If we started with an object pointer type, rebuild it.
7259   if (ptrType) {
7260     equivType = S.Context.getObjCObjectPointerType(equivType);
7261     if (auto nullability = type->getNullability(S.Context)) {
7262       // We create a nullability attribute from the __kindof attribute.
7263       // Make sure that will make sense.
7264       assert(attr.getAttributeSpellingListIndex() == 0 &&
7265              "multiple spellings for __kindof?");
7266       Attr *A = createNullabilityAttr(S.Context, attr, *nullability);
7267       A->setImplicit(true);
7268       equivType = state.getAttributedType(A, equivType, equivType);
7269     }
7270   }
7271 
7272   // Build the attributed type to record where __kindof occurred.
7273   type = state.getAttributedType(
7274       createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, equivType);
7275   return false;
7276 }
7277 
7278 /// Distribute a nullability type attribute that cannot be applied to
7279 /// the type specifier to a pointer, block pointer, or member pointer
7280 /// declarator, complaining if necessary.
7281 ///
7282 /// \returns true if the nullability annotation was distributed, false
7283 /// otherwise.
distributeNullabilityTypeAttr(TypeProcessingState & state,QualType type,ParsedAttr & attr)7284 static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
7285                                           QualType type, ParsedAttr &attr) {
7286   Declarator &declarator = state.getDeclarator();
7287 
7288   /// Attempt to move the attribute to the specified chunk.
7289   auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
7290     // If there is already a nullability attribute there, don't add
7291     // one.
7292     if (hasNullabilityAttr(chunk.getAttrs()))
7293       return false;
7294 
7295     // Complain about the nullability qualifier being in the wrong
7296     // place.
7297     enum {
7298       PK_Pointer,
7299       PK_BlockPointer,
7300       PK_MemberPointer,
7301       PK_FunctionPointer,
7302       PK_MemberFunctionPointer,
7303     } pointerKind
7304       = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
7305                                                              : PK_Pointer)
7306         : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
7307         : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
7308 
7309     auto diag = state.getSema().Diag(attr.getLoc(),
7310                                      diag::warn_nullability_declspec)
7311       << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
7312                              attr.isContextSensitiveKeywordAttribute())
7313       << type
7314       << static_cast<unsigned>(pointerKind);
7315 
7316     // FIXME: MemberPointer chunks don't carry the location of the *.
7317     if (chunk.Kind != DeclaratorChunk::MemberPointer) {
7318       diag << FixItHint::CreateRemoval(attr.getLoc())
7319            << FixItHint::CreateInsertion(
7320                   state.getSema().getPreprocessor().getLocForEndOfToken(
7321                       chunk.Loc),
7322                   " " + attr.getAttrName()->getName().str() + " ");
7323     }
7324 
7325     moveAttrFromListToList(attr, state.getCurrentAttributes(),
7326                            chunk.getAttrs());
7327     return true;
7328   };
7329 
7330   // Move it to the outermost pointer, member pointer, or block
7331   // pointer declarator.
7332   for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
7333     DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
7334     switch (chunk.Kind) {
7335     case DeclaratorChunk::Pointer:
7336     case DeclaratorChunk::BlockPointer:
7337     case DeclaratorChunk::MemberPointer:
7338       return moveToChunk(chunk, false);
7339 
7340     case DeclaratorChunk::Paren:
7341     case DeclaratorChunk::Array:
7342       continue;
7343 
7344     case DeclaratorChunk::Function:
7345       // Try to move past the return type to a function/block/member
7346       // function pointer.
7347       if (DeclaratorChunk *dest = maybeMovePastReturnType(
7348                                     declarator, i,
7349                                     /*onlyBlockPointers=*/false)) {
7350         return moveToChunk(*dest, true);
7351       }
7352 
7353       return false;
7354 
7355     // Don't walk through these.
7356     case DeclaratorChunk::Reference:
7357     case DeclaratorChunk::Pipe:
7358       return false;
7359     }
7360   }
7361 
7362   return false;
7363 }
7364 
getCCTypeAttr(ASTContext & Ctx,ParsedAttr & Attr)7365 static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) {
7366   assert(!Attr.isInvalid());
7367   switch (Attr.getKind()) {
7368   default:
7369     llvm_unreachable("not a calling convention attribute");
7370   case ParsedAttr::AT_CDecl:
7371     return createSimpleAttr<CDeclAttr>(Ctx, Attr);
7372   case ParsedAttr::AT_FastCall:
7373     return createSimpleAttr<FastCallAttr>(Ctx, Attr);
7374   case ParsedAttr::AT_StdCall:
7375     return createSimpleAttr<StdCallAttr>(Ctx, Attr);
7376   case ParsedAttr::AT_ThisCall:
7377     return createSimpleAttr<ThisCallAttr>(Ctx, Attr);
7378   case ParsedAttr::AT_RegCall:
7379     return createSimpleAttr<RegCallAttr>(Ctx, Attr);
7380   case ParsedAttr::AT_Pascal:
7381     return createSimpleAttr<PascalAttr>(Ctx, Attr);
7382   case ParsedAttr::AT_SwiftCall:
7383     return createSimpleAttr<SwiftCallAttr>(Ctx, Attr);
7384   case ParsedAttr::AT_SwiftAsyncCall:
7385     return createSimpleAttr<SwiftAsyncCallAttr>(Ctx, Attr);
7386   case ParsedAttr::AT_VectorCall:
7387     return createSimpleAttr<VectorCallAttr>(Ctx, Attr);
7388   case ParsedAttr::AT_AArch64VectorPcs:
7389     return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, Attr);
7390   case ParsedAttr::AT_Pcs: {
7391     // The attribute may have had a fixit applied where we treated an
7392     // identifier as a string literal.  The contents of the string are valid,
7393     // but the form may not be.
7394     StringRef Str;
7395     if (Attr.isArgExpr(0))
7396       Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
7397     else
7398       Str = Attr.getArgAsIdent(0)->Ident->getName();
7399     PcsAttr::PCSType Type;
7400     if (!PcsAttr::ConvertStrToPCSType(Str, Type))
7401       llvm_unreachable("already validated the attribute");
7402     return ::new (Ctx) PcsAttr(Ctx, Attr, Type);
7403   }
7404   case ParsedAttr::AT_IntelOclBicc:
7405     return createSimpleAttr<IntelOclBiccAttr>(Ctx, Attr);
7406   case ParsedAttr::AT_MSABI:
7407     return createSimpleAttr<MSABIAttr>(Ctx, Attr);
7408   case ParsedAttr::AT_SysVABI:
7409     return createSimpleAttr<SysVABIAttr>(Ctx, Attr);
7410   case ParsedAttr::AT_PreserveMost:
7411     return createSimpleAttr<PreserveMostAttr>(Ctx, Attr);
7412   case ParsedAttr::AT_PreserveAll:
7413     return createSimpleAttr<PreserveAllAttr>(Ctx, Attr);
7414   }
7415   llvm_unreachable("unexpected attribute kind!");
7416 }
7417 
7418 /// Process an individual function attribute.  Returns true to
7419 /// indicate that the attribute was handled, false if it wasn't.
handleFunctionTypeAttr(TypeProcessingState & state,ParsedAttr & attr,QualType & type)7420 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
7421                                    QualType &type) {
7422   Sema &S = state.getSema();
7423 
7424   FunctionTypeUnwrapper unwrapped(S, type);
7425 
7426   if (attr.getKind() == ParsedAttr::AT_NoReturn) {
7427     if (S.CheckAttrNoArgs(attr))
7428       return true;
7429 
7430     // Delay if this is not a function type.
7431     if (!unwrapped.isFunctionType())
7432       return false;
7433 
7434     // Otherwise we can process right away.
7435     FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
7436     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7437     return true;
7438   }
7439 
7440   if (attr.getKind() == ParsedAttr::AT_CmseNSCall) {
7441     // Delay if this is not a function type.
7442     if (!unwrapped.isFunctionType())
7443       return false;
7444 
7445     // Ignore if we don't have CMSE enabled.
7446     if (!S.getLangOpts().Cmse) {
7447       S.Diag(attr.getLoc(), diag::warn_attribute_ignored) << attr;
7448       attr.setInvalid();
7449       return true;
7450     }
7451 
7452     // Otherwise we can process right away.
7453     FunctionType::ExtInfo EI =
7454         unwrapped.get()->getExtInfo().withCmseNSCall(true);
7455     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7456     return true;
7457   }
7458 
7459   // ns_returns_retained is not always a type attribute, but if we got
7460   // here, we're treating it as one right now.
7461   if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) {
7462     if (attr.getNumArgs()) return true;
7463 
7464     // Delay if this is not a function type.
7465     if (!unwrapped.isFunctionType())
7466       return false;
7467 
7468     // Check whether the return type is reasonable.
7469     if (S.checkNSReturnsRetainedReturnType(attr.getLoc(),
7470                                            unwrapped.get()->getReturnType()))
7471       return true;
7472 
7473     // Only actually change the underlying type in ARC builds.
7474     QualType origType = type;
7475     if (state.getSema().getLangOpts().ObjCAutoRefCount) {
7476       FunctionType::ExtInfo EI
7477         = unwrapped.get()->getExtInfo().withProducesResult(true);
7478       type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7479     }
7480     type = state.getAttributedType(
7481         createSimpleAttr<NSReturnsRetainedAttr>(S.Context, attr),
7482         origType, type);
7483     return true;
7484   }
7485 
7486   if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) {
7487     if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
7488       return true;
7489 
7490     // Delay if this is not a function type.
7491     if (!unwrapped.isFunctionType())
7492       return false;
7493 
7494     FunctionType::ExtInfo EI =
7495         unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true);
7496     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7497     return true;
7498   }
7499 
7500   if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) {
7501     if (!S.getLangOpts().CFProtectionBranch) {
7502       S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored);
7503       attr.setInvalid();
7504       return true;
7505     }
7506 
7507     if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
7508       return true;
7509 
7510     // If this is not a function type, warning will be asserted by subject
7511     // check.
7512     if (!unwrapped.isFunctionType())
7513       return true;
7514 
7515     FunctionType::ExtInfo EI =
7516       unwrapped.get()->getExtInfo().withNoCfCheck(true);
7517     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7518     return true;
7519   }
7520 
7521   if (attr.getKind() == ParsedAttr::AT_Regparm) {
7522     unsigned value;
7523     if (S.CheckRegparmAttr(attr, value))
7524       return true;
7525 
7526     // Delay if this is not a function type.
7527     if (!unwrapped.isFunctionType())
7528       return false;
7529 
7530     // Diagnose regparm with fastcall.
7531     const FunctionType *fn = unwrapped.get();
7532     CallingConv CC = fn->getCallConv();
7533     if (CC == CC_X86FastCall) {
7534       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
7535         << FunctionType::getNameForCallConv(CC)
7536         << "regparm";
7537       attr.setInvalid();
7538       return true;
7539     }
7540 
7541     FunctionType::ExtInfo EI =
7542       unwrapped.get()->getExtInfo().withRegParm(value);
7543     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7544     return true;
7545   }
7546 
7547   if (attr.getKind() == ParsedAttr::AT_NoThrow) {
7548     // Delay if this is not a function type.
7549     if (!unwrapped.isFunctionType())
7550       return false;
7551 
7552     if (S.CheckAttrNoArgs(attr)) {
7553       attr.setInvalid();
7554       return true;
7555     }
7556 
7557     // Otherwise we can process right away.
7558     auto *Proto = unwrapped.get()->castAs<FunctionProtoType>();
7559 
7560     // MSVC ignores nothrow if it is in conflict with an explicit exception
7561     // specification.
7562     if (Proto->hasExceptionSpec()) {
7563       switch (Proto->getExceptionSpecType()) {
7564       case EST_None:
7565         llvm_unreachable("This doesn't have an exception spec!");
7566 
7567       case EST_DynamicNone:
7568       case EST_BasicNoexcept:
7569       case EST_NoexceptTrue:
7570       case EST_NoThrow:
7571         // Exception spec doesn't conflict with nothrow, so don't warn.
7572         LLVM_FALLTHROUGH;
7573       case EST_Unparsed:
7574       case EST_Uninstantiated:
7575       case EST_DependentNoexcept:
7576       case EST_Unevaluated:
7577         // We don't have enough information to properly determine if there is a
7578         // conflict, so suppress the warning.
7579         break;
7580       case EST_Dynamic:
7581       case EST_MSAny:
7582       case EST_NoexceptFalse:
7583         S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored);
7584         break;
7585       }
7586       return true;
7587     }
7588 
7589     type = unwrapped.wrap(
7590         S, S.Context
7591                .getFunctionTypeWithExceptionSpec(
7592                    QualType{Proto, 0},
7593                    FunctionProtoType::ExceptionSpecInfo{EST_NoThrow})
7594                ->getAs<FunctionType>());
7595     return true;
7596   }
7597 
7598   // Delay if the type didn't work out to a function.
7599   if (!unwrapped.isFunctionType()) return false;
7600 
7601   // Otherwise, a calling convention.
7602   CallingConv CC;
7603   if (S.CheckCallingConvAttr(attr, CC))
7604     return true;
7605 
7606   const FunctionType *fn = unwrapped.get();
7607   CallingConv CCOld = fn->getCallConv();
7608   Attr *CCAttr = getCCTypeAttr(S.Context, attr);
7609 
7610   if (CCOld != CC) {
7611     // Error out on when there's already an attribute on the type
7612     // and the CCs don't match.
7613     if (S.getCallingConvAttributedType(type)) {
7614       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
7615         << FunctionType::getNameForCallConv(CC)
7616         << FunctionType::getNameForCallConv(CCOld);
7617       attr.setInvalid();
7618       return true;
7619     }
7620   }
7621 
7622   // Diagnose use of variadic functions with calling conventions that
7623   // don't support them (e.g. because they're callee-cleanup).
7624   // We delay warning about this on unprototyped function declarations
7625   // until after redeclaration checking, just in case we pick up a
7626   // prototype that way.  And apparently we also "delay" warning about
7627   // unprototyped function types in general, despite not necessarily having
7628   // much ability to diagnose it later.
7629   if (!supportsVariadicCall(CC)) {
7630     const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
7631     if (FnP && FnP->isVariadic()) {
7632       // stdcall and fastcall are ignored with a warning for GCC and MS
7633       // compatibility.
7634       if (CC == CC_X86StdCall || CC == CC_X86FastCall)
7635         return S.Diag(attr.getLoc(), diag::warn_cconv_unsupported)
7636                << FunctionType::getNameForCallConv(CC)
7637                << (int)Sema::CallingConventionIgnoredReason::VariadicFunction;
7638 
7639       attr.setInvalid();
7640       return S.Diag(attr.getLoc(), diag::err_cconv_varargs)
7641              << FunctionType::getNameForCallConv(CC);
7642     }
7643   }
7644 
7645   // Also diagnose fastcall with regparm.
7646   if (CC == CC_X86FastCall && fn->getHasRegParm()) {
7647     S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
7648         << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
7649     attr.setInvalid();
7650     return true;
7651   }
7652 
7653   // Modify the CC from the wrapped function type, wrap it all back, and then
7654   // wrap the whole thing in an AttributedType as written.  The modified type
7655   // might have a different CC if we ignored the attribute.
7656   QualType Equivalent;
7657   if (CCOld == CC) {
7658     Equivalent = type;
7659   } else {
7660     auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
7661     Equivalent =
7662       unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7663   }
7664   type = state.getAttributedType(CCAttr, type, Equivalent);
7665   return true;
7666 }
7667 
hasExplicitCallingConv(QualType T)7668 bool Sema::hasExplicitCallingConv(QualType T) {
7669   const AttributedType *AT;
7670 
7671   // Stop if we'd be stripping off a typedef sugar node to reach the
7672   // AttributedType.
7673   while ((AT = T->getAs<AttributedType>()) &&
7674          AT->getAs<TypedefType>() == T->getAs<TypedefType>()) {
7675     if (AT->isCallingConv())
7676       return true;
7677     T = AT->getModifiedType();
7678   }
7679   return false;
7680 }
7681 
adjustMemberFunctionCC(QualType & T,bool IsStatic,bool IsCtorOrDtor,SourceLocation Loc)7682 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
7683                                   SourceLocation Loc) {
7684   FunctionTypeUnwrapper Unwrapped(*this, T);
7685   const FunctionType *FT = Unwrapped.get();
7686   bool IsVariadic = (isa<FunctionProtoType>(FT) &&
7687                      cast<FunctionProtoType>(FT)->isVariadic());
7688   CallingConv CurCC = FT->getCallConv();
7689   CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
7690 
7691   if (CurCC == ToCC)
7692     return;
7693 
7694   // MS compiler ignores explicit calling convention attributes on structors. We
7695   // should do the same.
7696   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
7697     // Issue a warning on ignored calling convention -- except of __stdcall.
7698     // Again, this is what MS compiler does.
7699     if (CurCC != CC_X86StdCall)
7700       Diag(Loc, diag::warn_cconv_unsupported)
7701           << FunctionType::getNameForCallConv(CurCC)
7702           << (int)Sema::CallingConventionIgnoredReason::ConstructorDestructor;
7703   // Default adjustment.
7704   } else {
7705     // Only adjust types with the default convention.  For example, on Windows
7706     // we should adjust a __cdecl type to __thiscall for instance methods, and a
7707     // __thiscall type to __cdecl for static methods.
7708     CallingConv DefaultCC =
7709         Context.getDefaultCallingConvention(IsVariadic, IsStatic);
7710 
7711     if (CurCC != DefaultCC || DefaultCC == ToCC)
7712       return;
7713 
7714     if (hasExplicitCallingConv(T))
7715       return;
7716   }
7717 
7718   FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
7719   QualType Wrapped = Unwrapped.wrap(*this, FT);
7720   T = Context.getAdjustedType(T, Wrapped);
7721 }
7722 
7723 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
7724 /// and float scalars, although arrays, pointers, and function return values are
7725 /// allowed in conjunction with this construct. Aggregates with this attribute
7726 /// are invalid, even if they are of the same size as a corresponding scalar.
7727 /// The raw attribute should contain precisely 1 argument, the vector size for
7728 /// the variable, measured in bytes. If curType and rawAttr are well formed,
7729 /// this routine will return a new vector type.
HandleVectorSizeAttr(QualType & CurType,const ParsedAttr & Attr,Sema & S)7730 static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr,
7731                                  Sema &S) {
7732   // Check the attribute arguments.
7733   if (Attr.getNumArgs() != 1) {
7734     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
7735                                                                       << 1;
7736     Attr.setInvalid();
7737     return;
7738   }
7739 
7740   Expr *SizeExpr = Attr.getArgAsExpr(0);
7741   QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc());
7742   if (!T.isNull())
7743     CurType = T;
7744   else
7745     Attr.setInvalid();
7746 }
7747 
7748 /// Process the OpenCL-like ext_vector_type attribute when it occurs on
7749 /// a type.
HandleExtVectorTypeAttr(QualType & CurType,const ParsedAttr & Attr,Sema & S)7750 static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
7751                                     Sema &S) {
7752   // check the attribute arguments.
7753   if (Attr.getNumArgs() != 1) {
7754     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
7755                                                                       << 1;
7756     return;
7757   }
7758 
7759   Expr *SizeExpr = Attr.getArgAsExpr(0);
7760   QualType T = S.BuildExtVectorType(CurType, SizeExpr, Attr.getLoc());
7761   if (!T.isNull())
7762     CurType = T;
7763 }
7764 
isPermittedNeonBaseType(QualType & Ty,VectorType::VectorKind VecKind,Sema & S)7765 static bool isPermittedNeonBaseType(QualType &Ty,
7766                                     VectorType::VectorKind VecKind, Sema &S) {
7767   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
7768   if (!BTy)
7769     return false;
7770 
7771   llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
7772 
7773   // Signed poly is mathematically wrong, but has been baked into some ABIs by
7774   // now.
7775   bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
7776                         Triple.getArch() == llvm::Triple::aarch64_32 ||
7777                         Triple.getArch() == llvm::Triple::aarch64_be;
7778   if (VecKind == VectorType::NeonPolyVector) {
7779     if (IsPolyUnsigned) {
7780       // AArch64 polynomial vectors are unsigned.
7781       return BTy->getKind() == BuiltinType::UChar ||
7782              BTy->getKind() == BuiltinType::UShort ||
7783              BTy->getKind() == BuiltinType::ULong ||
7784              BTy->getKind() == BuiltinType::ULongLong;
7785     } else {
7786       // AArch32 polynomial vectors are signed.
7787       return BTy->getKind() == BuiltinType::SChar ||
7788              BTy->getKind() == BuiltinType::Short ||
7789              BTy->getKind() == BuiltinType::LongLong;
7790     }
7791   }
7792 
7793   // Non-polynomial vector types: the usual suspects are allowed, as well as
7794   // float64_t on AArch64.
7795   if ((Triple.isArch64Bit() || Triple.getArch() == llvm::Triple::aarch64_32) &&
7796       BTy->getKind() == BuiltinType::Double)
7797     return true;
7798 
7799   return BTy->getKind() == BuiltinType::SChar ||
7800          BTy->getKind() == BuiltinType::UChar ||
7801          BTy->getKind() == BuiltinType::Short ||
7802          BTy->getKind() == BuiltinType::UShort ||
7803          BTy->getKind() == BuiltinType::Int ||
7804          BTy->getKind() == BuiltinType::UInt ||
7805          BTy->getKind() == BuiltinType::Long ||
7806          BTy->getKind() == BuiltinType::ULong ||
7807          BTy->getKind() == BuiltinType::LongLong ||
7808          BTy->getKind() == BuiltinType::ULongLong ||
7809          BTy->getKind() == BuiltinType::Float ||
7810          BTy->getKind() == BuiltinType::Half ||
7811          BTy->getKind() == BuiltinType::BFloat16;
7812 }
7813 
verifyValidIntegerConstantExpr(Sema & S,const ParsedAttr & Attr,llvm::APSInt & Result)7814 static bool verifyValidIntegerConstantExpr(Sema &S, const ParsedAttr &Attr,
7815                                            llvm::APSInt &Result) {
7816   const auto *AttrExpr = Attr.getArgAsExpr(0);
7817   if (!AttrExpr->isTypeDependent() && !AttrExpr->isValueDependent()) {
7818     if (Optional<llvm::APSInt> Res =
7819             AttrExpr->getIntegerConstantExpr(S.Context)) {
7820       Result = *Res;
7821       return true;
7822     }
7823   }
7824   S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
7825       << Attr << AANT_ArgumentIntegerConstant << AttrExpr->getSourceRange();
7826   Attr.setInvalid();
7827   return false;
7828 }
7829 
7830 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
7831 /// "neon_polyvector_type" attributes are used to create vector types that
7832 /// are mangled according to ARM's ABI.  Otherwise, these types are identical
7833 /// to those created with the "vector_size" attribute.  Unlike "vector_size"
7834 /// the argument to these Neon attributes is the number of vector elements,
7835 /// not the vector size in bytes.  The vector width and element type must
7836 /// match one of the standard Neon vector types.
HandleNeonVectorTypeAttr(QualType & CurType,const ParsedAttr & Attr,Sema & S,VectorType::VectorKind VecKind)7837 static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
7838                                      Sema &S, VectorType::VectorKind VecKind) {
7839   // Target must have NEON (or MVE, whose vectors are similar enough
7840   // not to need a separate attribute)
7841   if (!S.Context.getTargetInfo().hasFeature("neon") &&
7842       !S.Context.getTargetInfo().hasFeature("mve")) {
7843     S.Diag(Attr.getLoc(), diag::err_attribute_unsupported)
7844         << Attr << "'neon' or 'mve'";
7845     Attr.setInvalid();
7846     return;
7847   }
7848   // Check the attribute arguments.
7849   if (Attr.getNumArgs() != 1) {
7850     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
7851                                                                       << 1;
7852     Attr.setInvalid();
7853     return;
7854   }
7855   // The number of elements must be an ICE.
7856   llvm::APSInt numEltsInt(32);
7857   if (!verifyValidIntegerConstantExpr(S, Attr, numEltsInt))
7858     return;
7859 
7860   // Only certain element types are supported for Neon vectors.
7861   if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
7862     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
7863     Attr.setInvalid();
7864     return;
7865   }
7866 
7867   // The total size of the vector must be 64 or 128 bits.
7868   unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
7869   unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
7870   unsigned vecSize = typeSize * numElts;
7871   if (vecSize != 64 && vecSize != 128) {
7872     S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
7873     Attr.setInvalid();
7874     return;
7875   }
7876 
7877   CurType = S.Context.getVectorType(CurType, numElts, VecKind);
7878 }
7879 
7880 /// HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is
7881 /// used to create fixed-length versions of sizeless SVE types defined by
7882 /// the ACLE, such as svint32_t and svbool_t.
HandleArmSveVectorBitsTypeAttr(QualType & CurType,ParsedAttr & Attr,Sema & S)7883 static void HandleArmSveVectorBitsTypeAttr(QualType &CurType, ParsedAttr &Attr,
7884                                            Sema &S) {
7885   // Target must have SVE.
7886   if (!S.Context.getTargetInfo().hasFeature("sve")) {
7887     S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr << "'sve'";
7888     Attr.setInvalid();
7889     return;
7890   }
7891 
7892   // Attribute is unsupported if '-msve-vector-bits=<bits>' isn't specified.
7893   if (!S.getLangOpts().ArmSveVectorBits) {
7894     S.Diag(Attr.getLoc(), diag::err_attribute_arm_feature_sve_bits_unsupported)
7895         << Attr;
7896     Attr.setInvalid();
7897     return;
7898   }
7899 
7900   // Check the attribute arguments.
7901   if (Attr.getNumArgs() != 1) {
7902     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
7903         << Attr << 1;
7904     Attr.setInvalid();
7905     return;
7906   }
7907 
7908   // The vector size must be an integer constant expression.
7909   llvm::APSInt SveVectorSizeInBits(32);
7910   if (!verifyValidIntegerConstantExpr(S, Attr, SveVectorSizeInBits))
7911     return;
7912 
7913   unsigned VecSize = static_cast<unsigned>(SveVectorSizeInBits.getZExtValue());
7914 
7915   // The attribute vector size must match -msve-vector-bits.
7916   if (VecSize != S.getLangOpts().ArmSveVectorBits) {
7917     S.Diag(Attr.getLoc(), diag::err_attribute_bad_sve_vector_size)
7918         << VecSize << S.getLangOpts().ArmSveVectorBits;
7919     Attr.setInvalid();
7920     return;
7921   }
7922 
7923   // Attribute can only be attached to a single SVE vector or predicate type.
7924   if (!CurType->isVLSTBuiltinType()) {
7925     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_sve_type)
7926         << Attr << CurType;
7927     Attr.setInvalid();
7928     return;
7929   }
7930 
7931   const auto *BT = CurType->castAs<BuiltinType>();
7932 
7933   QualType EltType = CurType->getSveEltType(S.Context);
7934   unsigned TypeSize = S.Context.getTypeSize(EltType);
7935   VectorType::VectorKind VecKind = VectorType::SveFixedLengthDataVector;
7936   if (BT->getKind() == BuiltinType::SveBool) {
7937     // Predicates are represented as i8.
7938     VecSize /= S.Context.getCharWidth() * S.Context.getCharWidth();
7939     VecKind = VectorType::SveFixedLengthPredicateVector;
7940   } else
7941     VecSize /= TypeSize;
7942   CurType = S.Context.getVectorType(EltType, VecSize, VecKind);
7943 }
7944 
HandleArmMveStrictPolymorphismAttr(TypeProcessingState & State,QualType & CurType,ParsedAttr & Attr)7945 static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State,
7946                                                QualType &CurType,
7947                                                ParsedAttr &Attr) {
7948   const VectorType *VT = dyn_cast<VectorType>(CurType);
7949   if (!VT || VT->getVectorKind() != VectorType::NeonVector) {
7950     State.getSema().Diag(Attr.getLoc(),
7951                          diag::err_attribute_arm_mve_polymorphism);
7952     Attr.setInvalid();
7953     return;
7954   }
7955 
7956   CurType =
7957       State.getAttributedType(createSimpleAttr<ArmMveStrictPolymorphismAttr>(
7958                                   State.getSema().Context, Attr),
7959                               CurType, CurType);
7960 }
7961 
7962 /// Handle OpenCL Access Qualifier Attribute.
HandleOpenCLAccessAttr(QualType & CurType,const ParsedAttr & Attr,Sema & S)7963 static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr,
7964                                    Sema &S) {
7965   // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
7966   if (!(CurType->isImageType() || CurType->isPipeType())) {
7967     S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
7968     Attr.setInvalid();
7969     return;
7970   }
7971 
7972   if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
7973     QualType BaseTy = TypedefTy->desugar();
7974 
7975     std::string PrevAccessQual;
7976     if (BaseTy->isPipeType()) {
7977       if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) {
7978         OpenCLAccessAttr *Attr =
7979             TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>();
7980         PrevAccessQual = Attr->getSpelling();
7981       } else {
7982         PrevAccessQual = "read_only";
7983       }
7984     } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) {
7985 
7986       switch (ImgType->getKind()) {
7987         #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7988       case BuiltinType::Id:                                          \
7989         PrevAccessQual = #Access;                                    \
7990         break;
7991         #include "clang/Basic/OpenCLImageTypes.def"
7992       default:
7993         llvm_unreachable("Unable to find corresponding image type.");
7994       }
7995     } else {
7996       llvm_unreachable("unexpected type");
7997     }
7998     StringRef AttrName = Attr.getAttrName()->getName();
7999     if (PrevAccessQual == AttrName.ltrim("_")) {
8000       // Duplicated qualifiers
8001       S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec)
8002          << AttrName << Attr.getRange();
8003     } else {
8004       // Contradicting qualifiers
8005       S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
8006     }
8007 
8008     S.Diag(TypedefTy->getDecl()->getBeginLoc(),
8009            diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
8010   } else if (CurType->isPipeType()) {
8011     if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
8012       QualType ElemType = CurType->castAs<PipeType>()->getElementType();
8013       CurType = S.Context.getWritePipeType(ElemType);
8014     }
8015   }
8016 }
8017 
8018 /// HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type
HandleMatrixTypeAttr(QualType & CurType,const ParsedAttr & Attr,Sema & S)8019 static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8020                                  Sema &S) {
8021   if (!S.getLangOpts().MatrixTypes) {
8022     S.Diag(Attr.getLoc(), diag::err_builtin_matrix_disabled);
8023     return;
8024   }
8025 
8026   if (Attr.getNumArgs() != 2) {
8027     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8028         << Attr << 2;
8029     return;
8030   }
8031 
8032   Expr *RowsExpr = Attr.getArgAsExpr(0);
8033   Expr *ColsExpr = Attr.getArgAsExpr(1);
8034   QualType T = S.BuildMatrixType(CurType, RowsExpr, ColsExpr, Attr.getLoc());
8035   if (!T.isNull())
8036     CurType = T;
8037 }
8038 
HandleLifetimeBoundAttr(TypeProcessingState & State,QualType & CurType,ParsedAttr & Attr)8039 static void HandleLifetimeBoundAttr(TypeProcessingState &State,
8040                                     QualType &CurType,
8041                                     ParsedAttr &Attr) {
8042   if (State.getDeclarator().isDeclarationOfFunction()) {
8043     CurType = State.getAttributedType(
8044         createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr),
8045         CurType, CurType);
8046   }
8047 }
8048 
isAddressSpaceKind(const ParsedAttr & attr)8049 static bool isAddressSpaceKind(const ParsedAttr &attr) {
8050   auto attrKind = attr.getKind();
8051 
8052   return attrKind == ParsedAttr::AT_AddressSpace ||
8053          attrKind == ParsedAttr::AT_OpenCLPrivateAddressSpace ||
8054          attrKind == ParsedAttr::AT_OpenCLGlobalAddressSpace ||
8055          attrKind == ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace ||
8056          attrKind == ParsedAttr::AT_OpenCLGlobalHostAddressSpace ||
8057          attrKind == ParsedAttr::AT_OpenCLLocalAddressSpace ||
8058          attrKind == ParsedAttr::AT_OpenCLConstantAddressSpace ||
8059          attrKind == ParsedAttr::AT_OpenCLGenericAddressSpace;
8060 }
8061 
processTypeAttrs(TypeProcessingState & state,QualType & type,TypeAttrLocation TAL,ParsedAttributesView & attrs)8062 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
8063                              TypeAttrLocation TAL,
8064                              ParsedAttributesView &attrs) {
8065   // Scan through and apply attributes to this type where it makes sense.  Some
8066   // attributes (such as __address_space__, __vector_size__, etc) apply to the
8067   // type, but others can be present in the type specifiers even though they
8068   // apply to the decl.  Here we apply type attributes and ignore the rest.
8069 
8070   // This loop modifies the list pretty frequently, but we still need to make
8071   // sure we visit every element once. Copy the attributes list, and iterate
8072   // over that.
8073   ParsedAttributesView AttrsCopy{attrs};
8074 
8075   state.setParsedNoDeref(false);
8076 
8077   for (ParsedAttr &attr : AttrsCopy) {
8078 
8079     // Skip attributes that were marked to be invalid.
8080     if (attr.isInvalid())
8081       continue;
8082 
8083     if (attr.isStandardAttributeSyntax()) {
8084       // [[gnu::...]] attributes are treated as declaration attributes, so may
8085       // not appertain to a DeclaratorChunk. If we handle them as type
8086       // attributes, accept them in that position and diagnose the GCC
8087       // incompatibility.
8088       if (attr.isGNUScope()) {
8089         bool IsTypeAttr = attr.isTypeAttr();
8090         if (TAL == TAL_DeclChunk) {
8091           state.getSema().Diag(attr.getLoc(),
8092                                IsTypeAttr
8093                                    ? diag::warn_gcc_ignores_type_attr
8094                                    : diag::warn_cxx11_gnu_attribute_on_type)
8095               << attr;
8096           if (!IsTypeAttr)
8097             continue;
8098         }
8099       } else if (TAL != TAL_DeclChunk && !isAddressSpaceKind(attr)) {
8100         // Otherwise, only consider type processing for a C++11 attribute if
8101         // it's actually been applied to a type.
8102         // We also allow C++11 address_space and
8103         // OpenCL language address space attributes to pass through.
8104         continue;
8105       }
8106     }
8107 
8108     // If this is an attribute we can handle, do so now,
8109     // otherwise, add it to the FnAttrs list for rechaining.
8110     switch (attr.getKind()) {
8111     default:
8112       // A [[]] attribute on a declarator chunk must appertain to a type.
8113       if (attr.isStandardAttributeSyntax() && TAL == TAL_DeclChunk) {
8114         state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
8115             << attr;
8116         attr.setUsedAsTypeAttr();
8117       }
8118       break;
8119 
8120     case ParsedAttr::UnknownAttribute:
8121       if (attr.isStandardAttributeSyntax() && TAL == TAL_DeclChunk)
8122         state.getSema().Diag(attr.getLoc(),
8123                              diag::warn_unknown_attribute_ignored)
8124             << attr << attr.getRange();
8125       break;
8126 
8127     case ParsedAttr::IgnoredAttribute:
8128       break;
8129 
8130     case ParsedAttr::AT_MayAlias:
8131       // FIXME: This attribute needs to actually be handled, but if we ignore
8132       // it it breaks large amounts of Linux software.
8133       attr.setUsedAsTypeAttr();
8134       break;
8135     case ParsedAttr::AT_OpenCLPrivateAddressSpace:
8136     case ParsedAttr::AT_OpenCLGlobalAddressSpace:
8137     case ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace:
8138     case ParsedAttr::AT_OpenCLGlobalHostAddressSpace:
8139     case ParsedAttr::AT_OpenCLLocalAddressSpace:
8140     case ParsedAttr::AT_OpenCLConstantAddressSpace:
8141     case ParsedAttr::AT_OpenCLGenericAddressSpace:
8142     case ParsedAttr::AT_AddressSpace:
8143       HandleAddressSpaceTypeAttribute(type, attr, state);
8144       attr.setUsedAsTypeAttr();
8145       break;
8146     OBJC_POINTER_TYPE_ATTRS_CASELIST:
8147       if (!handleObjCPointerTypeAttr(state, attr, type))
8148         distributeObjCPointerTypeAttr(state, attr, type);
8149       attr.setUsedAsTypeAttr();
8150       break;
8151     case ParsedAttr::AT_VectorSize:
8152       HandleVectorSizeAttr(type, attr, state.getSema());
8153       attr.setUsedAsTypeAttr();
8154       break;
8155     case ParsedAttr::AT_ExtVectorType:
8156       HandleExtVectorTypeAttr(type, attr, state.getSema());
8157       attr.setUsedAsTypeAttr();
8158       break;
8159     case ParsedAttr::AT_NeonVectorType:
8160       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
8161                                VectorType::NeonVector);
8162       attr.setUsedAsTypeAttr();
8163       break;
8164     case ParsedAttr::AT_NeonPolyVectorType:
8165       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
8166                                VectorType::NeonPolyVector);
8167       attr.setUsedAsTypeAttr();
8168       break;
8169     case ParsedAttr::AT_ArmSveVectorBits:
8170       HandleArmSveVectorBitsTypeAttr(type, attr, state.getSema());
8171       attr.setUsedAsTypeAttr();
8172       break;
8173     case ParsedAttr::AT_ArmMveStrictPolymorphism: {
8174       HandleArmMveStrictPolymorphismAttr(state, type, attr);
8175       attr.setUsedAsTypeAttr();
8176       break;
8177     }
8178     case ParsedAttr::AT_OpenCLAccess:
8179       HandleOpenCLAccessAttr(type, attr, state.getSema());
8180       attr.setUsedAsTypeAttr();
8181       break;
8182     case ParsedAttr::AT_LifetimeBound:
8183       if (TAL == TAL_DeclChunk)
8184         HandleLifetimeBoundAttr(state, type, attr);
8185       break;
8186 
8187     case ParsedAttr::AT_NoDeref: {
8188       ASTContext &Ctx = state.getSema().Context;
8189       type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr),
8190                                      type, type);
8191       attr.setUsedAsTypeAttr();
8192       state.setParsedNoDeref(true);
8193       break;
8194     }
8195 
8196     case ParsedAttr::AT_MatrixType:
8197       HandleMatrixTypeAttr(type, attr, state.getSema());
8198       attr.setUsedAsTypeAttr();
8199       break;
8200 
8201     MS_TYPE_ATTRS_CASELIST:
8202       if (!handleMSPointerTypeQualifierAttr(state, attr, type))
8203         attr.setUsedAsTypeAttr();
8204       break;
8205 
8206 
8207     NULLABILITY_TYPE_ATTRS_CASELIST:
8208       // Either add nullability here or try to distribute it.  We
8209       // don't want to distribute the nullability specifier past any
8210       // dependent type, because that complicates the user model.
8211       if (type->canHaveNullability() || type->isDependentType() ||
8212           type->isArrayType() ||
8213           !distributeNullabilityTypeAttr(state, type, attr)) {
8214         unsigned endIndex;
8215         if (TAL == TAL_DeclChunk)
8216           endIndex = state.getCurrentChunkIndex();
8217         else
8218           endIndex = state.getDeclarator().getNumTypeObjects();
8219         bool allowOnArrayType =
8220             state.getDeclarator().isPrototypeContext() &&
8221             !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
8222         if (checkNullabilityTypeSpecifier(
8223               state,
8224               type,
8225               attr,
8226               allowOnArrayType)) {
8227           attr.setInvalid();
8228         }
8229 
8230         attr.setUsedAsTypeAttr();
8231       }
8232       break;
8233 
8234     case ParsedAttr::AT_ObjCKindOf:
8235       // '__kindof' must be part of the decl-specifiers.
8236       switch (TAL) {
8237       case TAL_DeclSpec:
8238         break;
8239 
8240       case TAL_DeclChunk:
8241       case TAL_DeclName:
8242         state.getSema().Diag(attr.getLoc(),
8243                              diag::err_objc_kindof_wrong_position)
8244             << FixItHint::CreateRemoval(attr.getLoc())
8245             << FixItHint::CreateInsertion(
8246                    state.getDeclarator().getDeclSpec().getBeginLoc(),
8247                    "__kindof ");
8248         break;
8249       }
8250 
8251       // Apply it regardless.
8252       if (checkObjCKindOfType(state, type, attr))
8253         attr.setInvalid();
8254       break;
8255 
8256     case ParsedAttr::AT_NoThrow:
8257     // Exception Specifications aren't generally supported in C mode throughout
8258     // clang, so revert to attribute-based handling for C.
8259       if (!state.getSema().getLangOpts().CPlusPlus)
8260         break;
8261       LLVM_FALLTHROUGH;
8262     FUNCTION_TYPE_ATTRS_CASELIST:
8263       attr.setUsedAsTypeAttr();
8264 
8265       // Never process function type attributes as part of the
8266       // declaration-specifiers.
8267       if (TAL == TAL_DeclSpec)
8268         distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
8269 
8270       // Otherwise, handle the possible delays.
8271       else if (!handleFunctionTypeAttr(state, attr, type))
8272         distributeFunctionTypeAttr(state, attr, type);
8273       break;
8274     case ParsedAttr::AT_AcquireHandle: {
8275       if (!type->isFunctionType())
8276         return;
8277 
8278       if (attr.getNumArgs() != 1) {
8279         state.getSema().Diag(attr.getLoc(),
8280                              diag::err_attribute_wrong_number_arguments)
8281             << attr << 1;
8282         attr.setInvalid();
8283         return;
8284       }
8285 
8286       StringRef HandleType;
8287       if (!state.getSema().checkStringLiteralArgumentAttr(attr, 0, HandleType))
8288         return;
8289       type = state.getAttributedType(
8290           AcquireHandleAttr::Create(state.getSema().Context, HandleType, attr),
8291           type, type);
8292       attr.setUsedAsTypeAttr();
8293       break;
8294     }
8295     }
8296 
8297     // Handle attributes that are defined in a macro. We do not want this to be
8298     // applied to ObjC builtin attributes.
8299     if (isa<AttributedType>(type) && attr.hasMacroIdentifier() &&
8300         !type.getQualifiers().hasObjCLifetime() &&
8301         !type.getQualifiers().hasObjCGCAttr() &&
8302         attr.getKind() != ParsedAttr::AT_ObjCGC &&
8303         attr.getKind() != ParsedAttr::AT_ObjCOwnership) {
8304       const IdentifierInfo *MacroII = attr.getMacroIdentifier();
8305       type = state.getSema().Context.getMacroQualifiedType(type, MacroII);
8306       state.setExpansionLocForMacroQualifiedType(
8307           cast<MacroQualifiedType>(type.getTypePtr()),
8308           attr.getMacroExpansionLoc());
8309     }
8310   }
8311 }
8312 
completeExprArrayBound(Expr * E)8313 void Sema::completeExprArrayBound(Expr *E) {
8314   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
8315     if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
8316       if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
8317         auto *Def = Var->getDefinition();
8318         if (!Def) {
8319           SourceLocation PointOfInstantiation = E->getExprLoc();
8320           runWithSufficientStackSpace(PointOfInstantiation, [&] {
8321             InstantiateVariableDefinition(PointOfInstantiation, Var);
8322           });
8323           Def = Var->getDefinition();
8324 
8325           // If we don't already have a point of instantiation, and we managed
8326           // to instantiate a definition, this is the point of instantiation.
8327           // Otherwise, we don't request an end-of-TU instantiation, so this is
8328           // not a point of instantiation.
8329           // FIXME: Is this really the right behavior?
8330           if (Var->getPointOfInstantiation().isInvalid() && Def) {
8331             assert(Var->getTemplateSpecializationKind() ==
8332                        TSK_ImplicitInstantiation &&
8333                    "explicit instantiation with no point of instantiation");
8334             Var->setTemplateSpecializationKind(
8335                 Var->getTemplateSpecializationKind(), PointOfInstantiation);
8336           }
8337         }
8338 
8339         // Update the type to the definition's type both here and within the
8340         // expression.
8341         if (Def) {
8342           DRE->setDecl(Def);
8343           QualType T = Def->getType();
8344           DRE->setType(T);
8345           // FIXME: Update the type on all intervening expressions.
8346           E->setType(T);
8347         }
8348 
8349         // We still go on to try to complete the type independently, as it
8350         // may also require instantiations or diagnostics if it remains
8351         // incomplete.
8352       }
8353     }
8354   }
8355 }
8356 
getCompletedType(Expr * E)8357 QualType Sema::getCompletedType(Expr *E) {
8358   // Incomplete array types may be completed by the initializer attached to
8359   // their definitions. For static data members of class templates and for
8360   // variable templates, we need to instantiate the definition to get this
8361   // initializer and complete the type.
8362   if (E->getType()->isIncompleteArrayType())
8363     completeExprArrayBound(E);
8364 
8365   // FIXME: Are there other cases which require instantiating something other
8366   // than the type to complete the type of an expression?
8367 
8368   return E->getType();
8369 }
8370 
8371 /// Ensure that the type of the given expression is complete.
8372 ///
8373 /// This routine checks whether the expression \p E has a complete type. If the
8374 /// expression refers to an instantiable construct, that instantiation is
8375 /// performed as needed to complete its type. Furthermore
8376 /// Sema::RequireCompleteType is called for the expression's type (or in the
8377 /// case of a reference type, the referred-to type).
8378 ///
8379 /// \param E The expression whose type is required to be complete.
8380 /// \param Kind Selects which completeness rules should be applied.
8381 /// \param Diagnoser The object that will emit a diagnostic if the type is
8382 /// incomplete.
8383 ///
8384 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
8385 /// otherwise.
RequireCompleteExprType(Expr * E,CompleteTypeKind Kind,TypeDiagnoser & Diagnoser)8386 bool Sema::RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
8387                                    TypeDiagnoser &Diagnoser) {
8388   return RequireCompleteType(E->getExprLoc(), getCompletedType(E), Kind,
8389                              Diagnoser);
8390 }
8391 
RequireCompleteExprType(Expr * E,unsigned DiagID)8392 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
8393   BoundTypeDiagnoser<> Diagnoser(DiagID);
8394   return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
8395 }
8396 
8397 /// Ensure that the type T is a complete type.
8398 ///
8399 /// This routine checks whether the type @p T is complete in any
8400 /// context where a complete type is required. If @p T is a complete
8401 /// type, returns false. If @p T is a class template specialization,
8402 /// this routine then attempts to perform class template
8403 /// instantiation. If instantiation fails, or if @p T is incomplete
8404 /// and cannot be completed, issues the diagnostic @p diag (giving it
8405 /// the type @p T) and returns true.
8406 ///
8407 /// @param Loc  The location in the source that the incomplete type
8408 /// diagnostic should refer to.
8409 ///
8410 /// @param T  The type that this routine is examining for completeness.
8411 ///
8412 /// @param Kind Selects which completeness rules should be applied.
8413 ///
8414 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
8415 /// @c false otherwise.
RequireCompleteType(SourceLocation Loc,QualType T,CompleteTypeKind Kind,TypeDiagnoser & Diagnoser)8416 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
8417                                CompleteTypeKind Kind,
8418                                TypeDiagnoser &Diagnoser) {
8419   if (RequireCompleteTypeImpl(Loc, T, Kind, &Diagnoser))
8420     return true;
8421   if (const TagType *Tag = T->getAs<TagType>()) {
8422     if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
8423       Tag->getDecl()->setCompleteDefinitionRequired();
8424       Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
8425     }
8426   }
8427   return false;
8428 }
8429 
hasStructuralCompatLayout(Decl * D,Decl * Suggested)8430 bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) {
8431   llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
8432   if (!Suggested)
8433     return false;
8434 
8435   // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
8436   // and isolate from other C++ specific checks.
8437   StructuralEquivalenceContext Ctx(
8438       D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls,
8439       StructuralEquivalenceKind::Default,
8440       false /*StrictTypeSpelling*/, true /*Complain*/,
8441       true /*ErrorOnTagTypeMismatch*/);
8442   return Ctx.IsEquivalent(D, Suggested);
8443 }
8444 
8445 /// Determine whether there is any declaration of \p D that was ever a
8446 ///        definition (perhaps before module merging) and is currently visible.
8447 /// \param D The definition of the entity.
8448 /// \param Suggested Filled in with the declaration that should be made visible
8449 ///        in order to provide a definition of this entity.
8450 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
8451 ///        not defined. This only matters for enums with a fixed underlying
8452 ///        type, since in all other cases, a type is complete if and only if it
8453 ///        is defined.
hasVisibleDefinition(NamedDecl * D,NamedDecl ** Suggested,bool OnlyNeedComplete)8454 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
8455                                 bool OnlyNeedComplete) {
8456   // Easy case: if we don't have modules, all declarations are visible.
8457   if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
8458     return true;
8459 
8460   // If this definition was instantiated from a template, map back to the
8461   // pattern from which it was instantiated.
8462   if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
8463     // We're in the middle of defining it; this definition should be treated
8464     // as visible.
8465     return true;
8466   } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
8467     if (auto *Pattern = RD->getTemplateInstantiationPattern())
8468       RD = Pattern;
8469     D = RD->getDefinition();
8470   } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
8471     if (auto *Pattern = ED->getTemplateInstantiationPattern())
8472       ED = Pattern;
8473     if (OnlyNeedComplete && (ED->isFixed() || getLangOpts().MSVCCompat)) {
8474       // If the enum has a fixed underlying type, it may have been forward
8475       // declared. In -fms-compatibility, `enum Foo;` will also forward declare
8476       // the enum and assign it the underlying type of `int`. Since we're only
8477       // looking for a complete type (not a definition), any visible declaration
8478       // of it will do.
8479       *Suggested = nullptr;
8480       for (auto *Redecl : ED->redecls()) {
8481         if (isVisible(Redecl))
8482           return true;
8483         if (Redecl->isThisDeclarationADefinition() ||
8484             (Redecl->isCanonicalDecl() && !*Suggested))
8485           *Suggested = Redecl;
8486       }
8487       return false;
8488     }
8489     D = ED->getDefinition();
8490   } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
8491     if (auto *Pattern = FD->getTemplateInstantiationPattern())
8492       FD = Pattern;
8493     D = FD->getDefinition();
8494   } else if (auto *VD = dyn_cast<VarDecl>(D)) {
8495     if (auto *Pattern = VD->getTemplateInstantiationPattern())
8496       VD = Pattern;
8497     D = VD->getDefinition();
8498   }
8499   assert(D && "missing definition for pattern of instantiated definition");
8500 
8501   *Suggested = D;
8502 
8503   auto DefinitionIsVisible = [&] {
8504     // The (primary) definition might be in a visible module.
8505     if (isVisible(D))
8506       return true;
8507 
8508     // A visible module might have a merged definition instead.
8509     if (D->isModulePrivate() ? hasMergedDefinitionInCurrentModule(D)
8510                              : hasVisibleMergedDefinition(D)) {
8511       if (CodeSynthesisContexts.empty() &&
8512           !getLangOpts().ModulesLocalVisibility) {
8513         // Cache the fact that this definition is implicitly visible because
8514         // there is a visible merged definition.
8515         D->setVisibleDespiteOwningModule();
8516       }
8517       return true;
8518     }
8519 
8520     return false;
8521   };
8522 
8523   if (DefinitionIsVisible())
8524     return true;
8525 
8526   // The external source may have additional definitions of this entity that are
8527   // visible, so complete the redeclaration chain now and ask again.
8528   if (auto *Source = Context.getExternalSource()) {
8529     Source->CompleteRedeclChain(D);
8530     return DefinitionIsVisible();
8531   }
8532 
8533   return false;
8534 }
8535 
8536 /// Locks in the inheritance model for the given class and all of its bases.
assignInheritanceModel(Sema & S,CXXRecordDecl * RD)8537 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
8538   RD = RD->getMostRecentNonInjectedDecl();
8539   if (!RD->hasAttr<MSInheritanceAttr>()) {
8540     MSInheritanceModel IM;
8541     bool BestCase = false;
8542     switch (S.MSPointerToMemberRepresentationMethod) {
8543     case LangOptions::PPTMK_BestCase:
8544       BestCase = true;
8545       IM = RD->calculateInheritanceModel();
8546       break;
8547     case LangOptions::PPTMK_FullGeneralitySingleInheritance:
8548       IM = MSInheritanceModel::Single;
8549       break;
8550     case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
8551       IM = MSInheritanceModel::Multiple;
8552       break;
8553     case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
8554       IM = MSInheritanceModel::Unspecified;
8555       break;
8556     }
8557 
8558     SourceRange Loc = S.ImplicitMSInheritanceAttrLoc.isValid()
8559                           ? S.ImplicitMSInheritanceAttrLoc
8560                           : RD->getSourceRange();
8561     RD->addAttr(MSInheritanceAttr::CreateImplicit(
8562         S.getASTContext(), BestCase, Loc, AttributeCommonInfo::AS_Microsoft,
8563         MSInheritanceAttr::Spelling(IM)));
8564     S.Consumer.AssignInheritanceModel(RD);
8565   }
8566 }
8567 
8568 /// The implementation of RequireCompleteType
RequireCompleteTypeImpl(SourceLocation Loc,QualType T,CompleteTypeKind Kind,TypeDiagnoser * Diagnoser)8569 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
8570                                    CompleteTypeKind Kind,
8571                                    TypeDiagnoser *Diagnoser) {
8572   // FIXME: Add this assertion to make sure we always get instantiation points.
8573   //  assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
8574   // FIXME: Add this assertion to help us flush out problems with
8575   // checking for dependent types and type-dependent expressions.
8576   //
8577   //  assert(!T->isDependentType() &&
8578   //         "Can't ask whether a dependent type is complete");
8579 
8580   if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
8581     if (!MPTy->getClass()->isDependentType()) {
8582       if (getLangOpts().CompleteMemberPointers &&
8583           !MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined() &&
8584           RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), Kind,
8585                               diag::err_memptr_incomplete))
8586         return true;
8587 
8588       // We lock in the inheritance model once somebody has asked us to ensure
8589       // that a pointer-to-member type is complete.
8590       if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8591         (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
8592         assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
8593       }
8594     }
8595   }
8596 
8597   NamedDecl *Def = nullptr;
8598   bool AcceptSizeless = (Kind == CompleteTypeKind::AcceptSizeless);
8599   bool Incomplete = (T->isIncompleteType(&Def) ||
8600                      (!AcceptSizeless && T->isSizelessBuiltinType()));
8601 
8602   // Check that any necessary explicit specializations are visible. For an
8603   // enum, we just need the declaration, so don't check this.
8604   if (Def && !isa<EnumDecl>(Def))
8605     checkSpecializationVisibility(Loc, Def);
8606 
8607   // If we have a complete type, we're done.
8608   if (!Incomplete) {
8609     // If we know about the definition but it is not visible, complain.
8610     NamedDecl *SuggestedDef = nullptr;
8611     if (Def &&
8612         !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) {
8613       // If the user is going to see an error here, recover by making the
8614       // definition visible.
8615       bool TreatAsComplete = Diagnoser && !isSFINAEContext();
8616       if (Diagnoser && SuggestedDef)
8617         diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition,
8618                               /*Recover*/TreatAsComplete);
8619       return !TreatAsComplete;
8620     } else if (Def && !TemplateInstCallbacks.empty()) {
8621       CodeSynthesisContext TempInst;
8622       TempInst.Kind = CodeSynthesisContext::Memoization;
8623       TempInst.Template = Def;
8624       TempInst.Entity = Def;
8625       TempInst.PointOfInstantiation = Loc;
8626       atTemplateBegin(TemplateInstCallbacks, *this, TempInst);
8627       atTemplateEnd(TemplateInstCallbacks, *this, TempInst);
8628     }
8629 
8630     return false;
8631   }
8632 
8633   TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def);
8634   ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def);
8635 
8636   // Give the external source a chance to provide a definition of the type.
8637   // This is kept separate from completing the redeclaration chain so that
8638   // external sources such as LLDB can avoid synthesizing a type definition
8639   // unless it's actually needed.
8640   if (Tag || IFace) {
8641     // Avoid diagnosing invalid decls as incomplete.
8642     if (Def->isInvalidDecl())
8643       return true;
8644 
8645     // Give the external AST source a chance to complete the type.
8646     if (auto *Source = Context.getExternalSource()) {
8647       if (Tag && Tag->hasExternalLexicalStorage())
8648           Source->CompleteType(Tag);
8649       if (IFace && IFace->hasExternalLexicalStorage())
8650           Source->CompleteType(IFace);
8651       // If the external source completed the type, go through the motions
8652       // again to ensure we're allowed to use the completed type.
8653       if (!T->isIncompleteType())
8654         return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
8655     }
8656   }
8657 
8658   // If we have a class template specialization or a class member of a
8659   // class template specialization, or an array with known size of such,
8660   // try to instantiate it.
8661   if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) {
8662     bool Instantiated = false;
8663     bool Diagnosed = false;
8664     if (RD->isDependentContext()) {
8665       // Don't try to instantiate a dependent class (eg, a member template of
8666       // an instantiated class template specialization).
8667       // FIXME: Can this ever happen?
8668     } else if (auto *ClassTemplateSpec =
8669             dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
8670       if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
8671         runWithSufficientStackSpace(Loc, [&] {
8672           Diagnosed = InstantiateClassTemplateSpecialization(
8673               Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
8674               /*Complain=*/Diagnoser);
8675         });
8676         Instantiated = true;
8677       }
8678     } else {
8679       CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass();
8680       if (!RD->isBeingDefined() && Pattern) {
8681         MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo();
8682         assert(MSI && "Missing member specialization information?");
8683         // This record was instantiated from a class within a template.
8684         if (MSI->getTemplateSpecializationKind() !=
8685             TSK_ExplicitSpecialization) {
8686           runWithSufficientStackSpace(Loc, [&] {
8687             Diagnosed = InstantiateClass(Loc, RD, Pattern,
8688                                          getTemplateInstantiationArgs(RD),
8689                                          TSK_ImplicitInstantiation,
8690                                          /*Complain=*/Diagnoser);
8691           });
8692           Instantiated = true;
8693         }
8694       }
8695     }
8696 
8697     if (Instantiated) {
8698       // Instantiate* might have already complained that the template is not
8699       // defined, if we asked it to.
8700       if (Diagnoser && Diagnosed)
8701         return true;
8702       // If we instantiated a definition, check that it's usable, even if
8703       // instantiation produced an error, so that repeated calls to this
8704       // function give consistent answers.
8705       if (!T->isIncompleteType())
8706         return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
8707     }
8708   }
8709 
8710   // FIXME: If we didn't instantiate a definition because of an explicit
8711   // specialization declaration, check that it's visible.
8712 
8713   if (!Diagnoser)
8714     return true;
8715 
8716   Diagnoser->diagnose(*this, Loc, T);
8717 
8718   // If the type was a forward declaration of a class/struct/union
8719   // type, produce a note.
8720   if (Tag && !Tag->isInvalidDecl() && !Tag->getLocation().isInvalid())
8721     Diag(Tag->getLocation(),
8722          Tag->isBeingDefined() ? diag::note_type_being_defined
8723                                : diag::note_forward_declaration)
8724       << Context.getTagDeclType(Tag);
8725 
8726   // If the Objective-C class was a forward declaration, produce a note.
8727   if (IFace && !IFace->isInvalidDecl() && !IFace->getLocation().isInvalid())
8728     Diag(IFace->getLocation(), diag::note_forward_class);
8729 
8730   // If we have external information that we can use to suggest a fix,
8731   // produce a note.
8732   if (ExternalSource)
8733     ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
8734 
8735   return true;
8736 }
8737 
RequireCompleteType(SourceLocation Loc,QualType T,CompleteTypeKind Kind,unsigned DiagID)8738 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
8739                                CompleteTypeKind Kind, unsigned DiagID) {
8740   BoundTypeDiagnoser<> Diagnoser(DiagID);
8741   return RequireCompleteType(Loc, T, Kind, Diagnoser);
8742 }
8743 
8744 /// Get diagnostic %select index for tag kind for
8745 /// literal type diagnostic message.
8746 /// WARNING: Indexes apply to particular diagnostics only!
8747 ///
8748 /// \returns diagnostic %select index.
getLiteralDiagFromTagKind(TagTypeKind Tag)8749 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
8750   switch (Tag) {
8751   case TTK_Struct: return 0;
8752   case TTK_Interface: return 1;
8753   case TTK_Class:  return 2;
8754   default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
8755   }
8756 }
8757 
8758 /// Ensure that the type T is a literal type.
8759 ///
8760 /// This routine checks whether the type @p T is a literal type. If @p T is an
8761 /// incomplete type, an attempt is made to complete it. If @p T is a literal
8762 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
8763 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
8764 /// it the type @p T), along with notes explaining why the type is not a
8765 /// literal type, and returns true.
8766 ///
8767 /// @param Loc  The location in the source that the non-literal type
8768 /// diagnostic should refer to.
8769 ///
8770 /// @param T  The type that this routine is examining for literalness.
8771 ///
8772 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
8773 ///
8774 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
8775 /// @c false otherwise.
RequireLiteralType(SourceLocation Loc,QualType T,TypeDiagnoser & Diagnoser)8776 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
8777                               TypeDiagnoser &Diagnoser) {
8778   assert(!T->isDependentType() && "type should not be dependent");
8779 
8780   QualType ElemType = Context.getBaseElementType(T);
8781   if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
8782       T->isLiteralType(Context))
8783     return false;
8784 
8785   Diagnoser.diagnose(*this, Loc, T);
8786 
8787   if (T->isVariableArrayType())
8788     return true;
8789 
8790   const RecordType *RT = ElemType->getAs<RecordType>();
8791   if (!RT)
8792     return true;
8793 
8794   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
8795 
8796   // A partially-defined class type can't be a literal type, because a literal
8797   // class type must have a trivial destructor (which can't be checked until
8798   // the class definition is complete).
8799   if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
8800     return true;
8801 
8802   // [expr.prim.lambda]p3:
8803   //   This class type is [not] a literal type.
8804   if (RD->isLambda() && !getLangOpts().CPlusPlus17) {
8805     Diag(RD->getLocation(), diag::note_non_literal_lambda);
8806     return true;
8807   }
8808 
8809   // If the class has virtual base classes, then it's not an aggregate, and
8810   // cannot have any constexpr constructors or a trivial default constructor,
8811   // so is non-literal. This is better to diagnose than the resulting absence
8812   // of constexpr constructors.
8813   if (RD->getNumVBases()) {
8814     Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
8815       << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
8816     for (const auto &I : RD->vbases())
8817       Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
8818           << I.getSourceRange();
8819   } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
8820              !RD->hasTrivialDefaultConstructor()) {
8821     Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
8822   } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
8823     for (const auto &I : RD->bases()) {
8824       if (!I.getType()->isLiteralType(Context)) {
8825         Diag(I.getBeginLoc(), diag::note_non_literal_base_class)
8826             << RD << I.getType() << I.getSourceRange();
8827         return true;
8828       }
8829     }
8830     for (const auto *I : RD->fields()) {
8831       if (!I->getType()->isLiteralType(Context) ||
8832           I->getType().isVolatileQualified()) {
8833         Diag(I->getLocation(), diag::note_non_literal_field)
8834           << RD << I << I->getType()
8835           << I->getType().isVolatileQualified();
8836         return true;
8837       }
8838     }
8839   } else if (getLangOpts().CPlusPlus20 ? !RD->hasConstexprDestructor()
8840                                        : !RD->hasTrivialDestructor()) {
8841     // All fields and bases are of literal types, so have trivial or constexpr
8842     // destructors. If this class's destructor is non-trivial / non-constexpr,
8843     // it must be user-declared.
8844     CXXDestructorDecl *Dtor = RD->getDestructor();
8845     assert(Dtor && "class has literal fields and bases but no dtor?");
8846     if (!Dtor)
8847       return true;
8848 
8849     if (getLangOpts().CPlusPlus20) {
8850       Diag(Dtor->getLocation(), diag::note_non_literal_non_constexpr_dtor)
8851           << RD;
8852     } else {
8853       Diag(Dtor->getLocation(), Dtor->isUserProvided()
8854                                     ? diag::note_non_literal_user_provided_dtor
8855                                     : diag::note_non_literal_nontrivial_dtor)
8856           << RD;
8857       if (!Dtor->isUserProvided())
8858         SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI,
8859                                /*Diagnose*/ true);
8860     }
8861   }
8862 
8863   return true;
8864 }
8865 
RequireLiteralType(SourceLocation Loc,QualType T,unsigned DiagID)8866 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
8867   BoundTypeDiagnoser<> Diagnoser(DiagID);
8868   return RequireLiteralType(Loc, T, Diagnoser);
8869 }
8870 
8871 /// Retrieve a version of the type 'T' that is elaborated by Keyword, qualified
8872 /// by the nested-name-specifier contained in SS, and that is (re)declared by
8873 /// OwnedTagDecl, which is nullptr if this is not a (re)declaration.
getElaboratedType(ElaboratedTypeKeyword Keyword,const CXXScopeSpec & SS,QualType T,TagDecl * OwnedTagDecl)8874 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
8875                                  const CXXScopeSpec &SS, QualType T,
8876                                  TagDecl *OwnedTagDecl) {
8877   if (T.isNull())
8878     return T;
8879   NestedNameSpecifier *NNS;
8880   if (SS.isValid())
8881     NNS = SS.getScopeRep();
8882   else {
8883     if (Keyword == ETK_None)
8884       return T;
8885     NNS = nullptr;
8886   }
8887   return Context.getElaboratedType(Keyword, NNS, T, OwnedTagDecl);
8888 }
8889 
BuildTypeofExprType(Expr * E,SourceLocation Loc)8890 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
8891   assert(!E->hasPlaceholderType() && "unexpected placeholder");
8892 
8893   if (!getLangOpts().CPlusPlus && E->refersToBitField())
8894     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2;
8895 
8896   if (!E->isTypeDependent()) {
8897     QualType T = E->getType();
8898     if (const TagType *TT = T->getAs<TagType>())
8899       DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
8900   }
8901   return Context.getTypeOfExprType(E);
8902 }
8903 
8904 /// getDecltypeForExpr - Given an expr, will return the decltype for
8905 /// that expression, according to the rules in C++11
8906 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
getDecltypeForExpr(Sema & S,Expr * E)8907 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
8908   if (E->isTypeDependent())
8909     return S.Context.DependentTy;
8910 
8911   Expr *IDExpr = E;
8912   if (auto *ImplCastExpr = dyn_cast<ImplicitCastExpr>(E))
8913     IDExpr = ImplCastExpr->getSubExpr();
8914 
8915   // C++11 [dcl.type.simple]p4:
8916   //   The type denoted by decltype(e) is defined as follows:
8917 
8918   // C++20:
8919   //     - if E is an unparenthesized id-expression naming a non-type
8920   //       template-parameter (13.2), decltype(E) is the type of the
8921   //       template-parameter after performing any necessary type deduction
8922   // Note that this does not pick up the implicit 'const' for a template
8923   // parameter object. This rule makes no difference before C++20 so we apply
8924   // it unconditionally.
8925   if (const auto *SNTTPE = dyn_cast<SubstNonTypeTemplateParmExpr>(IDExpr))
8926     return SNTTPE->getParameterType(S.Context);
8927 
8928   //     - if e is an unparenthesized id-expression or an unparenthesized class
8929   //       member access (5.2.5), decltype(e) is the type of the entity named
8930   //       by e. If there is no such entity, or if e names a set of overloaded
8931   //       functions, the program is ill-formed;
8932   //
8933   // We apply the same rules for Objective-C ivar and property references.
8934   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(IDExpr)) {
8935     const ValueDecl *VD = DRE->getDecl();
8936     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(VD))
8937       return TPO->getType().getUnqualifiedType();
8938     return VD->getType();
8939   } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(IDExpr)) {
8940     if (const ValueDecl *VD = ME->getMemberDecl())
8941       if (isa<FieldDecl>(VD) || isa<VarDecl>(VD))
8942         return VD->getType();
8943   } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(IDExpr)) {
8944     return IR->getDecl()->getType();
8945   } else if (const ObjCPropertyRefExpr *PR =
8946                  dyn_cast<ObjCPropertyRefExpr>(IDExpr)) {
8947     if (PR->isExplicitProperty())
8948       return PR->getExplicitProperty()->getType();
8949   } else if (auto *PE = dyn_cast<PredefinedExpr>(IDExpr)) {
8950     return PE->getType();
8951   }
8952 
8953   // C++11 [expr.lambda.prim]p18:
8954   //   Every occurrence of decltype((x)) where x is a possibly
8955   //   parenthesized id-expression that names an entity of automatic
8956   //   storage duration is treated as if x were transformed into an
8957   //   access to a corresponding data member of the closure type that
8958   //   would have been declared if x were an odr-use of the denoted
8959   //   entity.
8960   using namespace sema;
8961   if (S.getCurLambda()) {
8962     if (isa<ParenExpr>(IDExpr)) {
8963       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(IDExpr->IgnoreParens())) {
8964         if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
8965           QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
8966           if (!T.isNull())
8967             return S.Context.getLValueReferenceType(T);
8968         }
8969       }
8970     }
8971   }
8972 
8973   return S.Context.getReferenceQualifiedType(E);
8974 }
8975 
BuildDecltypeType(Expr * E,SourceLocation Loc,bool AsUnevaluated)8976 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc,
8977                                  bool AsUnevaluated) {
8978   assert(!E->hasPlaceholderType() && "unexpected placeholder");
8979 
8980   if (AsUnevaluated && CodeSynthesisContexts.empty() &&
8981       !E->isInstantiationDependent() && E->HasSideEffects(Context, false)) {
8982     // The expression operand for decltype is in an unevaluated expression
8983     // context, so side effects could result in unintended consequences.
8984     // Exclude instantiation-dependent expressions, because 'decltype' is often
8985     // used to build SFINAE gadgets.
8986     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
8987   }
8988 
8989   return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
8990 }
8991 
BuildUnaryTransformType(QualType BaseType,UnaryTransformType::UTTKind UKind,SourceLocation Loc)8992 QualType Sema::BuildUnaryTransformType(QualType BaseType,
8993                                        UnaryTransformType::UTTKind UKind,
8994                                        SourceLocation Loc) {
8995   switch (UKind) {
8996   case UnaryTransformType::EnumUnderlyingType:
8997     if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
8998       Diag(Loc, diag::err_only_enums_have_underlying_types);
8999       return QualType();
9000     } else {
9001       QualType Underlying = BaseType;
9002       if (!BaseType->isDependentType()) {
9003         // The enum could be incomplete if we're parsing its definition or
9004         // recovering from an error.
9005         NamedDecl *FwdDecl = nullptr;
9006         if (BaseType->isIncompleteType(&FwdDecl)) {
9007           Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
9008           Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
9009           return QualType();
9010         }
9011 
9012         EnumDecl *ED = BaseType->castAs<EnumType>()->getDecl();
9013         assert(ED && "EnumType has no EnumDecl");
9014 
9015         DiagnoseUseOfDecl(ED, Loc);
9016 
9017         Underlying = ED->getIntegerType();
9018         assert(!Underlying.isNull());
9019       }
9020       return Context.getUnaryTransformType(BaseType, Underlying,
9021                                         UnaryTransformType::EnumUnderlyingType);
9022     }
9023   }
9024   llvm_unreachable("unknown unary transform type");
9025 }
9026 
BuildAtomicType(QualType T,SourceLocation Loc)9027 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
9028   if (!T->isDependentType()) {
9029     // FIXME: It isn't entirely clear whether incomplete atomic types
9030     // are allowed or not; for simplicity, ban them for the moment.
9031     if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
9032       return QualType();
9033 
9034     int DisallowedKind = -1;
9035     if (T->isArrayType())
9036       DisallowedKind = 1;
9037     else if (T->isFunctionType())
9038       DisallowedKind = 2;
9039     else if (T->isReferenceType())
9040       DisallowedKind = 3;
9041     else if (T->isAtomicType())
9042       DisallowedKind = 4;
9043     else if (T.hasQualifiers())
9044       DisallowedKind = 5;
9045     else if (T->isSizelessType())
9046       DisallowedKind = 6;
9047     else if (!T.isTriviallyCopyableType(Context))
9048       // Some other non-trivially-copyable type (probably a C++ class)
9049       DisallowedKind = 7;
9050     else if (T->isExtIntType()) {
9051         DisallowedKind = 8;
9052     }
9053 
9054     if (DisallowedKind != -1) {
9055       Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
9056       return QualType();
9057     }
9058 
9059     // FIXME: Do we need any handling for ARC here?
9060   }
9061 
9062   // Build the pointer type.
9063   return Context.getAtomicType(T);
9064 }
9065