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