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