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