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