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