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