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