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