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