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