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