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