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.getAttrName()->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;
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_wchar_t_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_wchar_t_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 &AL) {
3946   AL.setUsedAsTypeAttr();
3947   return ::new (Ctx) AttrT(Ctx, AL);
3948 }
3949 
3950 static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr,
3951                                    NullabilityKind NK) {
3952   switch (NK) {
3953   case NullabilityKind::NonNull:
3954     return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr);
3955 
3956   case NullabilityKind::Nullable:
3957     return createSimpleAttr<TypeNullableAttr>(Ctx, Attr);
3958 
3959   case NullabilityKind::Unspecified:
3960     return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr);
3961   }
3962   llvm_unreachable("unknown NullabilityKind");
3963 }
3964 
3965 // Diagnose whether this is a case with the multiple addr spaces.
3966 // Returns true if this is an invalid case.
3967 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
3968 // by qualifiers for two or more different address spaces."
3969 static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld,
3970                                                 LangAS ASNew,
3971                                                 SourceLocation AttrLoc) {
3972   if (ASOld != LangAS::Default) {
3973     if (ASOld != ASNew) {
3974       S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
3975       return true;
3976     }
3977     // Emit a warning if they are identical; it's likely unintended.
3978     S.Diag(AttrLoc,
3979            diag::warn_attribute_address_multiple_identical_qualifiers);
3980   }
3981   return false;
3982 }
3983 
3984 static TypeSourceInfo *
3985 GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3986                                QualType T, TypeSourceInfo *ReturnTypeInfo);
3987 
3988 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
3989                                                 QualType declSpecType,
3990                                                 TypeSourceInfo *TInfo) {
3991   // The TypeSourceInfo that this function returns will not be a null type.
3992   // If there is an error, this function will fill in a dummy type as fallback.
3993   QualType T = declSpecType;
3994   Declarator &D = state.getDeclarator();
3995   Sema &S = state.getSema();
3996   ASTContext &Context = S.Context;
3997   const LangOptions &LangOpts = S.getLangOpts();
3998 
3999   // The name we're declaring, if any.
4000   DeclarationName Name;
4001   if (D.getIdentifier())
4002     Name = D.getIdentifier();
4003 
4004   // Does this declaration declare a typedef-name?
4005   bool IsTypedefName =
4006     D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
4007     D.getContext() == DeclaratorContext::AliasDeclContext ||
4008     D.getContext() == DeclaratorContext::AliasTemplateContext;
4009 
4010   // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
4011   bool IsQualifiedFunction = T->isFunctionProtoType() &&
4012       (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() ||
4013        T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
4014 
4015   // If T is 'decltype(auto)', the only declarators we can have are parens
4016   // and at most one function declarator if this is a function declaration.
4017   // If T is a deduced class template specialization type, we can have no
4018   // declarator chunks at all.
4019   if (auto *DT = T->getAs<DeducedType>()) {
4020     const AutoType *AT = T->getAs<AutoType>();
4021     bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
4022     if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
4023       for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4024         unsigned Index = E - I - 1;
4025         DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
4026         unsigned DiagId = IsClassTemplateDeduction
4027                               ? diag::err_deduced_class_template_compound_type
4028                               : diag::err_decltype_auto_compound_type;
4029         unsigned DiagKind = 0;
4030         switch (DeclChunk.Kind) {
4031         case DeclaratorChunk::Paren:
4032           // FIXME: Rejecting this is a little silly.
4033           if (IsClassTemplateDeduction) {
4034             DiagKind = 4;
4035             break;
4036           }
4037           continue;
4038         case DeclaratorChunk::Function: {
4039           if (IsClassTemplateDeduction) {
4040             DiagKind = 3;
4041             break;
4042           }
4043           unsigned FnIndex;
4044           if (D.isFunctionDeclarationContext() &&
4045               D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
4046             continue;
4047           DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
4048           break;
4049         }
4050         case DeclaratorChunk::Pointer:
4051         case DeclaratorChunk::BlockPointer:
4052         case DeclaratorChunk::MemberPointer:
4053           DiagKind = 0;
4054           break;
4055         case DeclaratorChunk::Reference:
4056           DiagKind = 1;
4057           break;
4058         case DeclaratorChunk::Array:
4059           DiagKind = 2;
4060           break;
4061         case DeclaratorChunk::Pipe:
4062           break;
4063         }
4064 
4065         S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
4066         D.setInvalidType(true);
4067         break;
4068       }
4069     }
4070   }
4071 
4072   // Determine whether we should infer _Nonnull on pointer types.
4073   Optional<NullabilityKind> inferNullability;
4074   bool inferNullabilityCS = false;
4075   bool inferNullabilityInnerOnly = false;
4076   bool inferNullabilityInnerOnlyComplete = false;
4077 
4078   // Are we in an assume-nonnull region?
4079   bool inAssumeNonNullRegion = false;
4080   SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4081   if (assumeNonNullLoc.isValid()) {
4082     inAssumeNonNullRegion = true;
4083     recordNullabilitySeen(S, assumeNonNullLoc);
4084   }
4085 
4086   // Whether to complain about missing nullability specifiers or not.
4087   enum {
4088     /// Never complain.
4089     CAMN_No,
4090     /// Complain on the inner pointers (but not the outermost
4091     /// pointer).
4092     CAMN_InnerPointers,
4093     /// Complain about any pointers that don't have nullability
4094     /// specified or inferred.
4095     CAMN_Yes
4096   } complainAboutMissingNullability = CAMN_No;
4097   unsigned NumPointersRemaining = 0;
4098   auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4099 
4100   if (IsTypedefName) {
4101     // For typedefs, we do not infer any nullability (the default),
4102     // and we only complain about missing nullability specifiers on
4103     // inner pointers.
4104     complainAboutMissingNullability = CAMN_InnerPointers;
4105 
4106     if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
4107         !T->getNullability(S.Context)) {
4108       // Note that we allow but don't require nullability on dependent types.
4109       ++NumPointersRemaining;
4110     }
4111 
4112     for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
4113       DeclaratorChunk &chunk = D.getTypeObject(i);
4114       switch (chunk.Kind) {
4115       case DeclaratorChunk::Array:
4116       case DeclaratorChunk::Function:
4117       case DeclaratorChunk::Pipe:
4118         break;
4119 
4120       case DeclaratorChunk::BlockPointer:
4121       case DeclaratorChunk::MemberPointer:
4122         ++NumPointersRemaining;
4123         break;
4124 
4125       case DeclaratorChunk::Paren:
4126       case DeclaratorChunk::Reference:
4127         continue;
4128 
4129       case DeclaratorChunk::Pointer:
4130         ++NumPointersRemaining;
4131         continue;
4132       }
4133     }
4134   } else {
4135     bool isFunctionOrMethod = false;
4136     switch (auto context = state.getDeclarator().getContext()) {
4137     case DeclaratorContext::ObjCParameterContext:
4138     case DeclaratorContext::ObjCResultContext:
4139     case DeclaratorContext::PrototypeContext:
4140     case DeclaratorContext::TrailingReturnContext:
4141     case DeclaratorContext::TrailingReturnVarContext:
4142       isFunctionOrMethod = true;
4143       LLVM_FALLTHROUGH;
4144 
4145     case DeclaratorContext::MemberContext:
4146       if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
4147         complainAboutMissingNullability = CAMN_No;
4148         break;
4149       }
4150 
4151       // Weak properties are inferred to be nullable.
4152       if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) {
4153         inferNullability = NullabilityKind::Nullable;
4154         break;
4155       }
4156 
4157       LLVM_FALLTHROUGH;
4158 
4159     case DeclaratorContext::FileContext:
4160     case DeclaratorContext::KNRTypeListContext: {
4161       complainAboutMissingNullability = CAMN_Yes;
4162 
4163       // Nullability inference depends on the type and declarator.
4164       auto wrappingKind = PointerWrappingDeclaratorKind::None;
4165       switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4166       case PointerDeclaratorKind::NonPointer:
4167       case PointerDeclaratorKind::MultiLevelPointer:
4168         // Cannot infer nullability.
4169         break;
4170 
4171       case PointerDeclaratorKind::SingleLevelPointer:
4172         // Infer _Nonnull if we are in an assumes-nonnull region.
4173         if (inAssumeNonNullRegion) {
4174           complainAboutInferringWithinChunk = wrappingKind;
4175           inferNullability = NullabilityKind::NonNull;
4176           inferNullabilityCS =
4177               (context == DeclaratorContext::ObjCParameterContext ||
4178                context == DeclaratorContext::ObjCResultContext);
4179         }
4180         break;
4181 
4182       case PointerDeclaratorKind::CFErrorRefPointer:
4183       case PointerDeclaratorKind::NSErrorPointerPointer:
4184         // Within a function or method signature, infer _Nullable at both
4185         // levels.
4186         if (isFunctionOrMethod && inAssumeNonNullRegion)
4187           inferNullability = NullabilityKind::Nullable;
4188         break;
4189 
4190       case PointerDeclaratorKind::MaybePointerToCFRef:
4191         if (isFunctionOrMethod) {
4192           // On pointer-to-pointer parameters marked cf_returns_retained or
4193           // cf_returns_not_retained, if the outer pointer is explicit then
4194           // infer the inner pointer as _Nullable.
4195           auto hasCFReturnsAttr =
4196               [](const ParsedAttributesView &AttrList) -> bool {
4197             return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
4198                    AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained);
4199           };
4200           if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4201             if (hasCFReturnsAttr(D.getAttributes()) ||
4202                 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
4203                 hasCFReturnsAttr(D.getDeclSpec().getAttributes())) {
4204               inferNullability = NullabilityKind::Nullable;
4205               inferNullabilityInnerOnly = true;
4206             }
4207           }
4208         }
4209         break;
4210       }
4211       break;
4212     }
4213 
4214     case DeclaratorContext::ConversionIdContext:
4215       complainAboutMissingNullability = CAMN_Yes;
4216       break;
4217 
4218     case DeclaratorContext::AliasDeclContext:
4219     case DeclaratorContext::AliasTemplateContext:
4220     case DeclaratorContext::BlockContext:
4221     case DeclaratorContext::BlockLiteralContext:
4222     case DeclaratorContext::ConditionContext:
4223     case DeclaratorContext::CXXCatchContext:
4224     case DeclaratorContext::CXXNewContext:
4225     case DeclaratorContext::ForContext:
4226     case DeclaratorContext::InitStmtContext:
4227     case DeclaratorContext::LambdaExprContext:
4228     case DeclaratorContext::LambdaExprParameterContext:
4229     case DeclaratorContext::ObjCCatchContext:
4230     case DeclaratorContext::TemplateParamContext:
4231     case DeclaratorContext::TemplateArgContext:
4232     case DeclaratorContext::TemplateTypeArgContext:
4233     case DeclaratorContext::TypeNameContext:
4234     case DeclaratorContext::FunctionalCastContext:
4235       // Don't infer in these contexts.
4236       break;
4237     }
4238   }
4239 
4240   // Local function that returns true if its argument looks like a va_list.
4241   auto isVaList = [&S](QualType T) -> bool {
4242     auto *typedefTy = T->getAs<TypedefType>();
4243     if (!typedefTy)
4244       return false;
4245     TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4246     do {
4247       if (typedefTy->getDecl() == vaListTypedef)
4248         return true;
4249       if (auto *name = typedefTy->getDecl()->getIdentifier())
4250         if (name->isStr("va_list"))
4251           return true;
4252       typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4253     } while (typedefTy);
4254     return false;
4255   };
4256 
4257   // Local function that checks the nullability for a given pointer declarator.
4258   // Returns true if _Nonnull was inferred.
4259   auto inferPointerNullability =
4260       [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4261           SourceLocation pointerEndLoc,
4262           ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * {
4263     // We've seen a pointer.
4264     if (NumPointersRemaining > 0)
4265       --NumPointersRemaining;
4266 
4267     // If a nullability attribute is present, there's nothing to do.
4268     if (hasNullabilityAttr(attrs))
4269       return nullptr;
4270 
4271     // If we're supposed to infer nullability, do so now.
4272     if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4273       ParsedAttr::Syntax syntax = inferNullabilityCS
4274                                       ? ParsedAttr::AS_ContextSensitiveKeyword
4275                                       : ParsedAttr::AS_Keyword;
4276       ParsedAttr *nullabilityAttr = Pool.create(
4277           S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
4278           nullptr, SourceLocation(), nullptr, 0, syntax);
4279 
4280       attrs.addAtEnd(nullabilityAttr);
4281 
4282       if (inferNullabilityCS) {
4283         state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4284           ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4285       }
4286 
4287       if (pointerLoc.isValid() &&
4288           complainAboutInferringWithinChunk !=
4289             PointerWrappingDeclaratorKind::None) {
4290         auto Diag =
4291             S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
4292         Diag << static_cast<int>(complainAboutInferringWithinChunk);
4293         fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull);
4294       }
4295 
4296       if (inferNullabilityInnerOnly)
4297         inferNullabilityInnerOnlyComplete = true;
4298       return nullabilityAttr;
4299     }
4300 
4301     // If we're supposed to complain about missing nullability, do so
4302     // now if it's truly missing.
4303     switch (complainAboutMissingNullability) {
4304     case CAMN_No:
4305       break;
4306 
4307     case CAMN_InnerPointers:
4308       if (NumPointersRemaining == 0)
4309         break;
4310       LLVM_FALLTHROUGH;
4311 
4312     case CAMN_Yes:
4313       checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4314     }
4315     return nullptr;
4316   };
4317 
4318   // If the type itself could have nullability but does not, infer pointer
4319   // nullability and perform consistency checking.
4320   if (S.CodeSynthesisContexts.empty()) {
4321     if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
4322         !T->getNullability(S.Context)) {
4323       if (isVaList(T)) {
4324         // Record that we've seen a pointer, but do nothing else.
4325         if (NumPointersRemaining > 0)
4326           --NumPointersRemaining;
4327       } else {
4328         SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4329         if (T->isBlockPointerType())
4330           pointerKind = SimplePointerKind::BlockPointer;
4331         else if (T->isMemberPointerType())
4332           pointerKind = SimplePointerKind::MemberPointer;
4333 
4334         if (auto *attr = inferPointerNullability(
4335                 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4336                 D.getDeclSpec().getEndLoc(),
4337                 D.getMutableDeclSpec().getAttributes(),
4338                 D.getMutableDeclSpec().getAttributePool())) {
4339           T = state.getAttributedType(
4340               createNullabilityAttr(Context, *attr, *inferNullability), T, T);
4341         }
4342       }
4343     }
4344 
4345     if (complainAboutMissingNullability == CAMN_Yes &&
4346         T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) &&
4347         D.isPrototypeContext() &&
4348         !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) {
4349       checkNullabilityConsistency(S, SimplePointerKind::Array,
4350                                   D.getDeclSpec().getTypeSpecTypeLoc());
4351     }
4352   }
4353 
4354   bool ExpectNoDerefChunk =
4355       state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref);
4356 
4357   // Walk the DeclTypeInfo, building the recursive type as we go.
4358   // DeclTypeInfos are ordered from the identifier out, which is
4359   // opposite of what we want :).
4360   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4361     unsigned chunkIndex = e - i - 1;
4362     state.setCurrentChunkIndex(chunkIndex);
4363     DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4364     IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4365     switch (DeclType.Kind) {
4366     case DeclaratorChunk::Paren:
4367       if (i == 0)
4368         warnAboutRedundantParens(S, D, T);
4369       T = S.BuildParenType(T);
4370       break;
4371     case DeclaratorChunk::BlockPointer:
4372       // If blocks are disabled, emit an error.
4373       if (!LangOpts.Blocks)
4374         S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4375 
4376       // Handle pointer nullability.
4377       inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
4378                               DeclType.EndLoc, DeclType.getAttrs(),
4379                               state.getDeclarator().getAttributePool());
4380 
4381       T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4382       if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4383         // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4384         // qualified with const.
4385         if (LangOpts.OpenCL)
4386           DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4387         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4388       }
4389       break;
4390     case DeclaratorChunk::Pointer:
4391       // Verify that we're not building a pointer to pointer to function with
4392       // exception specification.
4393       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4394         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4395         D.setInvalidType(true);
4396         // Build the type anyway.
4397       }
4398 
4399       // Handle pointer nullability
4400       inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4401                               DeclType.EndLoc, DeclType.getAttrs(),
4402                               state.getDeclarator().getAttributePool());
4403 
4404       if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) {
4405         T = Context.getObjCObjectPointerType(T);
4406         if (DeclType.Ptr.TypeQuals)
4407           T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4408         break;
4409       }
4410 
4411       // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4412       // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4413       // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4414       if (LangOpts.OpenCL) {
4415         if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4416             T->isBlockPointerType()) {
4417           S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4418           D.setInvalidType(true);
4419         }
4420       }
4421 
4422       T = S.BuildPointerType(T, DeclType.Loc, Name);
4423       if (DeclType.Ptr.TypeQuals)
4424         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4425       break;
4426     case DeclaratorChunk::Reference: {
4427       // Verify that we're not building a reference to pointer to function with
4428       // exception specification.
4429       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4430         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4431         D.setInvalidType(true);
4432         // Build the type anyway.
4433       }
4434       T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
4435 
4436       if (DeclType.Ref.HasRestrict)
4437         T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
4438       break;
4439     }
4440     case DeclaratorChunk::Array: {
4441       // Verify that we're not building an array of pointers to function with
4442       // exception specification.
4443       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4444         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4445         D.setInvalidType(true);
4446         // Build the type anyway.
4447       }
4448       DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4449       Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
4450       ArrayType::ArraySizeModifier ASM;
4451       if (ATI.isStar)
4452         ASM = ArrayType::Star;
4453       else if (ATI.hasStatic)
4454         ASM = ArrayType::Static;
4455       else
4456         ASM = ArrayType::Normal;
4457       if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
4458         // FIXME: This check isn't quite right: it allows star in prototypes
4459         // for function definitions, and disallows some edge cases detailed
4460         // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4461         S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
4462         ASM = ArrayType::Normal;
4463         D.setInvalidType(true);
4464       }
4465 
4466       // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4467       // shall appear only in a declaration of a function parameter with an
4468       // array type, ...
4469       if (ASM == ArrayType::Static || ATI.TypeQuals) {
4470         if (!(D.isPrototypeContext() ||
4471               D.getContext() == DeclaratorContext::KNRTypeListContext)) {
4472           S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
4473               (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4474           // Remove the 'static' and the type qualifiers.
4475           if (ASM == ArrayType::Static)
4476             ASM = ArrayType::Normal;
4477           ATI.TypeQuals = 0;
4478           D.setInvalidType(true);
4479         }
4480 
4481         // C99 6.7.5.2p1: ... and then only in the outermost array type
4482         // derivation.
4483         if (hasOuterPointerLikeChunk(D, chunkIndex)) {
4484           S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
4485             (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4486           if (ASM == ArrayType::Static)
4487             ASM = ArrayType::Normal;
4488           ATI.TypeQuals = 0;
4489           D.setInvalidType(true);
4490         }
4491       }
4492       const AutoType *AT = T->getContainedAutoType();
4493       // Allow arrays of auto if we are a generic lambda parameter.
4494       // i.e. [](auto (&array)[5]) { return array[0]; }; OK
4495       if (AT &&
4496           D.getContext() != DeclaratorContext::LambdaExprParameterContext) {
4497         // We've already diagnosed this for decltype(auto).
4498         if (!AT->isDecltypeAuto())
4499           S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
4500             << getPrintableNameForEntity(Name) << T;
4501         T = QualType();
4502         break;
4503       }
4504 
4505       // Array parameters can be marked nullable as well, although it's not
4506       // necessary if they're marked 'static'.
4507       if (complainAboutMissingNullability == CAMN_Yes &&
4508           !hasNullabilityAttr(DeclType.getAttrs()) &&
4509           ASM != ArrayType::Static &&
4510           D.isPrototypeContext() &&
4511           !hasOuterPointerLikeChunk(D, chunkIndex)) {
4512         checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
4513       }
4514 
4515       T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
4516                            SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
4517       break;
4518     }
4519     case DeclaratorChunk::Function: {
4520       // If the function declarator has a prototype (i.e. it is not () and
4521       // does not have a K&R-style identifier list), then the arguments are part
4522       // of the type, otherwise the argument list is ().
4523       DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4524       IsQualifiedFunction =
4525           FTI.hasMethodTypeQualifiers() || FTI.hasRefQualifier();
4526 
4527       // Check for auto functions and trailing return type and adjust the
4528       // return type accordingly.
4529       if (!D.isInvalidType()) {
4530         // trailing-return-type is only required if we're declaring a function,
4531         // and not, for instance, a pointer to a function.
4532         if (D.getDeclSpec().hasAutoTypeSpec() &&
4533             !FTI.hasTrailingReturnType() && chunkIndex == 0) {
4534           if (!S.getLangOpts().CPlusPlus14) {
4535             S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4536                    D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
4537                        ? diag::err_auto_missing_trailing_return
4538                        : diag::err_deduced_return_type);
4539             T = Context.IntTy;
4540             D.setInvalidType(true);
4541           } else {
4542             S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4543                    diag::warn_cxx11_compat_deduced_return_type);
4544           }
4545         } else if (FTI.hasTrailingReturnType()) {
4546           // T must be exactly 'auto' at this point. See CWG issue 681.
4547           if (isa<ParenType>(T)) {
4548             S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens)
4549                 << T << D.getSourceRange();
4550             D.setInvalidType(true);
4551           } else if (D.getName().getKind() ==
4552                      UnqualifiedIdKind::IK_DeductionGuideName) {
4553             if (T != Context.DependentTy) {
4554               S.Diag(D.getDeclSpec().getBeginLoc(),
4555                      diag::err_deduction_guide_with_complex_decl)
4556                   << D.getSourceRange();
4557               D.setInvalidType(true);
4558             }
4559           } else if (D.getContext() != DeclaratorContext::LambdaExprContext &&
4560                      (T.hasQualifiers() || !isa<AutoType>(T) ||
4561                       cast<AutoType>(T)->getKeyword() !=
4562                           AutoTypeKeyword::Auto)) {
4563             S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4564                    diag::err_trailing_return_without_auto)
4565                 << T << D.getDeclSpec().getSourceRange();
4566             D.setInvalidType(true);
4567           }
4568           T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
4569           if (T.isNull()) {
4570             // An error occurred parsing the trailing return type.
4571             T = Context.IntTy;
4572             D.setInvalidType(true);
4573           }
4574         } else {
4575           // This function type is not the type of the entity being declared,
4576           // so checking the 'auto' is not the responsibility of this chunk.
4577         }
4578       }
4579 
4580       // C99 6.7.5.3p1: The return type may not be a function or array type.
4581       // For conversion functions, we'll diagnose this particular error later.
4582       if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) &&
4583           (D.getName().getKind() !=
4584            UnqualifiedIdKind::IK_ConversionFunctionId)) {
4585         unsigned diagID = diag::err_func_returning_array_function;
4586         // Last processing chunk in block context means this function chunk
4587         // represents the block.
4588         if (chunkIndex == 0 &&
4589             D.getContext() == DeclaratorContext::BlockLiteralContext)
4590           diagID = diag::err_block_returning_array_function;
4591         S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
4592         T = Context.IntTy;
4593         D.setInvalidType(true);
4594       }
4595 
4596       // Do not allow returning half FP value.
4597       // FIXME: This really should be in BuildFunctionType.
4598       if (T->isHalfType()) {
4599         if (S.getLangOpts().OpenCL) {
4600           if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
4601             S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4602                 << T << 0 /*pointer hint*/;
4603             D.setInvalidType(true);
4604           }
4605         } else if (!S.getLangOpts().HalfArgsAndReturns) {
4606           S.Diag(D.getIdentifierLoc(),
4607             diag::err_parameters_retval_cannot_have_fp16_type) << 1;
4608           D.setInvalidType(true);
4609         }
4610       }
4611 
4612       if (LangOpts.OpenCL) {
4613         // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
4614         // function.
4615         if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
4616             T->isPipeType()) {
4617           S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4618               << T << 1 /*hint off*/;
4619           D.setInvalidType(true);
4620         }
4621         // OpenCL doesn't support variadic functions and blocks
4622         // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
4623         // We also allow here any toolchain reserved identifiers.
4624         if (FTI.isVariadic &&
4625             !(D.getIdentifier() &&
4626               ((D.getIdentifier()->getName() == "printf" &&
4627                 (LangOpts.OpenCLCPlusPlus || LangOpts.OpenCLVersion >= 120)) ||
4628                D.getIdentifier()->getName().startswith("__")))) {
4629           S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
4630           D.setInvalidType(true);
4631         }
4632       }
4633 
4634       // Methods cannot return interface types. All ObjC objects are
4635       // passed by reference.
4636       if (T->isObjCObjectType()) {
4637         SourceLocation DiagLoc, FixitLoc;
4638         if (TInfo) {
4639           DiagLoc = TInfo->getTypeLoc().getBeginLoc();
4640           FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc());
4641         } else {
4642           DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
4643           FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc());
4644         }
4645         S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
4646           << 0 << T
4647           << FixItHint::CreateInsertion(FixitLoc, "*");
4648 
4649         T = Context.getObjCObjectPointerType(T);
4650         if (TInfo) {
4651           TypeLocBuilder TLB;
4652           TLB.pushFullCopy(TInfo->getTypeLoc());
4653           ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
4654           TLoc.setStarLoc(FixitLoc);
4655           TInfo = TLB.getTypeSourceInfo(Context, T);
4656         }
4657 
4658         D.setInvalidType(true);
4659       }
4660 
4661       // cv-qualifiers on return types are pointless except when the type is a
4662       // class type in C++.
4663       if ((T.getCVRQualifiers() || T->isAtomicType()) &&
4664           !(S.getLangOpts().CPlusPlus &&
4665             (T->isDependentType() || T->isRecordType()))) {
4666         if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
4667             D.getFunctionDefinitionKind() == FDK_Definition) {
4668           // [6.9.1/3] qualified void return is invalid on a C
4669           // function definition.  Apparently ok on declarations and
4670           // in C++ though (!)
4671           S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
4672         } else
4673           diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
4674       }
4675 
4676       // Objective-C ARC ownership qualifiers are ignored on the function
4677       // return type (by type canonicalization). Complain if this attribute
4678       // was written here.
4679       if (T.getQualifiers().hasObjCLifetime()) {
4680         SourceLocation AttrLoc;
4681         if (chunkIndex + 1 < D.getNumTypeObjects()) {
4682           DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
4683           for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) {
4684             if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
4685               AttrLoc = AL.getLoc();
4686               break;
4687             }
4688           }
4689         }
4690         if (AttrLoc.isInvalid()) {
4691           for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
4692             if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
4693               AttrLoc = AL.getLoc();
4694               break;
4695             }
4696           }
4697         }
4698 
4699         if (AttrLoc.isValid()) {
4700           // The ownership attributes are almost always written via
4701           // the predefined
4702           // __strong/__weak/__autoreleasing/__unsafe_unretained.
4703           if (AttrLoc.isMacroID())
4704             AttrLoc =
4705                 S.SourceMgr.getImmediateExpansionRange(AttrLoc).getBegin();
4706 
4707           S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
4708             << T.getQualifiers().getObjCLifetime();
4709         }
4710       }
4711 
4712       if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
4713         // C++ [dcl.fct]p6:
4714         //   Types shall not be defined in return or parameter types.
4715         TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
4716         S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
4717           << Context.getTypeDeclType(Tag);
4718       }
4719 
4720       // Exception specs are not allowed in typedefs. Complain, but add it
4721       // anyway.
4722       if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
4723         S.Diag(FTI.getExceptionSpecLocBeg(),
4724                diag::err_exception_spec_in_typedef)
4725             << (D.getContext() == DeclaratorContext::AliasDeclContext ||
4726                 D.getContext() == DeclaratorContext::AliasTemplateContext);
4727 
4728       // If we see "T var();" or "T var(T());" at block scope, it is probably
4729       // an attempt to initialize a variable, not a function declaration.
4730       if (FTI.isAmbiguous)
4731         warnAboutAmbiguousFunction(S, D, DeclType, T);
4732 
4733       FunctionType::ExtInfo EI(
4734           getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex));
4735 
4736       if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus
4737                                             && !LangOpts.OpenCL) {
4738         // Simple void foo(), where the incoming T is the result type.
4739         T = Context.getFunctionNoProtoType(T, EI);
4740       } else {
4741         // We allow a zero-parameter variadic function in C if the
4742         // function is marked with the "overloadable" attribute. Scan
4743         // for this attribute now.
4744         if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus)
4745           if (!D.getAttributes().hasAttribute(ParsedAttr::AT_Overloadable))
4746             S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
4747 
4748         if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
4749           // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
4750           // definition.
4751           S.Diag(FTI.Params[0].IdentLoc,
4752                  diag::err_ident_list_in_fn_declaration);
4753           D.setInvalidType(true);
4754           // Recover by creating a K&R-style function type.
4755           T = Context.getFunctionNoProtoType(T, EI);
4756           break;
4757         }
4758 
4759         FunctionProtoType::ExtProtoInfo EPI;
4760         EPI.ExtInfo = EI;
4761         EPI.Variadic = FTI.isVariadic;
4762         EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
4763         EPI.TypeQuals.addCVRUQualifiers(
4764             FTI.MethodQualifiers ? FTI.MethodQualifiers->getTypeQualifiers()
4765                                  : 0);
4766         EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
4767                     : FTI.RefQualifierIsLValueRef? RQ_LValue
4768                     : RQ_RValue;
4769 
4770         // Otherwise, we have a function with a parameter list that is
4771         // potentially variadic.
4772         SmallVector<QualType, 16> ParamTys;
4773         ParamTys.reserve(FTI.NumParams);
4774 
4775         SmallVector<FunctionProtoType::ExtParameterInfo, 16>
4776           ExtParameterInfos(FTI.NumParams);
4777         bool HasAnyInterestingExtParameterInfos = false;
4778 
4779         for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
4780           ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
4781           QualType ParamTy = Param->getType();
4782           assert(!ParamTy.isNull() && "Couldn't parse type?");
4783 
4784           // Look for 'void'.  void is allowed only as a single parameter to a
4785           // function with no other parameters (C99 6.7.5.3p10).  We record
4786           // int(void) as a FunctionProtoType with an empty parameter list.
4787           if (ParamTy->isVoidType()) {
4788             // If this is something like 'float(int, void)', reject it.  'void'
4789             // is an incomplete type (C99 6.2.5p19) and function decls cannot
4790             // have parameters of incomplete type.
4791             if (FTI.NumParams != 1 || FTI.isVariadic) {
4792               S.Diag(DeclType.Loc, diag::err_void_only_param);
4793               ParamTy = Context.IntTy;
4794               Param->setType(ParamTy);
4795             } else if (FTI.Params[i].Ident) {
4796               // Reject, but continue to parse 'int(void abc)'.
4797               S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
4798               ParamTy = Context.IntTy;
4799               Param->setType(ParamTy);
4800             } else {
4801               // Reject, but continue to parse 'float(const void)'.
4802               if (ParamTy.hasQualifiers())
4803                 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
4804 
4805               // Do not add 'void' to the list.
4806               break;
4807             }
4808           } else if (ParamTy->isHalfType()) {
4809             // Disallow half FP parameters.
4810             // FIXME: This really should be in BuildFunctionType.
4811             if (S.getLangOpts().OpenCL) {
4812               if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
4813                 S.Diag(Param->getLocation(),
4814                   diag::err_opencl_half_param) << ParamTy;
4815                 D.setInvalidType();
4816                 Param->setInvalidDecl();
4817               }
4818             } else if (!S.getLangOpts().HalfArgsAndReturns) {
4819               S.Diag(Param->getLocation(),
4820                 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
4821               D.setInvalidType();
4822             }
4823           } else if (!FTI.hasPrototype) {
4824             if (ParamTy->isPromotableIntegerType()) {
4825               ParamTy = Context.getPromotedIntegerType(ParamTy);
4826               Param->setKNRPromoted(true);
4827             } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
4828               if (BTy->getKind() == BuiltinType::Float) {
4829                 ParamTy = Context.DoubleTy;
4830                 Param->setKNRPromoted(true);
4831               }
4832             }
4833           }
4834 
4835           if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
4836             ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
4837             HasAnyInterestingExtParameterInfos = true;
4838           }
4839 
4840           if (auto attr = Param->getAttr<ParameterABIAttr>()) {
4841             ExtParameterInfos[i] =
4842               ExtParameterInfos[i].withABI(attr->getABI());
4843             HasAnyInterestingExtParameterInfos = true;
4844           }
4845 
4846           if (Param->hasAttr<PassObjectSizeAttr>()) {
4847             ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
4848             HasAnyInterestingExtParameterInfos = true;
4849           }
4850 
4851           if (Param->hasAttr<NoEscapeAttr>()) {
4852             ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
4853             HasAnyInterestingExtParameterInfos = true;
4854           }
4855 
4856           ParamTys.push_back(ParamTy);
4857         }
4858 
4859         if (HasAnyInterestingExtParameterInfos) {
4860           EPI.ExtParameterInfos = ExtParameterInfos.data();
4861           checkExtParameterInfos(S, ParamTys, EPI,
4862               [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
4863         }
4864 
4865         SmallVector<QualType, 4> Exceptions;
4866         SmallVector<ParsedType, 2> DynamicExceptions;
4867         SmallVector<SourceRange, 2> DynamicExceptionRanges;
4868         Expr *NoexceptExpr = nullptr;
4869 
4870         if (FTI.getExceptionSpecType() == EST_Dynamic) {
4871           // FIXME: It's rather inefficient to have to split into two vectors
4872           // here.
4873           unsigned N = FTI.getNumExceptions();
4874           DynamicExceptions.reserve(N);
4875           DynamicExceptionRanges.reserve(N);
4876           for (unsigned I = 0; I != N; ++I) {
4877             DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
4878             DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
4879           }
4880         } else if (isComputedNoexcept(FTI.getExceptionSpecType())) {
4881           NoexceptExpr = FTI.NoexceptExpr;
4882         }
4883 
4884         S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
4885                                       FTI.getExceptionSpecType(),
4886                                       DynamicExceptions,
4887                                       DynamicExceptionRanges,
4888                                       NoexceptExpr,
4889                                       Exceptions,
4890                                       EPI.ExceptionSpec);
4891 
4892         // FIXME: Set address space from attrs for C++ mode here.
4893         // OpenCLCPlusPlus: A class member function has an address space.
4894         auto IsClassMember = [&]() {
4895           return (!state.getDeclarator().getCXXScopeSpec().isEmpty() &&
4896                   state.getDeclarator()
4897                           .getCXXScopeSpec()
4898                           .getScopeRep()
4899                           ->getKind() == NestedNameSpecifier::TypeSpec) ||
4900                  state.getDeclarator().getContext() ==
4901                      DeclaratorContext::MemberContext;
4902         };
4903 
4904         if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) {
4905           LangAS ASIdx = LangAS::Default;
4906           // Take address space attr if any and mark as invalid to avoid adding
4907           // them later while creating QualType.
4908           if (FTI.MethodQualifiers)
4909             for (ParsedAttr &attr : FTI.MethodQualifiers->getAttributes()) {
4910               LangAS ASIdxNew = attr.asOpenCLLangAS();
4911               if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew,
4912                                                       attr.getLoc()))
4913                 D.setInvalidType(true);
4914               else
4915                 ASIdx = ASIdxNew;
4916             }
4917           // If a class member function's address space is not set, set it to
4918           // __generic.
4919           LangAS AS =
4920               (ASIdx == LangAS::Default ? LangAS::opencl_generic : ASIdx);
4921           EPI.TypeQuals.addAddressSpace(AS);
4922         }
4923         T = Context.getFunctionType(T, ParamTys, EPI);
4924       }
4925       break;
4926     }
4927     case DeclaratorChunk::MemberPointer: {
4928       // The scope spec must refer to a class, or be dependent.
4929       CXXScopeSpec &SS = DeclType.Mem.Scope();
4930       QualType ClsType;
4931 
4932       // Handle pointer nullability.
4933       inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
4934                               DeclType.EndLoc, DeclType.getAttrs(),
4935                               state.getDeclarator().getAttributePool());
4936 
4937       if (SS.isInvalid()) {
4938         // Avoid emitting extra errors if we already errored on the scope.
4939         D.setInvalidType(true);
4940       } else if (S.isDependentScopeSpecifier(SS) ||
4941                  dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
4942         NestedNameSpecifier *NNS = SS.getScopeRep();
4943         NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
4944         switch (NNS->getKind()) {
4945         case NestedNameSpecifier::Identifier:
4946           ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
4947                                                  NNS->getAsIdentifier());
4948           break;
4949 
4950         case NestedNameSpecifier::Namespace:
4951         case NestedNameSpecifier::NamespaceAlias:
4952         case NestedNameSpecifier::Global:
4953         case NestedNameSpecifier::Super:
4954           llvm_unreachable("Nested-name-specifier must name a type");
4955 
4956         case NestedNameSpecifier::TypeSpec:
4957         case NestedNameSpecifier::TypeSpecWithTemplate:
4958           ClsType = QualType(NNS->getAsType(), 0);
4959           // Note: if the NNS has a prefix and ClsType is a nondependent
4960           // TemplateSpecializationType, then the NNS prefix is NOT included
4961           // in ClsType; hence we wrap ClsType into an ElaboratedType.
4962           // NOTE: in particular, no wrap occurs if ClsType already is an
4963           // Elaborated, DependentName, or DependentTemplateSpecialization.
4964           if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
4965             ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
4966           break;
4967         }
4968       } else {
4969         S.Diag(DeclType.Mem.Scope().getBeginLoc(),
4970              diag::err_illegal_decl_mempointer_in_nonclass)
4971           << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
4972           << DeclType.Mem.Scope().getRange();
4973         D.setInvalidType(true);
4974       }
4975 
4976       if (!ClsType.isNull())
4977         T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
4978                                      D.getIdentifier());
4979       if (T.isNull()) {
4980         T = Context.IntTy;
4981         D.setInvalidType(true);
4982       } else if (DeclType.Mem.TypeQuals) {
4983         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
4984       }
4985       break;
4986     }
4987 
4988     case DeclaratorChunk::Pipe: {
4989       T = S.BuildReadPipeType(T, DeclType.Loc);
4990       processTypeAttrs(state, T, TAL_DeclSpec,
4991                        D.getMutableDeclSpec().getAttributes());
4992       break;
4993     }
4994     }
4995 
4996     if (T.isNull()) {
4997       D.setInvalidType(true);
4998       T = Context.IntTy;
4999     }
5000 
5001     // See if there are any attributes on this declarator chunk.
5002     processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs());
5003 
5004     if (DeclType.Kind != DeclaratorChunk::Paren) {
5005       if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType))
5006         S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array);
5007 
5008       ExpectNoDerefChunk = state.didParseNoDeref();
5009     }
5010   }
5011 
5012   if (ExpectNoDerefChunk)
5013     S.Diag(state.getDeclarator().getBeginLoc(),
5014            diag::warn_noderef_on_non_pointer_or_array);
5015 
5016   // GNU warning -Wstrict-prototypes
5017   //   Warn if a function declaration is without a prototype.
5018   //   This warning is issued for all kinds of unprototyped function
5019   //   declarations (i.e. function type typedef, function pointer etc.)
5020   //   C99 6.7.5.3p14:
5021   //   The empty list in a function declarator that is not part of a definition
5022   //   of that function specifies that no information about the number or types
5023   //   of the parameters is supplied.
5024   if (!LangOpts.CPlusPlus && D.getFunctionDefinitionKind() == FDK_Declaration) {
5025     bool IsBlock = false;
5026     for (const DeclaratorChunk &DeclType : D.type_objects()) {
5027       switch (DeclType.Kind) {
5028       case DeclaratorChunk::BlockPointer:
5029         IsBlock = true;
5030         break;
5031       case DeclaratorChunk::Function: {
5032         const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5033         // We supress the warning when there's no LParen location, as this
5034         // indicates the declaration was an implicit declaration, which gets
5035         // warned about separately via -Wimplicit-function-declaration.
5036         if (FTI.NumParams == 0 && !FTI.isVariadic && FTI.getLParenLoc().isValid())
5037           S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
5038               << IsBlock
5039               << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
5040         IsBlock = false;
5041         break;
5042       }
5043       default:
5044         break;
5045       }
5046     }
5047   }
5048 
5049   assert(!T.isNull() && "T must not be null after this point");
5050 
5051   if (LangOpts.CPlusPlus && T->isFunctionType()) {
5052     const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
5053     assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
5054 
5055     // C++ 8.3.5p4:
5056     //   A cv-qualifier-seq shall only be part of the function type
5057     //   for a nonstatic member function, the function type to which a pointer
5058     //   to member refers, or the top-level function type of a function typedef
5059     //   declaration.
5060     //
5061     // Core issue 547 also allows cv-qualifiers on function types that are
5062     // top-level template type arguments.
5063     enum { NonMember, Member, DeductionGuide } Kind = NonMember;
5064     if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
5065       Kind = DeductionGuide;
5066     else if (!D.getCXXScopeSpec().isSet()) {
5067       if ((D.getContext() == DeclaratorContext::MemberContext ||
5068            D.getContext() == DeclaratorContext::LambdaExprContext) &&
5069           !D.getDeclSpec().isFriendSpecified())
5070         Kind = Member;
5071     } else {
5072       DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
5073       if (!DC || DC->isRecord())
5074         Kind = Member;
5075     }
5076 
5077     // C++11 [dcl.fct]p6 (w/DR1417):
5078     // An attempt to specify a function type with a cv-qualifier-seq or a
5079     // ref-qualifier (including by typedef-name) is ill-formed unless it is:
5080     //  - the function type for a non-static member function,
5081     //  - the function type to which a pointer to member refers,
5082     //  - the top-level function type of a function typedef declaration or
5083     //    alias-declaration,
5084     //  - the type-id in the default argument of a type-parameter, or
5085     //  - the type-id of a template-argument for a type-parameter
5086     //
5087     // FIXME: Checking this here is insufficient. We accept-invalid on:
5088     //
5089     //   template<typename T> struct S { void f(T); };
5090     //   S<int() const> s;
5091     //
5092     // ... for instance.
5093     if (IsQualifiedFunction &&
5094         !(Kind == Member &&
5095           D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
5096         !IsTypedefName &&
5097         D.getContext() != DeclaratorContext::TemplateArgContext &&
5098         D.getContext() != DeclaratorContext::TemplateTypeArgContext) {
5099       SourceLocation Loc = D.getBeginLoc();
5100       SourceRange RemovalRange;
5101       unsigned I;
5102       if (D.isFunctionDeclarator(I)) {
5103         SmallVector<SourceLocation, 4> RemovalLocs;
5104         const DeclaratorChunk &Chunk = D.getTypeObject(I);
5105         assert(Chunk.Kind == DeclaratorChunk::Function);
5106 
5107         if (Chunk.Fun.hasRefQualifier())
5108           RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
5109 
5110         if (Chunk.Fun.hasMethodTypeQualifiers())
5111           Chunk.Fun.MethodQualifiers->forEachQualifier(
5112               [&](DeclSpec::TQ TypeQual, StringRef QualName,
5113                   SourceLocation SL) { RemovalLocs.push_back(SL); });
5114 
5115         if (!RemovalLocs.empty()) {
5116           llvm::sort(RemovalLocs,
5117                      BeforeThanCompare<SourceLocation>(S.getSourceManager()));
5118           RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
5119           Loc = RemovalLocs.front();
5120         }
5121       }
5122 
5123       S.Diag(Loc, diag::err_invalid_qualified_function_type)
5124         << Kind << D.isFunctionDeclarator() << T
5125         << getFunctionQualifiersAsString(FnTy)
5126         << FixItHint::CreateRemoval(RemovalRange);
5127 
5128       // Strip the cv-qualifiers and ref-qualifiers from the type.
5129       FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
5130       EPI.TypeQuals.removeCVRQualifiers();
5131       EPI.RefQualifier = RQ_None;
5132 
5133       T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
5134                                   EPI);
5135       // Rebuild any parens around the identifier in the function type.
5136       for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5137         if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
5138           break;
5139         T = S.BuildParenType(T);
5140       }
5141     }
5142   }
5143 
5144   // Apply any undistributed attributes from the declarator.
5145   processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
5146 
5147   // Diagnose any ignored type attributes.
5148   state.diagnoseIgnoredTypeAttrs(T);
5149 
5150   // C++0x [dcl.constexpr]p9:
5151   //  A constexpr specifier used in an object declaration declares the object
5152   //  as const.
5153   if (D.getDeclSpec().getConstexprSpecifier() == CSK_constexpr &&
5154       T->isObjectType())
5155     T.addConst();
5156 
5157   // If there was an ellipsis in the declarator, the declaration declares a
5158   // parameter pack whose type may be a pack expansion type.
5159   if (D.hasEllipsis()) {
5160     // C++0x [dcl.fct]p13:
5161     //   A declarator-id or abstract-declarator containing an ellipsis shall
5162     //   only be used in a parameter-declaration. Such a parameter-declaration
5163     //   is a parameter pack (14.5.3). [...]
5164     switch (D.getContext()) {
5165     case DeclaratorContext::PrototypeContext:
5166     case DeclaratorContext::LambdaExprParameterContext:
5167       // C++0x [dcl.fct]p13:
5168       //   [...] When it is part of a parameter-declaration-clause, the
5169       //   parameter pack is a function parameter pack (14.5.3). The type T
5170       //   of the declarator-id of the function parameter pack shall contain
5171       //   a template parameter pack; each template parameter pack in T is
5172       //   expanded by the function parameter pack.
5173       //
5174       // We represent function parameter packs as function parameters whose
5175       // type is a pack expansion.
5176       if (!T->containsUnexpandedParameterPack()) {
5177         S.Diag(D.getEllipsisLoc(),
5178              diag::err_function_parameter_pack_without_parameter_packs)
5179           << T <<  D.getSourceRange();
5180         D.setEllipsisLoc(SourceLocation());
5181       } else {
5182         T = Context.getPackExpansionType(T, None);
5183       }
5184       break;
5185     case DeclaratorContext::TemplateParamContext:
5186       // C++0x [temp.param]p15:
5187       //   If a template-parameter is a [...] is a parameter-declaration that
5188       //   declares a parameter pack (8.3.5), then the template-parameter is a
5189       //   template parameter pack (14.5.3).
5190       //
5191       // Note: core issue 778 clarifies that, if there are any unexpanded
5192       // parameter packs in the type of the non-type template parameter, then
5193       // it expands those parameter packs.
5194       if (T->containsUnexpandedParameterPack())
5195         T = Context.getPackExpansionType(T, None);
5196       else
5197         S.Diag(D.getEllipsisLoc(),
5198                LangOpts.CPlusPlus11
5199                  ? diag::warn_cxx98_compat_variadic_templates
5200                  : diag::ext_variadic_templates);
5201       break;
5202 
5203     case DeclaratorContext::FileContext:
5204     case DeclaratorContext::KNRTypeListContext:
5205     case DeclaratorContext::ObjCParameterContext:  // FIXME: special diagnostic
5206                                                    // here?
5207     case DeclaratorContext::ObjCResultContext:     // FIXME: special diagnostic
5208                                                    // here?
5209     case DeclaratorContext::TypeNameContext:
5210     case DeclaratorContext::FunctionalCastContext:
5211     case DeclaratorContext::CXXNewContext:
5212     case DeclaratorContext::AliasDeclContext:
5213     case DeclaratorContext::AliasTemplateContext:
5214     case DeclaratorContext::MemberContext:
5215     case DeclaratorContext::BlockContext:
5216     case DeclaratorContext::ForContext:
5217     case DeclaratorContext::InitStmtContext:
5218     case DeclaratorContext::ConditionContext:
5219     case DeclaratorContext::CXXCatchContext:
5220     case DeclaratorContext::ObjCCatchContext:
5221     case DeclaratorContext::BlockLiteralContext:
5222     case DeclaratorContext::LambdaExprContext:
5223     case DeclaratorContext::ConversionIdContext:
5224     case DeclaratorContext::TrailingReturnContext:
5225     case DeclaratorContext::TrailingReturnVarContext:
5226     case DeclaratorContext::TemplateArgContext:
5227     case DeclaratorContext::TemplateTypeArgContext:
5228       // FIXME: We may want to allow parameter packs in block-literal contexts
5229       // in the future.
5230       S.Diag(D.getEllipsisLoc(),
5231              diag::err_ellipsis_in_declarator_not_parameter);
5232       D.setEllipsisLoc(SourceLocation());
5233       break;
5234     }
5235   }
5236 
5237   assert(!T.isNull() && "T must not be null at the end of this function");
5238   if (D.isInvalidType())
5239     return Context.getTrivialTypeSourceInfo(T);
5240 
5241   return GetTypeSourceInfoForDeclarator(state, T, TInfo);
5242 }
5243 
5244 /// GetTypeForDeclarator - Convert the type for the specified
5245 /// declarator to Type instances.
5246 ///
5247 /// The result of this call will never be null, but the associated
5248 /// type may be a null type if there's an unrecoverable error.
5249 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
5250   // Determine the type of the declarator. Not all forms of declarator
5251   // have a type.
5252 
5253   TypeProcessingState state(*this, D);
5254 
5255   TypeSourceInfo *ReturnTypeInfo = nullptr;
5256   QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5257   if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
5258     inferARCWriteback(state, T);
5259 
5260   return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
5261 }
5262 
5263 static void transferARCOwnershipToDeclSpec(Sema &S,
5264                                            QualType &declSpecTy,
5265                                            Qualifiers::ObjCLifetime ownership) {
5266   if (declSpecTy->isObjCRetainableType() &&
5267       declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
5268     Qualifiers qs;
5269     qs.addObjCLifetime(ownership);
5270     declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
5271   }
5272 }
5273 
5274 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
5275                                             Qualifiers::ObjCLifetime ownership,
5276                                             unsigned chunkIndex) {
5277   Sema &S = state.getSema();
5278   Declarator &D = state.getDeclarator();
5279 
5280   // Look for an explicit lifetime attribute.
5281   DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
5282   if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership))
5283     return;
5284 
5285   const char *attrStr = nullptr;
5286   switch (ownership) {
5287   case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
5288   case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
5289   case Qualifiers::OCL_Strong: attrStr = "strong"; break;
5290   case Qualifiers::OCL_Weak: attrStr = "weak"; break;
5291   case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
5292   }
5293 
5294   IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
5295   Arg->Ident = &S.Context.Idents.get(attrStr);
5296   Arg->Loc = SourceLocation();
5297 
5298   ArgsUnion Args(Arg);
5299 
5300   // If there wasn't one, add one (with an invalid source location
5301   // so that we don't make an AttributedType for it).
5302   ParsedAttr *attr = D.getAttributePool().create(
5303       &S.Context.Idents.get("objc_ownership"), SourceLocation(),
5304       /*scope*/ nullptr, SourceLocation(),
5305       /*args*/ &Args, 1, ParsedAttr::AS_GNU);
5306   chunk.getAttrs().addAtEnd(attr);
5307   // TODO: mark whether we did this inference?
5308 }
5309 
5310 /// Used for transferring ownership in casts resulting in l-values.
5311 static void transferARCOwnership(TypeProcessingState &state,
5312                                  QualType &declSpecTy,
5313                                  Qualifiers::ObjCLifetime ownership) {
5314   Sema &S = state.getSema();
5315   Declarator &D = state.getDeclarator();
5316 
5317   int inner = -1;
5318   bool hasIndirection = false;
5319   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5320     DeclaratorChunk &chunk = D.getTypeObject(i);
5321     switch (chunk.Kind) {
5322     case DeclaratorChunk::Paren:
5323       // Ignore parens.
5324       break;
5325 
5326     case DeclaratorChunk::Array:
5327     case DeclaratorChunk::Reference:
5328     case DeclaratorChunk::Pointer:
5329       if (inner != -1)
5330         hasIndirection = true;
5331       inner = i;
5332       break;
5333 
5334     case DeclaratorChunk::BlockPointer:
5335       if (inner != -1)
5336         transferARCOwnershipToDeclaratorChunk(state, ownership, i);
5337       return;
5338 
5339     case DeclaratorChunk::Function:
5340     case DeclaratorChunk::MemberPointer:
5341     case DeclaratorChunk::Pipe:
5342       return;
5343     }
5344   }
5345 
5346   if (inner == -1)
5347     return;
5348 
5349   DeclaratorChunk &chunk = D.getTypeObject(inner);
5350   if (chunk.Kind == DeclaratorChunk::Pointer) {
5351     if (declSpecTy->isObjCRetainableType())
5352       return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5353     if (declSpecTy->isObjCObjectType() && hasIndirection)
5354       return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
5355   } else {
5356     assert(chunk.Kind == DeclaratorChunk::Array ||
5357            chunk.Kind == DeclaratorChunk::Reference);
5358     return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5359   }
5360 }
5361 
5362 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
5363   TypeProcessingState state(*this, D);
5364 
5365   TypeSourceInfo *ReturnTypeInfo = nullptr;
5366   QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5367 
5368   if (getLangOpts().ObjC) {
5369     Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
5370     if (ownership != Qualifiers::OCL_None)
5371       transferARCOwnership(state, declSpecTy, ownership);
5372   }
5373 
5374   return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
5375 }
5376 
5377 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
5378                                   TypeProcessingState &State) {
5379   TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr()));
5380 }
5381 
5382 namespace {
5383   class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
5384     ASTContext &Context;
5385     TypeProcessingState &State;
5386     const DeclSpec &DS;
5387 
5388   public:
5389     TypeSpecLocFiller(ASTContext &Context, TypeProcessingState &State,
5390                       const DeclSpec &DS)
5391         : Context(Context), State(State), DS(DS) {}
5392 
5393     void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5394       Visit(TL.getModifiedLoc());
5395       fillAttributedTypeLoc(TL, State);
5396     }
5397     void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
5398       Visit(TL.getInnerLoc());
5399       TL.setExpansionLoc(
5400           State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
5401     }
5402     void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5403       Visit(TL.getUnqualifiedLoc());
5404     }
5405     void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5406       TL.setNameLoc(DS.getTypeSpecTypeLoc());
5407     }
5408     void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5409       TL.setNameLoc(DS.getTypeSpecTypeLoc());
5410       // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
5411       // addition field. What we have is good enough for dispay of location
5412       // of 'fixit' on interface name.
5413       TL.setNameEndLoc(DS.getEndLoc());
5414     }
5415     void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5416       TypeSourceInfo *RepTInfo = nullptr;
5417       Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5418       TL.copy(RepTInfo->getTypeLoc());
5419     }
5420     void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5421       TypeSourceInfo *RepTInfo = nullptr;
5422       Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5423       TL.copy(RepTInfo->getTypeLoc());
5424     }
5425     void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
5426       TypeSourceInfo *TInfo = nullptr;
5427       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5428 
5429       // If we got no declarator info from previous Sema routines,
5430       // just fill with the typespec loc.
5431       if (!TInfo) {
5432         TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
5433         return;
5434       }
5435 
5436       TypeLoc OldTL = TInfo->getTypeLoc();
5437       if (TInfo->getType()->getAs<ElaboratedType>()) {
5438         ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
5439         TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
5440             .castAs<TemplateSpecializationTypeLoc>();
5441         TL.copy(NamedTL);
5442       } else {
5443         TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
5444         assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
5445       }
5446 
5447     }
5448     void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5449       assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
5450       TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5451       TL.setParensRange(DS.getTypeofParensRange());
5452     }
5453     void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5454       assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
5455       TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5456       TL.setParensRange(DS.getTypeofParensRange());
5457       assert(DS.getRepAsType());
5458       TypeSourceInfo *TInfo = nullptr;
5459       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5460       TL.setUnderlyingTInfo(TInfo);
5461     }
5462     void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5463       // FIXME: This holds only because we only have one unary transform.
5464       assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
5465       TL.setKWLoc(DS.getTypeSpecTypeLoc());
5466       TL.setParensRange(DS.getTypeofParensRange());
5467       assert(DS.getRepAsType());
5468       TypeSourceInfo *TInfo = nullptr;
5469       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5470       TL.setUnderlyingTInfo(TInfo);
5471     }
5472     void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5473       // By default, use the source location of the type specifier.
5474       TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
5475       if (TL.needsExtraLocalData()) {
5476         // Set info for the written builtin specifiers.
5477         TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
5478         // Try to have a meaningful source location.
5479         if (TL.getWrittenSignSpec() != TSS_unspecified)
5480           TL.expandBuiltinRange(DS.getTypeSpecSignLoc());
5481         if (TL.getWrittenWidthSpec() != TSW_unspecified)
5482           TL.expandBuiltinRange(DS.getTypeSpecWidthRange());
5483       }
5484     }
5485     void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5486       ElaboratedTypeKeyword Keyword
5487         = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
5488       if (DS.getTypeSpecType() == TST_typename) {
5489         TypeSourceInfo *TInfo = nullptr;
5490         Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5491         if (TInfo) {
5492           TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
5493           return;
5494         }
5495       }
5496       TL.setElaboratedKeywordLoc(Keyword != ETK_None
5497                                  ? DS.getTypeSpecTypeLoc()
5498                                  : SourceLocation());
5499       const CXXScopeSpec& SS = DS.getTypeSpecScope();
5500       TL.setQualifierLoc(SS.getWithLocInContext(Context));
5501       Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
5502     }
5503     void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5504       assert(DS.getTypeSpecType() == TST_typename);
5505       TypeSourceInfo *TInfo = nullptr;
5506       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5507       assert(TInfo);
5508       TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
5509     }
5510     void VisitDependentTemplateSpecializationTypeLoc(
5511                                  DependentTemplateSpecializationTypeLoc TL) {
5512       assert(DS.getTypeSpecType() == TST_typename);
5513       TypeSourceInfo *TInfo = nullptr;
5514       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5515       assert(TInfo);
5516       TL.copy(
5517           TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
5518     }
5519     void VisitTagTypeLoc(TagTypeLoc TL) {
5520       TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
5521     }
5522     void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5523       // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
5524       // or an _Atomic qualifier.
5525       if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
5526         TL.setKWLoc(DS.getTypeSpecTypeLoc());
5527         TL.setParensRange(DS.getTypeofParensRange());
5528 
5529         TypeSourceInfo *TInfo = nullptr;
5530         Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5531         assert(TInfo);
5532         TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
5533       } else {
5534         TL.setKWLoc(DS.getAtomicSpecLoc());
5535         // No parens, to indicate this was spelled as an _Atomic qualifier.
5536         TL.setParensRange(SourceRange());
5537         Visit(TL.getValueLoc());
5538       }
5539     }
5540 
5541     void VisitPipeTypeLoc(PipeTypeLoc TL) {
5542       TL.setKWLoc(DS.getTypeSpecTypeLoc());
5543 
5544       TypeSourceInfo *TInfo = nullptr;
5545       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5546       TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
5547     }
5548 
5549     void VisitTypeLoc(TypeLoc TL) {
5550       // FIXME: add other typespec types and change this to an assert.
5551       TL.initialize(Context, DS.getTypeSpecTypeLoc());
5552     }
5553   };
5554 
5555   class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
5556     ASTContext &Context;
5557     TypeProcessingState &State;
5558     const DeclaratorChunk &Chunk;
5559 
5560   public:
5561     DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State,
5562                         const DeclaratorChunk &Chunk)
5563         : Context(Context), State(State), Chunk(Chunk) {}
5564 
5565     void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5566       llvm_unreachable("qualified type locs not expected here!");
5567     }
5568     void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5569       llvm_unreachable("decayed type locs not expected here!");
5570     }
5571 
5572     void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5573       fillAttributedTypeLoc(TL, State);
5574     }
5575     void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5576       // nothing
5577     }
5578     void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5579       assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
5580       TL.setCaretLoc(Chunk.Loc);
5581     }
5582     void VisitPointerTypeLoc(PointerTypeLoc TL) {
5583       assert(Chunk.Kind == DeclaratorChunk::Pointer);
5584       TL.setStarLoc(Chunk.Loc);
5585     }
5586     void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5587       assert(Chunk.Kind == DeclaratorChunk::Pointer);
5588       TL.setStarLoc(Chunk.Loc);
5589     }
5590     void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5591       assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
5592       const CXXScopeSpec& SS = Chunk.Mem.Scope();
5593       NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
5594 
5595       const Type* ClsTy = TL.getClass();
5596       QualType ClsQT = QualType(ClsTy, 0);
5597       TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
5598       // Now copy source location info into the type loc component.
5599       TypeLoc ClsTL = ClsTInfo->getTypeLoc();
5600       switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
5601       case NestedNameSpecifier::Identifier:
5602         assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
5603         {
5604           DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
5605           DNTLoc.setElaboratedKeywordLoc(SourceLocation());
5606           DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
5607           DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
5608         }
5609         break;
5610 
5611       case NestedNameSpecifier::TypeSpec:
5612       case NestedNameSpecifier::TypeSpecWithTemplate:
5613         if (isa<ElaboratedType>(ClsTy)) {
5614           ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
5615           ETLoc.setElaboratedKeywordLoc(SourceLocation());
5616           ETLoc.setQualifierLoc(NNSLoc.getPrefix());
5617           TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
5618           NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
5619         } else {
5620           ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
5621         }
5622         break;
5623 
5624       case NestedNameSpecifier::Namespace:
5625       case NestedNameSpecifier::NamespaceAlias:
5626       case NestedNameSpecifier::Global:
5627       case NestedNameSpecifier::Super:
5628         llvm_unreachable("Nested-name-specifier must name a type");
5629       }
5630 
5631       // Finally fill in MemberPointerLocInfo fields.
5632       TL.setStarLoc(Chunk.Loc);
5633       TL.setClassTInfo(ClsTInfo);
5634     }
5635     void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5636       assert(Chunk.Kind == DeclaratorChunk::Reference);
5637       // 'Amp' is misleading: this might have been originally
5638       /// spelled with AmpAmp.
5639       TL.setAmpLoc(Chunk.Loc);
5640     }
5641     void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5642       assert(Chunk.Kind == DeclaratorChunk::Reference);
5643       assert(!Chunk.Ref.LValueRef);
5644       TL.setAmpAmpLoc(Chunk.Loc);
5645     }
5646     void VisitArrayTypeLoc(ArrayTypeLoc TL) {
5647       assert(Chunk.Kind == DeclaratorChunk::Array);
5648       TL.setLBracketLoc(Chunk.Loc);
5649       TL.setRBracketLoc(Chunk.EndLoc);
5650       TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
5651     }
5652     void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5653       assert(Chunk.Kind == DeclaratorChunk::Function);
5654       TL.setLocalRangeBegin(Chunk.Loc);
5655       TL.setLocalRangeEnd(Chunk.EndLoc);
5656 
5657       const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
5658       TL.setLParenLoc(FTI.getLParenLoc());
5659       TL.setRParenLoc(FTI.getRParenLoc());
5660       for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
5661         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5662         TL.setParam(tpi++, Param);
5663       }
5664       TL.setExceptionSpecRange(FTI.getExceptionSpecRange());
5665     }
5666     void VisitParenTypeLoc(ParenTypeLoc TL) {
5667       assert(Chunk.Kind == DeclaratorChunk::Paren);
5668       TL.setLParenLoc(Chunk.Loc);
5669       TL.setRParenLoc(Chunk.EndLoc);
5670     }
5671     void VisitPipeTypeLoc(PipeTypeLoc TL) {
5672       assert(Chunk.Kind == DeclaratorChunk::Pipe);
5673       TL.setKWLoc(Chunk.Loc);
5674     }
5675     void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
5676       TL.setExpansionLoc(Chunk.Loc);
5677     }
5678 
5679     void VisitTypeLoc(TypeLoc TL) {
5680       llvm_unreachable("unsupported TypeLoc kind in declarator!");
5681     }
5682   };
5683 } // end anonymous namespace
5684 
5685 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
5686   SourceLocation Loc;
5687   switch (Chunk.Kind) {
5688   case DeclaratorChunk::Function:
5689   case DeclaratorChunk::Array:
5690   case DeclaratorChunk::Paren:
5691   case DeclaratorChunk::Pipe:
5692     llvm_unreachable("cannot be _Atomic qualified");
5693 
5694   case DeclaratorChunk::Pointer:
5695     Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
5696     break;
5697 
5698   case DeclaratorChunk::BlockPointer:
5699   case DeclaratorChunk::Reference:
5700   case DeclaratorChunk::MemberPointer:
5701     // FIXME: Provide a source location for the _Atomic keyword.
5702     break;
5703   }
5704 
5705   ATL.setKWLoc(Loc);
5706   ATL.setParensRange(SourceRange());
5707 }
5708 
5709 static void
5710 fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL,
5711                                  const ParsedAttributesView &Attrs) {
5712   for (const ParsedAttr &AL : Attrs) {
5713     if (AL.getKind() == ParsedAttr::AT_AddressSpace) {
5714       DASTL.setAttrNameLoc(AL.getLoc());
5715       DASTL.setAttrExprOperand(AL.getArgAsExpr(0));
5716       DASTL.setAttrOperandParensRange(SourceRange());
5717       return;
5718     }
5719   }
5720 
5721   llvm_unreachable(
5722       "no address_space attribute found at the expected location!");
5723 }
5724 
5725 /// Create and instantiate a TypeSourceInfo with type source information.
5726 ///
5727 /// \param T QualType referring to the type as written in source code.
5728 ///
5729 /// \param ReturnTypeInfo For declarators whose return type does not show
5730 /// up in the normal place in the declaration specifiers (such as a C++
5731 /// conversion function), this pointer will refer to a type source information
5732 /// for that return type.
5733 static TypeSourceInfo *
5734 GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
5735                                QualType T, TypeSourceInfo *ReturnTypeInfo) {
5736   Sema &S = State.getSema();
5737   Declarator &D = State.getDeclarator();
5738 
5739   TypeSourceInfo *TInfo = S.Context.CreateTypeSourceInfo(T);
5740   UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
5741 
5742   // Handle parameter packs whose type is a pack expansion.
5743   if (isa<PackExpansionType>(T)) {
5744     CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
5745     CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
5746   }
5747 
5748   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5749     // An AtomicTypeLoc might be produced by an atomic qualifier in this
5750     // declarator chunk.
5751     if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
5752       fillAtomicQualLoc(ATL, D.getTypeObject(i));
5753       CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
5754     }
5755 
5756     while (MacroQualifiedTypeLoc TL = CurrTL.getAs<MacroQualifiedTypeLoc>()) {
5757       TL.setExpansionLoc(
5758           State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
5759       CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
5760     }
5761 
5762     while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
5763       fillAttributedTypeLoc(TL, State);
5764       CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
5765     }
5766 
5767     while (DependentAddressSpaceTypeLoc TL =
5768                CurrTL.getAs<DependentAddressSpaceTypeLoc>()) {
5769       fillDependentAddressSpaceTypeLoc(TL, D.getTypeObject(i).getAttrs());
5770       CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc();
5771     }
5772 
5773     // FIXME: Ordering here?
5774     while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
5775       CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
5776 
5777     DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL);
5778     CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
5779   }
5780 
5781   // If we have different source information for the return type, use
5782   // that.  This really only applies to C++ conversion functions.
5783   if (ReturnTypeInfo) {
5784     TypeLoc TL = ReturnTypeInfo->getTypeLoc();
5785     assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
5786     memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
5787   } else {
5788     TypeSpecLocFiller(S.Context, State, D.getDeclSpec()).Visit(CurrTL);
5789   }
5790 
5791   return TInfo;
5792 }
5793 
5794 /// Create a LocInfoType to hold the given QualType and TypeSourceInfo.
5795 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
5796   // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
5797   // and Sema during declaration parsing. Try deallocating/caching them when
5798   // it's appropriate, instead of allocating them and keeping them around.
5799   LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
5800                                                        TypeAlignment);
5801   new (LocT) LocInfoType(T, TInfo);
5802   assert(LocT->getTypeClass() != T->getTypeClass() &&
5803          "LocInfoType's TypeClass conflicts with an existing Type class");
5804   return ParsedType::make(QualType(LocT, 0));
5805 }
5806 
5807 void LocInfoType::getAsStringInternal(std::string &Str,
5808                                       const PrintingPolicy &Policy) const {
5809   llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
5810          " was used directly instead of getting the QualType through"
5811          " GetTypeFromParser");
5812 }
5813 
5814 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
5815   // C99 6.7.6: Type names have no identifier.  This is already validated by
5816   // the parser.
5817   assert(D.getIdentifier() == nullptr &&
5818          "Type name should have no identifier!");
5819 
5820   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5821   QualType T = TInfo->getType();
5822   if (D.isInvalidType())
5823     return true;
5824 
5825   // Make sure there are no unused decl attributes on the declarator.
5826   // We don't want to do this for ObjC parameters because we're going
5827   // to apply them to the actual parameter declaration.
5828   // Likewise, we don't want to do this for alias declarations, because
5829   // we are actually going to build a declaration from this eventually.
5830   if (D.getContext() != DeclaratorContext::ObjCParameterContext &&
5831       D.getContext() != DeclaratorContext::AliasDeclContext &&
5832       D.getContext() != DeclaratorContext::AliasTemplateContext)
5833     checkUnusedDeclAttributes(D);
5834 
5835   if (getLangOpts().CPlusPlus) {
5836     // Check that there are no default arguments (C++ only).
5837     CheckExtraCXXDefaultArguments(D);
5838   }
5839 
5840   return CreateParsedType(T, TInfo);
5841 }
5842 
5843 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
5844   QualType T = Context.getObjCInstanceType();
5845   TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
5846   return CreateParsedType(T, TInfo);
5847 }
5848 
5849 //===----------------------------------------------------------------------===//
5850 // Type Attribute Processing
5851 //===----------------------------------------------------------------------===//
5852 
5853 /// Build an AddressSpace index from a constant expression and diagnose any
5854 /// errors related to invalid address_spaces. Returns true on successfully
5855 /// building an AddressSpace index.
5856 static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx,
5857                                    const Expr *AddrSpace,
5858                                    SourceLocation AttrLoc) {
5859   if (!AddrSpace->isValueDependent()) {
5860     llvm::APSInt addrSpace(32);
5861     if (!AddrSpace->isIntegerConstantExpr(addrSpace, S.Context)) {
5862       S.Diag(AttrLoc, diag::err_attribute_argument_type)
5863           << "'address_space'" << AANT_ArgumentIntegerConstant
5864           << AddrSpace->getSourceRange();
5865       return false;
5866     }
5867 
5868     // Bounds checking.
5869     if (addrSpace.isSigned()) {
5870       if (addrSpace.isNegative()) {
5871         S.Diag(AttrLoc, diag::err_attribute_address_space_negative)
5872             << AddrSpace->getSourceRange();
5873         return false;
5874       }
5875       addrSpace.setIsSigned(false);
5876     }
5877 
5878     llvm::APSInt max(addrSpace.getBitWidth());
5879     max =
5880         Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace;
5881     if (addrSpace > max) {
5882       S.Diag(AttrLoc, diag::err_attribute_address_space_too_high)
5883           << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange();
5884       return false;
5885     }
5886 
5887     ASIdx =
5888         getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue()));
5889     return true;
5890   }
5891 
5892   // Default value for DependentAddressSpaceTypes
5893   ASIdx = LangAS::Default;
5894   return true;
5895 }
5896 
5897 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression
5898 /// is uninstantiated. If instantiated it will apply the appropriate address
5899 /// space to the type. This function allows dependent template variables to be
5900 /// used in conjunction with the address_space attribute
5901 QualType Sema::BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
5902                                      SourceLocation AttrLoc) {
5903   if (!AddrSpace->isValueDependent()) {
5904     if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx,
5905                                             AttrLoc))
5906       return QualType();
5907 
5908     return Context.getAddrSpaceQualType(T, ASIdx);
5909   }
5910 
5911   // A check with similar intentions as checking if a type already has an
5912   // address space except for on a dependent types, basically if the
5913   // current type is already a DependentAddressSpaceType then its already
5914   // lined up to have another address space on it and we can't have
5915   // multiple address spaces on the one pointer indirection
5916   if (T->getAs<DependentAddressSpaceType>()) {
5917     Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
5918     return QualType();
5919   }
5920 
5921   return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc);
5922 }
5923 
5924 QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
5925                                      SourceLocation AttrLoc) {
5926   LangAS ASIdx;
5927   if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc))
5928     return QualType();
5929   return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc);
5930 }
5931 
5932 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
5933 /// specified type.  The attribute contains 1 argument, the id of the address
5934 /// space for the type.
5935 static void HandleAddressSpaceTypeAttribute(QualType &Type,
5936                                             const ParsedAttr &Attr,
5937                                             TypeProcessingState &State) {
5938   Sema &S = State.getSema();
5939 
5940   // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
5941   // qualified by an address-space qualifier."
5942   if (Type->isFunctionType()) {
5943     S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
5944     Attr.setInvalid();
5945     return;
5946   }
5947 
5948   LangAS ASIdx;
5949   if (Attr.getKind() == ParsedAttr::AT_AddressSpace) {
5950 
5951     // Check the attribute arguments.
5952     if (Attr.getNumArgs() != 1) {
5953       S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
5954                                                                         << 1;
5955       Attr.setInvalid();
5956       return;
5957     }
5958 
5959     Expr *ASArgExpr;
5960     if (Attr.isArgIdent(0)) {
5961       // Special case where the argument is a template id.
5962       CXXScopeSpec SS;
5963       SourceLocation TemplateKWLoc;
5964       UnqualifiedId id;
5965       id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
5966 
5967       ExprResult AddrSpace = S.ActOnIdExpression(
5968           S.getCurScope(), SS, TemplateKWLoc, id, /*HasTrailingLParen=*/false,
5969           /*IsAddressOfOperand=*/false);
5970       if (AddrSpace.isInvalid())
5971         return;
5972 
5973       ASArgExpr = static_cast<Expr *>(AddrSpace.get());
5974     } else {
5975       ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5976     }
5977 
5978     LangAS ASIdx;
5979     if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) {
5980       Attr.setInvalid();
5981       return;
5982     }
5983 
5984     ASTContext &Ctx = S.Context;
5985     auto *ASAttr =
5986         ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx));
5987 
5988     // If the expression is not value dependent (not templated), then we can
5989     // apply the address space qualifiers just to the equivalent type.
5990     // Otherwise, we make an AttributedType with the modified and equivalent
5991     // type the same, and wrap it in a DependentAddressSpaceType. When this
5992     // dependent type is resolved, the qualifier is added to the equivalent type
5993     // later.
5994     QualType T;
5995     if (!ASArgExpr->isValueDependent()) {
5996       QualType EquivType =
5997           S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc());
5998       if (EquivType.isNull()) {
5999         Attr.setInvalid();
6000         return;
6001       }
6002       T = State.getAttributedType(ASAttr, Type, EquivType);
6003     } else {
6004       T = State.getAttributedType(ASAttr, Type, Type);
6005       T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc());
6006     }
6007 
6008     if (!T.isNull())
6009       Type = T;
6010     else
6011       Attr.setInvalid();
6012   } else {
6013     // The keyword-based type attributes imply which address space to use.
6014     ASIdx = Attr.asOpenCLLangAS();
6015     if (ASIdx == LangAS::Default)
6016       llvm_unreachable("Invalid address space");
6017 
6018     if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx,
6019                                             Attr.getLoc())) {
6020       Attr.setInvalid();
6021       return;
6022     }
6023 
6024     Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
6025   }
6026 }
6027 
6028 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
6029 /// attribute on the specified type.
6030 ///
6031 /// Returns 'true' if the attribute was handled.
6032 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
6033                                         ParsedAttr &attr, QualType &type) {
6034   bool NonObjCPointer = false;
6035 
6036   if (!type->isDependentType() && !type->isUndeducedType()) {
6037     if (const PointerType *ptr = type->getAs<PointerType>()) {
6038       QualType pointee = ptr->getPointeeType();
6039       if (pointee->isObjCRetainableType() || pointee->isPointerType())
6040         return false;
6041       // It is important not to lose the source info that there was an attribute
6042       // applied to non-objc pointer. We will create an attributed type but
6043       // its type will be the same as the original type.
6044       NonObjCPointer = true;
6045     } else if (!type->isObjCRetainableType()) {
6046       return false;
6047     }
6048 
6049     // Don't accept an ownership attribute in the declspec if it would
6050     // just be the return type of a block pointer.
6051     if (state.isProcessingDeclSpec()) {
6052       Declarator &D = state.getDeclarator();
6053       if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
6054                                   /*onlyBlockPointers=*/true))
6055         return false;
6056     }
6057   }
6058 
6059   Sema &S = state.getSema();
6060   SourceLocation AttrLoc = attr.getLoc();
6061   if (AttrLoc.isMacroID())
6062     AttrLoc =
6063         S.getSourceManager().getImmediateExpansionRange(AttrLoc).getBegin();
6064 
6065   if (!attr.isArgIdent(0)) {
6066     S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr
6067                                                        << AANT_ArgumentString;
6068     attr.setInvalid();
6069     return true;
6070   }
6071 
6072   IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
6073   Qualifiers::ObjCLifetime lifetime;
6074   if (II->isStr("none"))
6075     lifetime = Qualifiers::OCL_ExplicitNone;
6076   else if (II->isStr("strong"))
6077     lifetime = Qualifiers::OCL_Strong;
6078   else if (II->isStr("weak"))
6079     lifetime = Qualifiers::OCL_Weak;
6080   else if (II->isStr("autoreleasing"))
6081     lifetime = Qualifiers::OCL_Autoreleasing;
6082   else {
6083     S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II;
6084     attr.setInvalid();
6085     return true;
6086   }
6087 
6088   // Just ignore lifetime attributes other than __weak and __unsafe_unretained
6089   // outside of ARC mode.
6090   if (!S.getLangOpts().ObjCAutoRefCount &&
6091       lifetime != Qualifiers::OCL_Weak &&
6092       lifetime != Qualifiers::OCL_ExplicitNone) {
6093     return true;
6094   }
6095 
6096   SplitQualType underlyingType = type.split();
6097 
6098   // Check for redundant/conflicting ownership qualifiers.
6099   if (Qualifiers::ObjCLifetime previousLifetime
6100         = type.getQualifiers().getObjCLifetime()) {
6101     // If it's written directly, that's an error.
6102     if (S.Context.hasDirectOwnershipQualifier(type)) {
6103       S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
6104         << type;
6105       return true;
6106     }
6107 
6108     // Otherwise, if the qualifiers actually conflict, pull sugar off
6109     // and remove the ObjCLifetime qualifiers.
6110     if (previousLifetime != lifetime) {
6111       // It's possible to have multiple local ObjCLifetime qualifiers. We
6112       // can't stop after we reach a type that is directly qualified.
6113       const Type *prevTy = nullptr;
6114       while (!prevTy || prevTy != underlyingType.Ty) {
6115         prevTy = underlyingType.Ty;
6116         underlyingType = underlyingType.getSingleStepDesugaredType();
6117       }
6118       underlyingType.Quals.removeObjCLifetime();
6119     }
6120   }
6121 
6122   underlyingType.Quals.addObjCLifetime(lifetime);
6123 
6124   if (NonObjCPointer) {
6125     StringRef name = attr.getAttrName()->getName();
6126     switch (lifetime) {
6127     case Qualifiers::OCL_None:
6128     case Qualifiers::OCL_ExplicitNone:
6129       break;
6130     case Qualifiers::OCL_Strong: name = "__strong"; break;
6131     case Qualifiers::OCL_Weak: name = "__weak"; break;
6132     case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
6133     }
6134     S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
6135       << TDS_ObjCObjOrBlock << type;
6136   }
6137 
6138   // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
6139   // because having both 'T' and '__unsafe_unretained T' exist in the type
6140   // system causes unfortunate widespread consistency problems.  (For example,
6141   // they're not considered compatible types, and we mangle them identicially
6142   // as template arguments.)  These problems are all individually fixable,
6143   // but it's easier to just not add the qualifier and instead sniff it out
6144   // in specific places using isObjCInertUnsafeUnretainedType().
6145   //
6146   // Doing this does means we miss some trivial consistency checks that
6147   // would've triggered in ARC, but that's better than trying to solve all
6148   // the coexistence problems with __unsafe_unretained.
6149   if (!S.getLangOpts().ObjCAutoRefCount &&
6150       lifetime == Qualifiers::OCL_ExplicitNone) {
6151     type = state.getAttributedType(
6152         createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(S.Context, attr),
6153         type, type);
6154     return true;
6155   }
6156 
6157   QualType origType = type;
6158   if (!NonObjCPointer)
6159     type = S.Context.getQualifiedType(underlyingType);
6160 
6161   // If we have a valid source location for the attribute, use an
6162   // AttributedType instead.
6163   if (AttrLoc.isValid()) {
6164     type = state.getAttributedType(::new (S.Context)
6165                                        ObjCOwnershipAttr(S.Context, attr, II),
6166                                    origType, type);
6167   }
6168 
6169   auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
6170                             unsigned diagnostic, QualType type) {
6171     if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
6172       S.DelayedDiagnostics.add(
6173           sema::DelayedDiagnostic::makeForbiddenType(
6174               S.getSourceManager().getExpansionLoc(loc),
6175               diagnostic, type, /*ignored*/ 0));
6176     } else {
6177       S.Diag(loc, diagnostic);
6178     }
6179   };
6180 
6181   // Sometimes, __weak isn't allowed.
6182   if (lifetime == Qualifiers::OCL_Weak &&
6183       !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
6184 
6185     // Use a specialized diagnostic if the runtime just doesn't support them.
6186     unsigned diagnostic =
6187       (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
6188                                        : diag::err_arc_weak_no_runtime);
6189 
6190     // In any case, delay the diagnostic until we know what we're parsing.
6191     diagnoseOrDelay(S, AttrLoc, diagnostic, type);
6192 
6193     attr.setInvalid();
6194     return true;
6195   }
6196 
6197   // Forbid __weak for class objects marked as
6198   // objc_arc_weak_reference_unavailable
6199   if (lifetime == Qualifiers::OCL_Weak) {
6200     if (const ObjCObjectPointerType *ObjT =
6201           type->getAs<ObjCObjectPointerType>()) {
6202       if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
6203         if (Class->isArcWeakrefUnavailable()) {
6204           S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
6205           S.Diag(ObjT->getInterfaceDecl()->getLocation(),
6206                  diag::note_class_declared);
6207         }
6208       }
6209     }
6210   }
6211 
6212   return true;
6213 }
6214 
6215 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
6216 /// attribute on the specified type.  Returns true to indicate that
6217 /// the attribute was handled, false to indicate that the type does
6218 /// not permit the attribute.
6219 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
6220                                  QualType &type) {
6221   Sema &S = state.getSema();
6222 
6223   // Delay if this isn't some kind of pointer.
6224   if (!type->isPointerType() &&
6225       !type->isObjCObjectPointerType() &&
6226       !type->isBlockPointerType())
6227     return false;
6228 
6229   if (type.getObjCGCAttr() != Qualifiers::GCNone) {
6230     S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
6231     attr.setInvalid();
6232     return true;
6233   }
6234 
6235   // Check the attribute arguments.
6236   if (!attr.isArgIdent(0)) {
6237     S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
6238         << attr << AANT_ArgumentString;
6239     attr.setInvalid();
6240     return true;
6241   }
6242   Qualifiers::GC GCAttr;
6243   if (attr.getNumArgs() > 1) {
6244     S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr
6245                                                                       << 1;
6246     attr.setInvalid();
6247     return true;
6248   }
6249 
6250   IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
6251   if (II->isStr("weak"))
6252     GCAttr = Qualifiers::Weak;
6253   else if (II->isStr("strong"))
6254     GCAttr = Qualifiers::Strong;
6255   else {
6256     S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
6257         << attr << II;
6258     attr.setInvalid();
6259     return true;
6260   }
6261 
6262   QualType origType = type;
6263   type = S.Context.getObjCGCQualType(origType, GCAttr);
6264 
6265   // Make an attributed type to preserve the source information.
6266   if (attr.getLoc().isValid())
6267     type = state.getAttributedType(
6268         ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type);
6269 
6270   return true;
6271 }
6272 
6273 namespace {
6274   /// A helper class to unwrap a type down to a function for the
6275   /// purposes of applying attributes there.
6276   ///
6277   /// Use:
6278   ///   FunctionTypeUnwrapper unwrapped(SemaRef, T);
6279   ///   if (unwrapped.isFunctionType()) {
6280   ///     const FunctionType *fn = unwrapped.get();
6281   ///     // change fn somehow
6282   ///     T = unwrapped.wrap(fn);
6283   ///   }
6284   struct FunctionTypeUnwrapper {
6285     enum WrapKind {
6286       Desugar,
6287       Attributed,
6288       Parens,
6289       Pointer,
6290       BlockPointer,
6291       Reference,
6292       MemberPointer
6293     };
6294 
6295     QualType Original;
6296     const FunctionType *Fn;
6297     SmallVector<unsigned char /*WrapKind*/, 8> Stack;
6298 
6299     FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
6300       while (true) {
6301         const Type *Ty = T.getTypePtr();
6302         if (isa<FunctionType>(Ty)) {
6303           Fn = cast<FunctionType>(Ty);
6304           return;
6305         } else if (isa<ParenType>(Ty)) {
6306           T = cast<ParenType>(Ty)->getInnerType();
6307           Stack.push_back(Parens);
6308         } else if (isa<PointerType>(Ty)) {
6309           T = cast<PointerType>(Ty)->getPointeeType();
6310           Stack.push_back(Pointer);
6311         } else if (isa<BlockPointerType>(Ty)) {
6312           T = cast<BlockPointerType>(Ty)->getPointeeType();
6313           Stack.push_back(BlockPointer);
6314         } else if (isa<MemberPointerType>(Ty)) {
6315           T = cast<MemberPointerType>(Ty)->getPointeeType();
6316           Stack.push_back(MemberPointer);
6317         } else if (isa<ReferenceType>(Ty)) {
6318           T = cast<ReferenceType>(Ty)->getPointeeType();
6319           Stack.push_back(Reference);
6320         } else if (isa<AttributedType>(Ty)) {
6321           T = cast<AttributedType>(Ty)->getEquivalentType();
6322           Stack.push_back(Attributed);
6323         } else {
6324           const Type *DTy = Ty->getUnqualifiedDesugaredType();
6325           if (Ty == DTy) {
6326             Fn = nullptr;
6327             return;
6328           }
6329 
6330           T = QualType(DTy, 0);
6331           Stack.push_back(Desugar);
6332         }
6333       }
6334     }
6335 
6336     bool isFunctionType() const { return (Fn != nullptr); }
6337     const FunctionType *get() const { return Fn; }
6338 
6339     QualType wrap(Sema &S, const FunctionType *New) {
6340       // If T wasn't modified from the unwrapped type, do nothing.
6341       if (New == get()) return Original;
6342 
6343       Fn = New;
6344       return wrap(S.Context, Original, 0);
6345     }
6346 
6347   private:
6348     QualType wrap(ASTContext &C, QualType Old, unsigned I) {
6349       if (I == Stack.size())
6350         return C.getQualifiedType(Fn, Old.getQualifiers());
6351 
6352       // Build up the inner type, applying the qualifiers from the old
6353       // type to the new type.
6354       SplitQualType SplitOld = Old.split();
6355 
6356       // As a special case, tail-recurse if there are no qualifiers.
6357       if (SplitOld.Quals.empty())
6358         return wrap(C, SplitOld.Ty, I);
6359       return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
6360     }
6361 
6362     QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
6363       if (I == Stack.size()) return QualType(Fn, 0);
6364 
6365       switch (static_cast<WrapKind>(Stack[I++])) {
6366       case Desugar:
6367         // This is the point at which we potentially lose source
6368         // information.
6369         return wrap(C, Old->getUnqualifiedDesugaredType(), I);
6370 
6371       case Attributed:
6372         return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
6373 
6374       case Parens: {
6375         QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
6376         return C.getParenType(New);
6377       }
6378 
6379       case Pointer: {
6380         QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
6381         return C.getPointerType(New);
6382       }
6383 
6384       case BlockPointer: {
6385         QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
6386         return C.getBlockPointerType(New);
6387       }
6388 
6389       case MemberPointer: {
6390         const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
6391         QualType New = wrap(C, OldMPT->getPointeeType(), I);
6392         return C.getMemberPointerType(New, OldMPT->getClass());
6393       }
6394 
6395       case Reference: {
6396         const ReferenceType *OldRef = cast<ReferenceType>(Old);
6397         QualType New = wrap(C, OldRef->getPointeeType(), I);
6398         if (isa<LValueReferenceType>(OldRef))
6399           return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
6400         else
6401           return C.getRValueReferenceType(New);
6402       }
6403       }
6404 
6405       llvm_unreachable("unknown wrapping kind");
6406     }
6407   };
6408 } // end anonymous namespace
6409 
6410 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
6411                                              ParsedAttr &PAttr, QualType &Type) {
6412   Sema &S = State.getSema();
6413 
6414   Attr *A;
6415   switch (PAttr.getKind()) {
6416   default: llvm_unreachable("Unknown attribute kind");
6417   case ParsedAttr::AT_Ptr32:
6418     A = createSimpleAttr<Ptr32Attr>(S.Context, PAttr);
6419     break;
6420   case ParsedAttr::AT_Ptr64:
6421     A = createSimpleAttr<Ptr64Attr>(S.Context, PAttr);
6422     break;
6423   case ParsedAttr::AT_SPtr:
6424     A = createSimpleAttr<SPtrAttr>(S.Context, PAttr);
6425     break;
6426   case ParsedAttr::AT_UPtr:
6427     A = createSimpleAttr<UPtrAttr>(S.Context, PAttr);
6428     break;
6429   }
6430 
6431   attr::Kind NewAttrKind = A->getKind();
6432   QualType Desugared = Type;
6433   const AttributedType *AT = dyn_cast<AttributedType>(Type);
6434   while (AT) {
6435     attr::Kind CurAttrKind = AT->getAttrKind();
6436 
6437     // You cannot specify duplicate type attributes, so if the attribute has
6438     // already been applied, flag it.
6439     if (NewAttrKind == CurAttrKind) {
6440       S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
6441       return true;
6442     }
6443 
6444     // You cannot have both __sptr and __uptr on the same type, nor can you
6445     // have __ptr32 and __ptr64.
6446     if ((CurAttrKind == attr::Ptr32 && NewAttrKind == attr::Ptr64) ||
6447         (CurAttrKind == attr::Ptr64 && NewAttrKind == attr::Ptr32)) {
6448       S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
6449         << "'__ptr32'" << "'__ptr64'";
6450       return true;
6451     } else if ((CurAttrKind == attr::SPtr && NewAttrKind == attr::UPtr) ||
6452                (CurAttrKind == attr::UPtr && NewAttrKind == attr::SPtr)) {
6453       S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
6454         << "'__sptr'" << "'__uptr'";
6455       return true;
6456     }
6457 
6458     Desugared = AT->getEquivalentType();
6459     AT = dyn_cast<AttributedType>(Desugared);
6460   }
6461 
6462   // Pointer type qualifiers can only operate on pointer types, but not
6463   // pointer-to-member types.
6464   //
6465   // FIXME: Should we really be disallowing this attribute if there is any
6466   // type sugar between it and the pointer (other than attributes)? Eg, this
6467   // disallows the attribute on a parenthesized pointer.
6468   // And if so, should we really allow *any* type attribute?
6469   if (!isa<PointerType>(Desugared)) {
6470     if (Type->isMemberPointerType())
6471       S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr;
6472     else
6473       S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0;
6474     return true;
6475   }
6476 
6477   Type = State.getAttributedType(A, Type, Type);
6478   return false;
6479 }
6480 
6481 /// Map a nullability attribute kind to a nullability kind.
6482 static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind) {
6483   switch (kind) {
6484   case ParsedAttr::AT_TypeNonNull:
6485     return NullabilityKind::NonNull;
6486 
6487   case ParsedAttr::AT_TypeNullable:
6488     return NullabilityKind::Nullable;
6489 
6490   case ParsedAttr::AT_TypeNullUnspecified:
6491     return NullabilityKind::Unspecified;
6492 
6493   default:
6494     llvm_unreachable("not a nullability attribute kind");
6495   }
6496 }
6497 
6498 /// Applies a nullability type specifier to the given type, if possible.
6499 ///
6500 /// \param state The type processing state.
6501 ///
6502 /// \param type The type to which the nullability specifier will be
6503 /// added. On success, this type will be updated appropriately.
6504 ///
6505 /// \param attr The attribute as written on the type.
6506 ///
6507 /// \param allowOnArrayType Whether to accept nullability specifiers on an
6508 /// array type (e.g., because it will decay to a pointer).
6509 ///
6510 /// \returns true if a problem has been diagnosed, false on success.
6511 static bool checkNullabilityTypeSpecifier(TypeProcessingState &state,
6512                                           QualType &type,
6513                                           ParsedAttr &attr,
6514                                           bool allowOnArrayType) {
6515   Sema &S = state.getSema();
6516 
6517   NullabilityKind nullability = mapNullabilityAttrKind(attr.getKind());
6518   SourceLocation nullabilityLoc = attr.getLoc();
6519   bool isContextSensitive = attr.isContextSensitiveKeywordAttribute();
6520 
6521   recordNullabilitySeen(S, nullabilityLoc);
6522 
6523   // Check for existing nullability attributes on the type.
6524   QualType desugared = type;
6525   while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
6526     // Check whether there is already a null
6527     if (auto existingNullability = attributed->getImmediateNullability()) {
6528       // Duplicated nullability.
6529       if (nullability == *existingNullability) {
6530         S.Diag(nullabilityLoc, diag::warn_nullability_duplicate)
6531           << DiagNullabilityKind(nullability, isContextSensitive)
6532           << FixItHint::CreateRemoval(nullabilityLoc);
6533 
6534         break;
6535       }
6536 
6537       // Conflicting nullability.
6538       S.Diag(nullabilityLoc, diag::err_nullability_conflicting)
6539         << DiagNullabilityKind(nullability, isContextSensitive)
6540         << DiagNullabilityKind(*existingNullability, false);
6541       return true;
6542     }
6543 
6544     desugared = attributed->getModifiedType();
6545   }
6546 
6547   // If there is already a different nullability specifier, complain.
6548   // This (unlike the code above) looks through typedefs that might
6549   // have nullability specifiers on them, which means we cannot
6550   // provide a useful Fix-It.
6551   if (auto existingNullability = desugared->getNullability(S.Context)) {
6552     if (nullability != *existingNullability) {
6553       S.Diag(nullabilityLoc, diag::err_nullability_conflicting)
6554         << DiagNullabilityKind(nullability, isContextSensitive)
6555         << DiagNullabilityKind(*existingNullability, false);
6556 
6557       // Try to find the typedef with the existing nullability specifier.
6558       if (auto typedefType = desugared->getAs<TypedefType>()) {
6559         TypedefNameDecl *typedefDecl = typedefType->getDecl();
6560         QualType underlyingType = typedefDecl->getUnderlyingType();
6561         if (auto typedefNullability
6562               = AttributedType::stripOuterNullability(underlyingType)) {
6563           if (*typedefNullability == *existingNullability) {
6564             S.Diag(typedefDecl->getLocation(), diag::note_nullability_here)
6565               << DiagNullabilityKind(*existingNullability, false);
6566           }
6567         }
6568       }
6569 
6570       return true;
6571     }
6572   }
6573 
6574   // If this definitely isn't a pointer type, reject the specifier.
6575   if (!desugared->canHaveNullability() &&
6576       !(allowOnArrayType && desugared->isArrayType())) {
6577     S.Diag(nullabilityLoc, diag::err_nullability_nonpointer)
6578       << DiagNullabilityKind(nullability, isContextSensitive) << type;
6579     return true;
6580   }
6581 
6582   // For the context-sensitive keywords/Objective-C property
6583   // attributes, require that the type be a single-level pointer.
6584   if (isContextSensitive) {
6585     // Make sure that the pointee isn't itself a pointer type.
6586     const Type *pointeeType;
6587     if (desugared->isArrayType())
6588       pointeeType = desugared->getArrayElementTypeNoTypeQual();
6589     else
6590       pointeeType = desugared->getPointeeType().getTypePtr();
6591 
6592     if (pointeeType->isAnyPointerType() ||
6593         pointeeType->isObjCObjectPointerType() ||
6594         pointeeType->isMemberPointerType()) {
6595       S.Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
6596         << DiagNullabilityKind(nullability, true)
6597         << type;
6598       S.Diag(nullabilityLoc, diag::note_nullability_type_specifier)
6599         << DiagNullabilityKind(nullability, false)
6600         << type
6601         << FixItHint::CreateReplacement(nullabilityLoc,
6602                                         getNullabilitySpelling(nullability));
6603       return true;
6604     }
6605   }
6606 
6607   // Form the attributed type.
6608   type = state.getAttributedType(
6609       createNullabilityAttr(S.Context, attr, nullability), type, type);
6610   return false;
6611 }
6612 
6613 /// Check the application of the Objective-C '__kindof' qualifier to
6614 /// the given type.
6615 static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type,
6616                                 ParsedAttr &attr) {
6617   Sema &S = state.getSema();
6618 
6619   if (isa<ObjCTypeParamType>(type)) {
6620     // Build the attributed type to record where __kindof occurred.
6621     type = state.getAttributedType(
6622         createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, type);
6623     return false;
6624   }
6625 
6626   // Find out if it's an Objective-C object or object pointer type;
6627   const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
6628   const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
6629                                           : type->getAs<ObjCObjectType>();
6630 
6631   // If not, we can't apply __kindof.
6632   if (!objType) {
6633     // FIXME: Handle dependent types that aren't yet object types.
6634     S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject)
6635       << type;
6636     return true;
6637   }
6638 
6639   // Rebuild the "equivalent" type, which pushes __kindof down into
6640   // the object type.
6641   // There is no need to apply kindof on an unqualified id type.
6642   QualType equivType = S.Context.getObjCObjectType(
6643       objType->getBaseType(), objType->getTypeArgsAsWritten(),
6644       objType->getProtocols(),
6645       /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
6646 
6647   // If we started with an object pointer type, rebuild it.
6648   if (ptrType) {
6649     equivType = S.Context.getObjCObjectPointerType(equivType);
6650     if (auto nullability = type->getNullability(S.Context)) {
6651       // We create a nullability attribute from the __kindof attribute.
6652       // Make sure that will make sense.
6653       assert(attr.getAttributeSpellingListIndex() == 0 &&
6654              "multiple spellings for __kindof?");
6655       Attr *A = createNullabilityAttr(S.Context, attr, *nullability);
6656       A->setImplicit(true);
6657       equivType = state.getAttributedType(A, equivType, equivType);
6658     }
6659   }
6660 
6661   // Build the attributed type to record where __kindof occurred.
6662   type = state.getAttributedType(
6663       createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, equivType);
6664   return false;
6665 }
6666 
6667 /// Distribute a nullability type attribute that cannot be applied to
6668 /// the type specifier to a pointer, block pointer, or member pointer
6669 /// declarator, complaining if necessary.
6670 ///
6671 /// \returns true if the nullability annotation was distributed, false
6672 /// otherwise.
6673 static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
6674                                           QualType type, ParsedAttr &attr) {
6675   Declarator &declarator = state.getDeclarator();
6676 
6677   /// Attempt to move the attribute to the specified chunk.
6678   auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
6679     // If there is already a nullability attribute there, don't add
6680     // one.
6681     if (hasNullabilityAttr(chunk.getAttrs()))
6682       return false;
6683 
6684     // Complain about the nullability qualifier being in the wrong
6685     // place.
6686     enum {
6687       PK_Pointer,
6688       PK_BlockPointer,
6689       PK_MemberPointer,
6690       PK_FunctionPointer,
6691       PK_MemberFunctionPointer,
6692     } pointerKind
6693       = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
6694                                                              : PK_Pointer)
6695         : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
6696         : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
6697 
6698     auto diag = state.getSema().Diag(attr.getLoc(),
6699                                      diag::warn_nullability_declspec)
6700       << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
6701                              attr.isContextSensitiveKeywordAttribute())
6702       << type
6703       << static_cast<unsigned>(pointerKind);
6704 
6705     // FIXME: MemberPointer chunks don't carry the location of the *.
6706     if (chunk.Kind != DeclaratorChunk::MemberPointer) {
6707       diag << FixItHint::CreateRemoval(attr.getLoc())
6708            << FixItHint::CreateInsertion(
6709                   state.getSema().getPreprocessor().getLocForEndOfToken(
6710                       chunk.Loc),
6711                   " " + attr.getAttrName()->getName().str() + " ");
6712     }
6713 
6714     moveAttrFromListToList(attr, state.getCurrentAttributes(),
6715                            chunk.getAttrs());
6716     return true;
6717   };
6718 
6719   // Move it to the outermost pointer, member pointer, or block
6720   // pointer declarator.
6721   for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
6722     DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
6723     switch (chunk.Kind) {
6724     case DeclaratorChunk::Pointer:
6725     case DeclaratorChunk::BlockPointer:
6726     case DeclaratorChunk::MemberPointer:
6727       return moveToChunk(chunk, false);
6728 
6729     case DeclaratorChunk::Paren:
6730     case DeclaratorChunk::Array:
6731       continue;
6732 
6733     case DeclaratorChunk::Function:
6734       // Try to move past the return type to a function/block/member
6735       // function pointer.
6736       if (DeclaratorChunk *dest = maybeMovePastReturnType(
6737                                     declarator, i,
6738                                     /*onlyBlockPointers=*/false)) {
6739         return moveToChunk(*dest, true);
6740       }
6741 
6742       return false;
6743 
6744     // Don't walk through these.
6745     case DeclaratorChunk::Reference:
6746     case DeclaratorChunk::Pipe:
6747       return false;
6748     }
6749   }
6750 
6751   return false;
6752 }
6753 
6754 static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) {
6755   assert(!Attr.isInvalid());
6756   switch (Attr.getKind()) {
6757   default:
6758     llvm_unreachable("not a calling convention attribute");
6759   case ParsedAttr::AT_CDecl:
6760     return createSimpleAttr<CDeclAttr>(Ctx, Attr);
6761   case ParsedAttr::AT_FastCall:
6762     return createSimpleAttr<FastCallAttr>(Ctx, Attr);
6763   case ParsedAttr::AT_StdCall:
6764     return createSimpleAttr<StdCallAttr>(Ctx, Attr);
6765   case ParsedAttr::AT_ThisCall:
6766     return createSimpleAttr<ThisCallAttr>(Ctx, Attr);
6767   case ParsedAttr::AT_RegCall:
6768     return createSimpleAttr<RegCallAttr>(Ctx, Attr);
6769   case ParsedAttr::AT_Pascal:
6770     return createSimpleAttr<PascalAttr>(Ctx, Attr);
6771   case ParsedAttr::AT_SwiftCall:
6772     return createSimpleAttr<SwiftCallAttr>(Ctx, Attr);
6773   case ParsedAttr::AT_VectorCall:
6774     return createSimpleAttr<VectorCallAttr>(Ctx, Attr);
6775   case ParsedAttr::AT_AArch64VectorPcs:
6776     return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, Attr);
6777   case ParsedAttr::AT_Pcs: {
6778     // The attribute may have had a fixit applied where we treated an
6779     // identifier as a string literal.  The contents of the string are valid,
6780     // but the form may not be.
6781     StringRef Str;
6782     if (Attr.isArgExpr(0))
6783       Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
6784     else
6785       Str = Attr.getArgAsIdent(0)->Ident->getName();
6786     PcsAttr::PCSType Type;
6787     if (!PcsAttr::ConvertStrToPCSType(Str, Type))
6788       llvm_unreachable("already validated the attribute");
6789     return ::new (Ctx) PcsAttr(Ctx, Attr, Type);
6790   }
6791   case ParsedAttr::AT_IntelOclBicc:
6792     return createSimpleAttr<IntelOclBiccAttr>(Ctx, Attr);
6793   case ParsedAttr::AT_MSABI:
6794     return createSimpleAttr<MSABIAttr>(Ctx, Attr);
6795   case ParsedAttr::AT_SysVABI:
6796     return createSimpleAttr<SysVABIAttr>(Ctx, Attr);
6797   case ParsedAttr::AT_PreserveMost:
6798     return createSimpleAttr<PreserveMostAttr>(Ctx, Attr);
6799   case ParsedAttr::AT_PreserveAll:
6800     return createSimpleAttr<PreserveAllAttr>(Ctx, Attr);
6801   }
6802   llvm_unreachable("unexpected attribute kind!");
6803 }
6804 
6805 /// Process an individual function attribute.  Returns true to
6806 /// indicate that the attribute was handled, false if it wasn't.
6807 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
6808                                    QualType &type) {
6809   Sema &S = state.getSema();
6810 
6811   FunctionTypeUnwrapper unwrapped(S, type);
6812 
6813   if (attr.getKind() == ParsedAttr::AT_NoReturn) {
6814     if (S.CheckAttrNoArgs(attr))
6815       return true;
6816 
6817     // Delay if this is not a function type.
6818     if (!unwrapped.isFunctionType())
6819       return false;
6820 
6821     // Otherwise we can process right away.
6822     FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
6823     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6824     return true;
6825   }
6826 
6827   // ns_returns_retained is not always a type attribute, but if we got
6828   // here, we're treating it as one right now.
6829   if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) {
6830     if (attr.getNumArgs()) return true;
6831 
6832     // Delay if this is not a function type.
6833     if (!unwrapped.isFunctionType())
6834       return false;
6835 
6836     // Check whether the return type is reasonable.
6837     if (S.checkNSReturnsRetainedReturnType(attr.getLoc(),
6838                                            unwrapped.get()->getReturnType()))
6839       return true;
6840 
6841     // Only actually change the underlying type in ARC builds.
6842     QualType origType = type;
6843     if (state.getSema().getLangOpts().ObjCAutoRefCount) {
6844       FunctionType::ExtInfo EI
6845         = unwrapped.get()->getExtInfo().withProducesResult(true);
6846       type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6847     }
6848     type = state.getAttributedType(
6849         createSimpleAttr<NSReturnsRetainedAttr>(S.Context, attr),
6850         origType, type);
6851     return true;
6852   }
6853 
6854   if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) {
6855     if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
6856       return true;
6857 
6858     // Delay if this is not a function type.
6859     if (!unwrapped.isFunctionType())
6860       return false;
6861 
6862     FunctionType::ExtInfo EI =
6863         unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true);
6864     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6865     return true;
6866   }
6867 
6868   if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) {
6869     if (!S.getLangOpts().CFProtectionBranch) {
6870       S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored);
6871       attr.setInvalid();
6872       return true;
6873     }
6874 
6875     if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
6876       return true;
6877 
6878     // If this is not a function type, warning will be asserted by subject
6879     // check.
6880     if (!unwrapped.isFunctionType())
6881       return true;
6882 
6883     FunctionType::ExtInfo EI =
6884       unwrapped.get()->getExtInfo().withNoCfCheck(true);
6885     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6886     return true;
6887   }
6888 
6889   if (attr.getKind() == ParsedAttr::AT_Regparm) {
6890     unsigned value;
6891     if (S.CheckRegparmAttr(attr, value))
6892       return true;
6893 
6894     // Delay if this is not a function type.
6895     if (!unwrapped.isFunctionType())
6896       return false;
6897 
6898     // Diagnose regparm with fastcall.
6899     const FunctionType *fn = unwrapped.get();
6900     CallingConv CC = fn->getCallConv();
6901     if (CC == CC_X86FastCall) {
6902       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6903         << FunctionType::getNameForCallConv(CC)
6904         << "regparm";
6905       attr.setInvalid();
6906       return true;
6907     }
6908 
6909     FunctionType::ExtInfo EI =
6910       unwrapped.get()->getExtInfo().withRegParm(value);
6911     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6912     return true;
6913   }
6914 
6915   if (attr.getKind() == ParsedAttr::AT_NoThrow) {
6916     // Delay if this is not a function type.
6917     if (!unwrapped.isFunctionType())
6918       return false;
6919 
6920     if (S.CheckAttrNoArgs(attr)) {
6921       attr.setInvalid();
6922       return true;
6923     }
6924 
6925     // Otherwise we can process right away.
6926     auto *Proto = unwrapped.get()->castAs<FunctionProtoType>();
6927 
6928     // MSVC ignores nothrow if it is in conflict with an explicit exception
6929     // specification.
6930     if (Proto->hasExceptionSpec()) {
6931       switch (Proto->getExceptionSpecType()) {
6932       case EST_None:
6933         llvm_unreachable("This doesn't have an exception spec!");
6934 
6935       case EST_DynamicNone:
6936       case EST_BasicNoexcept:
6937       case EST_NoexceptTrue:
6938       case EST_NoThrow:
6939         // Exception spec doesn't conflict with nothrow, so don't warn.
6940         LLVM_FALLTHROUGH;
6941       case EST_Unparsed:
6942       case EST_Uninstantiated:
6943       case EST_DependentNoexcept:
6944       case EST_Unevaluated:
6945         // We don't have enough information to properly determine if there is a
6946         // conflict, so suppress the warning.
6947         break;
6948       case EST_Dynamic:
6949       case EST_MSAny:
6950       case EST_NoexceptFalse:
6951         S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored);
6952         break;
6953       }
6954       return true;
6955     }
6956 
6957     type = unwrapped.wrap(
6958         S, S.Context
6959                .getFunctionTypeWithExceptionSpec(
6960                    QualType{Proto, 0},
6961                    FunctionProtoType::ExceptionSpecInfo{EST_NoThrow})
6962                ->getAs<FunctionType>());
6963     return true;
6964   }
6965 
6966   // Delay if the type didn't work out to a function.
6967   if (!unwrapped.isFunctionType()) return false;
6968 
6969   // Otherwise, a calling convention.
6970   CallingConv CC;
6971   if (S.CheckCallingConvAttr(attr, CC))
6972     return true;
6973 
6974   const FunctionType *fn = unwrapped.get();
6975   CallingConv CCOld = fn->getCallConv();
6976   Attr *CCAttr = getCCTypeAttr(S.Context, attr);
6977 
6978   if (CCOld != CC) {
6979     // Error out on when there's already an attribute on the type
6980     // and the CCs don't match.
6981     if (S.getCallingConvAttributedType(type)) {
6982       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6983         << FunctionType::getNameForCallConv(CC)
6984         << FunctionType::getNameForCallConv(CCOld);
6985       attr.setInvalid();
6986       return true;
6987     }
6988   }
6989 
6990   // Diagnose use of variadic functions with calling conventions that
6991   // don't support them (e.g. because they're callee-cleanup).
6992   // We delay warning about this on unprototyped function declarations
6993   // until after redeclaration checking, just in case we pick up a
6994   // prototype that way.  And apparently we also "delay" warning about
6995   // unprototyped function types in general, despite not necessarily having
6996   // much ability to diagnose it later.
6997   if (!supportsVariadicCall(CC)) {
6998     const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
6999     if (FnP && FnP->isVariadic()) {
7000       // stdcall and fastcall are ignored with a warning for GCC and MS
7001       // compatibility.
7002       if (CC == CC_X86StdCall || CC == CC_X86FastCall)
7003         return S.Diag(attr.getLoc(), diag::warn_cconv_unsupported)
7004                << FunctionType::getNameForCallConv(CC)
7005                << (int)Sema::CallingConventionIgnoredReason::VariadicFunction;
7006 
7007       attr.setInvalid();
7008       return S.Diag(attr.getLoc(), diag::err_cconv_varargs)
7009              << FunctionType::getNameForCallConv(CC);
7010     }
7011   }
7012 
7013   // Also diagnose fastcall with regparm.
7014   if (CC == CC_X86FastCall && fn->getHasRegParm()) {
7015     S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
7016         << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
7017     attr.setInvalid();
7018     return true;
7019   }
7020 
7021   // Modify the CC from the wrapped function type, wrap it all back, and then
7022   // wrap the whole thing in an AttributedType as written.  The modified type
7023   // might have a different CC if we ignored the attribute.
7024   QualType Equivalent;
7025   if (CCOld == CC) {
7026     Equivalent = type;
7027   } else {
7028     auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
7029     Equivalent =
7030       unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7031   }
7032   type = state.getAttributedType(CCAttr, type, Equivalent);
7033   return true;
7034 }
7035 
7036 bool Sema::hasExplicitCallingConv(QualType T) {
7037   const AttributedType *AT;
7038 
7039   // Stop if we'd be stripping off a typedef sugar node to reach the
7040   // AttributedType.
7041   while ((AT = T->getAs<AttributedType>()) &&
7042          AT->getAs<TypedefType>() == T->getAs<TypedefType>()) {
7043     if (AT->isCallingConv())
7044       return true;
7045     T = AT->getModifiedType();
7046   }
7047   return false;
7048 }
7049 
7050 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
7051                                   SourceLocation Loc) {
7052   FunctionTypeUnwrapper Unwrapped(*this, T);
7053   const FunctionType *FT = Unwrapped.get();
7054   bool IsVariadic = (isa<FunctionProtoType>(FT) &&
7055                      cast<FunctionProtoType>(FT)->isVariadic());
7056   CallingConv CurCC = FT->getCallConv();
7057   CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
7058 
7059   if (CurCC == ToCC)
7060     return;
7061 
7062   // MS compiler ignores explicit calling convention attributes on structors. We
7063   // should do the same.
7064   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
7065     // Issue a warning on ignored calling convention -- except of __stdcall.
7066     // Again, this is what MS compiler does.
7067     if (CurCC != CC_X86StdCall)
7068       Diag(Loc, diag::warn_cconv_unsupported)
7069           << FunctionType::getNameForCallConv(CurCC)
7070           << (int)Sema::CallingConventionIgnoredReason::ConstructorDestructor;
7071   // Default adjustment.
7072   } else {
7073     // Only adjust types with the default convention.  For example, on Windows
7074     // we should adjust a __cdecl type to __thiscall for instance methods, and a
7075     // __thiscall type to __cdecl for static methods.
7076     CallingConv DefaultCC =
7077         Context.getDefaultCallingConvention(IsVariadic, IsStatic);
7078 
7079     if (CurCC != DefaultCC || DefaultCC == ToCC)
7080       return;
7081 
7082     if (hasExplicitCallingConv(T))
7083       return;
7084   }
7085 
7086   FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
7087   QualType Wrapped = Unwrapped.wrap(*this, FT);
7088   T = Context.getAdjustedType(T, Wrapped);
7089 }
7090 
7091 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
7092 /// and float scalars, although arrays, pointers, and function return values are
7093 /// allowed in conjunction with this construct. Aggregates with this attribute
7094 /// are invalid, even if they are of the same size as a corresponding scalar.
7095 /// The raw attribute should contain precisely 1 argument, the vector size for
7096 /// the variable, measured in bytes. If curType and rawAttr are well formed,
7097 /// this routine will return a new vector type.
7098 static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr,
7099                                  Sema &S) {
7100   // Check the attribute arguments.
7101   if (Attr.getNumArgs() != 1) {
7102     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
7103                                                                       << 1;
7104     Attr.setInvalid();
7105     return;
7106   }
7107 
7108   Expr *SizeExpr;
7109   // Special case where the argument is a template id.
7110   if (Attr.isArgIdent(0)) {
7111     CXXScopeSpec SS;
7112     SourceLocation TemplateKWLoc;
7113     UnqualifiedId Id;
7114     Id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
7115 
7116     ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
7117                                           Id, /*HasTrailingLParen=*/false,
7118                                           /*IsAddressOfOperand=*/false);
7119 
7120     if (Size.isInvalid())
7121       return;
7122     SizeExpr = Size.get();
7123   } else {
7124     SizeExpr = Attr.getArgAsExpr(0);
7125   }
7126 
7127   QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc());
7128   if (!T.isNull())
7129     CurType = T;
7130   else
7131     Attr.setInvalid();
7132 }
7133 
7134 /// Process the OpenCL-like ext_vector_type attribute when it occurs on
7135 /// a type.
7136 static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
7137                                     Sema &S) {
7138   // check the attribute arguments.
7139   if (Attr.getNumArgs() != 1) {
7140     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
7141                                                                       << 1;
7142     return;
7143   }
7144 
7145   Expr *sizeExpr;
7146 
7147   // Special case where the argument is a template id.
7148   if (Attr.isArgIdent(0)) {
7149     CXXScopeSpec SS;
7150     SourceLocation TemplateKWLoc;
7151     UnqualifiedId id;
7152     id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
7153 
7154     ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
7155                                           id, /*HasTrailingLParen=*/false,
7156                                           /*IsAddressOfOperand=*/false);
7157     if (Size.isInvalid())
7158       return;
7159 
7160     sizeExpr = Size.get();
7161   } else {
7162     sizeExpr = Attr.getArgAsExpr(0);
7163   }
7164 
7165   // Create the vector type.
7166   QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
7167   if (!T.isNull())
7168     CurType = T;
7169 }
7170 
7171 static bool isPermittedNeonBaseType(QualType &Ty,
7172                                     VectorType::VectorKind VecKind, Sema &S) {
7173   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
7174   if (!BTy)
7175     return false;
7176 
7177   llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
7178 
7179   // Signed poly is mathematically wrong, but has been baked into some ABIs by
7180   // now.
7181   bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
7182                         Triple.getArch() == llvm::Triple::aarch64_be;
7183   if (VecKind == VectorType::NeonPolyVector) {
7184     if (IsPolyUnsigned) {
7185       // AArch64 polynomial vectors are unsigned and support poly64.
7186       return BTy->getKind() == BuiltinType::UChar ||
7187              BTy->getKind() == BuiltinType::UShort ||
7188              BTy->getKind() == BuiltinType::ULong ||
7189              BTy->getKind() == BuiltinType::ULongLong;
7190     } else {
7191       // AArch32 polynomial vector are signed.
7192       return BTy->getKind() == BuiltinType::SChar ||
7193              BTy->getKind() == BuiltinType::Short;
7194     }
7195   }
7196 
7197   // Non-polynomial vector types: the usual suspects are allowed, as well as
7198   // float64_t on AArch64.
7199   bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 ||
7200                  Triple.getArch() == llvm::Triple::aarch64_be;
7201 
7202   if (Is64Bit && BTy->getKind() == BuiltinType::Double)
7203     return true;
7204 
7205   return BTy->getKind() == BuiltinType::SChar ||
7206          BTy->getKind() == BuiltinType::UChar ||
7207          BTy->getKind() == BuiltinType::Short ||
7208          BTy->getKind() == BuiltinType::UShort ||
7209          BTy->getKind() == BuiltinType::Int ||
7210          BTy->getKind() == BuiltinType::UInt ||
7211          BTy->getKind() == BuiltinType::Long ||
7212          BTy->getKind() == BuiltinType::ULong ||
7213          BTy->getKind() == BuiltinType::LongLong ||
7214          BTy->getKind() == BuiltinType::ULongLong ||
7215          BTy->getKind() == BuiltinType::Float ||
7216          BTy->getKind() == BuiltinType::Half;
7217 }
7218 
7219 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
7220 /// "neon_polyvector_type" attributes are used to create vector types that
7221 /// are mangled according to ARM's ABI.  Otherwise, these types are identical
7222 /// to those created with the "vector_size" attribute.  Unlike "vector_size"
7223 /// the argument to these Neon attributes is the number of vector elements,
7224 /// not the vector size in bytes.  The vector width and element type must
7225 /// match one of the standard Neon vector types.
7226 static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
7227                                      Sema &S, VectorType::VectorKind VecKind) {
7228   // Target must have NEON
7229   if (!S.Context.getTargetInfo().hasFeature("neon")) {
7230     S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr;
7231     Attr.setInvalid();
7232     return;
7233   }
7234   // Check the attribute arguments.
7235   if (Attr.getNumArgs() != 1) {
7236     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
7237                                                                       << 1;
7238     Attr.setInvalid();
7239     return;
7240   }
7241   // The number of elements must be an ICE.
7242   Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
7243   llvm::APSInt numEltsInt(32);
7244   if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
7245       !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
7246     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
7247         << Attr << AANT_ArgumentIntegerConstant
7248         << numEltsExpr->getSourceRange();
7249     Attr.setInvalid();
7250     return;
7251   }
7252   // Only certain element types are supported for Neon vectors.
7253   if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
7254     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
7255     Attr.setInvalid();
7256     return;
7257   }
7258 
7259   // The total size of the vector must be 64 or 128 bits.
7260   unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
7261   unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
7262   unsigned vecSize = typeSize * numElts;
7263   if (vecSize != 64 && vecSize != 128) {
7264     S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
7265     Attr.setInvalid();
7266     return;
7267   }
7268 
7269   CurType = S.Context.getVectorType(CurType, numElts, VecKind);
7270 }
7271 
7272 /// Handle OpenCL Access Qualifier Attribute.
7273 static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr,
7274                                    Sema &S) {
7275   // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
7276   if (!(CurType->isImageType() || CurType->isPipeType())) {
7277     S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
7278     Attr.setInvalid();
7279     return;
7280   }
7281 
7282   if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
7283     QualType BaseTy = TypedefTy->desugar();
7284 
7285     std::string PrevAccessQual;
7286     if (BaseTy->isPipeType()) {
7287       if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) {
7288         OpenCLAccessAttr *Attr =
7289             TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>();
7290         PrevAccessQual = Attr->getSpelling();
7291       } else {
7292         PrevAccessQual = "read_only";
7293       }
7294     } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) {
7295 
7296       switch (ImgType->getKind()) {
7297         #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7298       case BuiltinType::Id:                                          \
7299         PrevAccessQual = #Access;                                    \
7300         break;
7301         #include "clang/Basic/OpenCLImageTypes.def"
7302       default:
7303         llvm_unreachable("Unable to find corresponding image type.");
7304       }
7305     } else {
7306       llvm_unreachable("unexpected type");
7307     }
7308     StringRef AttrName = Attr.getAttrName()->getName();
7309     if (PrevAccessQual == AttrName.ltrim("_")) {
7310       // Duplicated qualifiers
7311       S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec)
7312          << AttrName << Attr.getRange();
7313     } else {
7314       // Contradicting qualifiers
7315       S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
7316     }
7317 
7318     S.Diag(TypedefTy->getDecl()->getBeginLoc(),
7319            diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
7320   } else if (CurType->isPipeType()) {
7321     if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
7322       QualType ElemType = CurType->getAs<PipeType>()->getElementType();
7323       CurType = S.Context.getWritePipeType(ElemType);
7324     }
7325   }
7326 }
7327 
7328 static void deduceOpenCLImplicitAddrSpace(TypeProcessingState &State,
7329                                           QualType &T, TypeAttrLocation TAL) {
7330   Declarator &D = State.getDeclarator();
7331 
7332   // Handle the cases where address space should not be deduced.
7333   //
7334   // The pointee type of a pointer type is always deduced since a pointer always
7335   // points to some memory location which should has an address space.
7336   //
7337   // There are situations that at the point of certain declarations, the address
7338   // space may be unknown and better to be left as default. For example, when
7339   // defining a typedef or struct type, they are not associated with any
7340   // specific address space. Later on, they may be used with any address space
7341   // to declare a variable.
7342   //
7343   // The return value of a function is r-value, therefore should not have
7344   // address space.
7345   //
7346   // The void type does not occupy memory, therefore should not have address
7347   // space, except when it is used as a pointee type.
7348   //
7349   // Since LLVM assumes function type is in default address space, it should not
7350   // have address space.
7351   auto ChunkIndex = State.getCurrentChunkIndex();
7352   bool IsPointee =
7353       ChunkIndex > 0 &&
7354       (D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Pointer ||
7355        D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Reference ||
7356        D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::BlockPointer);
7357   // For pointers/references to arrays the next chunk is always an array
7358   // followed by any number of parentheses.
7359   if (!IsPointee && ChunkIndex > 1) {
7360     auto AdjustedCI = ChunkIndex - 1;
7361     if (D.getTypeObject(AdjustedCI).Kind == DeclaratorChunk::Array)
7362       AdjustedCI--;
7363     // Skip over all parentheses.
7364     while (AdjustedCI > 0 &&
7365            D.getTypeObject(AdjustedCI).Kind == DeclaratorChunk::Paren)
7366       AdjustedCI--;
7367     if (D.getTypeObject(AdjustedCI).Kind == DeclaratorChunk::Pointer ||
7368         D.getTypeObject(AdjustedCI).Kind == DeclaratorChunk::Reference)
7369       IsPointee = true;
7370   }
7371   bool IsFuncReturnType =
7372       ChunkIndex > 0 &&
7373       D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Function;
7374   bool IsFuncType =
7375       ChunkIndex < D.getNumTypeObjects() &&
7376       D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function;
7377   if ( // Do not deduce addr space for function return type and function type,
7378        // otherwise it will fail some sema check.
7379       IsFuncReturnType || IsFuncType ||
7380       // Do not deduce addr space for member types of struct, except the pointee
7381       // type of a pointer member type or static data members.
7382       (D.getContext() == DeclaratorContext::MemberContext &&
7383        (!IsPointee &&
7384         D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)) ||
7385       // Do not deduce addr space of non-pointee in type alias because it
7386       // doesn't define any object.
7387       (D.getContext() == DeclaratorContext::AliasDeclContext && !IsPointee) ||
7388       // Do not deduce addr space for types used to define a typedef and the
7389       // typedef itself, except the pointee type of a pointer type which is used
7390       // to define the typedef.
7391       (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef &&
7392        !IsPointee) ||
7393       // Do not deduce addr space of the void type, e.g. in f(void), otherwise
7394       // it will fail some sema check.
7395       (T->isVoidType() && !IsPointee) ||
7396       // Do not deduce addr spaces for dependent types because they might end
7397       // up instantiating to a type with an explicit address space qualifier.
7398       // Except for pointer or reference types because the addr space in
7399       // template argument can only belong to a pointee.
7400       (T->isDependentType() && !T->isPointerType() && !T->isReferenceType()) ||
7401       // Do not deduce addr space of decltype because it will be taken from
7402       // its argument.
7403       T->isDecltypeType() ||
7404       // OpenCL spec v2.0 s6.9.b:
7405       // The sampler type cannot be used with the __local and __global address
7406       // space qualifiers.
7407       // OpenCL spec v2.0 s6.13.14:
7408       // Samplers can also be declared as global constants in the program
7409       // source using the following syntax.
7410       //   const sampler_t <sampler name> = <value>
7411       // In codegen, file-scope sampler type variable has special handing and
7412       // does not rely on address space qualifier. On the other hand, deducing
7413       // address space of const sampler file-scope variable as global address
7414       // space causes spurious diagnostic about __global address space
7415       // qualifier, therefore do not deduce address space of file-scope sampler
7416       // type variable.
7417       (D.getContext() == DeclaratorContext::FileContext && T->isSamplerT()))
7418     return;
7419 
7420   LangAS ImpAddr = LangAS::Default;
7421   // Put OpenCL automatic variable in private address space.
7422   // OpenCL v1.2 s6.5:
7423   // The default address space name for arguments to a function in a
7424   // program, or local variables of a function is __private. All function
7425   // arguments shall be in the __private address space.
7426   if (State.getSema().getLangOpts().OpenCLVersion <= 120 &&
7427       !State.getSema().getLangOpts().OpenCLCPlusPlus) {
7428     ImpAddr = LangAS::opencl_private;
7429   } else {
7430     // If address space is not set, OpenCL 2.0 defines non private default
7431     // address spaces for some cases:
7432     // OpenCL 2.0, section 6.5:
7433     // The address space for a variable at program scope or a static variable
7434     // inside a function can either be __global or __constant, but defaults to
7435     // __global if not specified.
7436     // (...)
7437     // Pointers that are declared without pointing to a named address space
7438     // point to the generic address space.
7439     if (IsPointee) {
7440       ImpAddr = LangAS::opencl_generic;
7441     } else {
7442       if (D.getContext() == DeclaratorContext::TemplateArgContext) {
7443         // Do not deduce address space for non-pointee type in template arg.
7444       } else if (D.getContext() == DeclaratorContext::FileContext) {
7445         ImpAddr = LangAS::opencl_global;
7446       } else {
7447         if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
7448             D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) {
7449           ImpAddr = LangAS::opencl_global;
7450         } else {
7451           ImpAddr = LangAS::opencl_private;
7452         }
7453       }
7454     }
7455   }
7456   T = State.getSema().Context.getAddrSpaceQualType(T, ImpAddr);
7457 }
7458 
7459 static void HandleLifetimeBoundAttr(TypeProcessingState &State,
7460                                     QualType &CurType,
7461                                     ParsedAttr &Attr) {
7462   if (State.getDeclarator().isDeclarationOfFunction()) {
7463     CurType = State.getAttributedType(
7464         createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr),
7465         CurType, CurType);
7466   } else {
7467     Attr.diagnoseAppertainsTo(State.getSema(), nullptr);
7468   }
7469 }
7470 
7471 
7472 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
7473                              TypeAttrLocation TAL,
7474                              ParsedAttributesView &attrs) {
7475   // Scan through and apply attributes to this type where it makes sense.  Some
7476   // attributes (such as __address_space__, __vector_size__, etc) apply to the
7477   // type, but others can be present in the type specifiers even though they
7478   // apply to the decl.  Here we apply type attributes and ignore the rest.
7479 
7480   // This loop modifies the list pretty frequently, but we still need to make
7481   // sure we visit every element once. Copy the attributes list, and iterate
7482   // over that.
7483   ParsedAttributesView AttrsCopy{attrs};
7484 
7485   state.setParsedNoDeref(false);
7486 
7487   for (ParsedAttr &attr : AttrsCopy) {
7488 
7489     // Skip attributes that were marked to be invalid.
7490     if (attr.isInvalid())
7491       continue;
7492 
7493     if (attr.isCXX11Attribute()) {
7494       // [[gnu::...]] attributes are treated as declaration attributes, so may
7495       // not appertain to a DeclaratorChunk. If we handle them as type
7496       // attributes, accept them in that position and diagnose the GCC
7497       // incompatibility.
7498       if (attr.isGNUScope()) {
7499         bool IsTypeAttr = attr.isTypeAttr();
7500         if (TAL == TAL_DeclChunk) {
7501           state.getSema().Diag(attr.getLoc(),
7502                                IsTypeAttr
7503                                    ? diag::warn_gcc_ignores_type_attr
7504                                    : diag::warn_cxx11_gnu_attribute_on_type)
7505               << attr;
7506           if (!IsTypeAttr)
7507             continue;
7508         }
7509       } else if (TAL != TAL_DeclChunk &&
7510                  attr.getKind() != ParsedAttr::AT_AddressSpace) {
7511         // Otherwise, only consider type processing for a C++11 attribute if
7512         // it's actually been applied to a type.
7513         // We also allow C++11 address_space attributes to pass through.
7514         continue;
7515       }
7516     }
7517 
7518     // If this is an attribute we can handle, do so now,
7519     // otherwise, add it to the FnAttrs list for rechaining.
7520     switch (attr.getKind()) {
7521     default:
7522       // A C++11 attribute on a declarator chunk must appertain to a type.
7523       if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
7524         state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
7525             << attr;
7526         attr.setUsedAsTypeAttr();
7527       }
7528       break;
7529 
7530     case ParsedAttr::UnknownAttribute:
7531       if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
7532         state.getSema().Diag(attr.getLoc(),
7533                              diag::warn_unknown_attribute_ignored)
7534             << attr;
7535       break;
7536 
7537     case ParsedAttr::IgnoredAttribute:
7538       break;
7539 
7540     case ParsedAttr::AT_MayAlias:
7541       // FIXME: This attribute needs to actually be handled, but if we ignore
7542       // it it breaks large amounts of Linux software.
7543       attr.setUsedAsTypeAttr();
7544       break;
7545     case ParsedAttr::AT_OpenCLPrivateAddressSpace:
7546     case ParsedAttr::AT_OpenCLGlobalAddressSpace:
7547     case ParsedAttr::AT_OpenCLLocalAddressSpace:
7548     case ParsedAttr::AT_OpenCLConstantAddressSpace:
7549     case ParsedAttr::AT_OpenCLGenericAddressSpace:
7550     case ParsedAttr::AT_AddressSpace:
7551       HandleAddressSpaceTypeAttribute(type, attr, state);
7552       attr.setUsedAsTypeAttr();
7553       break;
7554     OBJC_POINTER_TYPE_ATTRS_CASELIST:
7555       if (!handleObjCPointerTypeAttr(state, attr, type))
7556         distributeObjCPointerTypeAttr(state, attr, type);
7557       attr.setUsedAsTypeAttr();
7558       break;
7559     case ParsedAttr::AT_VectorSize:
7560       HandleVectorSizeAttr(type, attr, state.getSema());
7561       attr.setUsedAsTypeAttr();
7562       break;
7563     case ParsedAttr::AT_ExtVectorType:
7564       HandleExtVectorTypeAttr(type, attr, state.getSema());
7565       attr.setUsedAsTypeAttr();
7566       break;
7567     case ParsedAttr::AT_NeonVectorType:
7568       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
7569                                VectorType::NeonVector);
7570       attr.setUsedAsTypeAttr();
7571       break;
7572     case ParsedAttr::AT_NeonPolyVectorType:
7573       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
7574                                VectorType::NeonPolyVector);
7575       attr.setUsedAsTypeAttr();
7576       break;
7577     case ParsedAttr::AT_OpenCLAccess:
7578       HandleOpenCLAccessAttr(type, attr, state.getSema());
7579       attr.setUsedAsTypeAttr();
7580       break;
7581     case ParsedAttr::AT_LifetimeBound:
7582       if (TAL == TAL_DeclChunk)
7583         HandleLifetimeBoundAttr(state, type, attr);
7584       break;
7585 
7586     case ParsedAttr::AT_NoDeref: {
7587       ASTContext &Ctx = state.getSema().Context;
7588       type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr),
7589                                      type, type);
7590       attr.setUsedAsTypeAttr();
7591       state.setParsedNoDeref(true);
7592       break;
7593     }
7594 
7595     MS_TYPE_ATTRS_CASELIST:
7596       if (!handleMSPointerTypeQualifierAttr(state, attr, type))
7597         attr.setUsedAsTypeAttr();
7598       break;
7599 
7600 
7601     NULLABILITY_TYPE_ATTRS_CASELIST:
7602       // Either add nullability here or try to distribute it.  We
7603       // don't want to distribute the nullability specifier past any
7604       // dependent type, because that complicates the user model.
7605       if (type->canHaveNullability() || type->isDependentType() ||
7606           type->isArrayType() ||
7607           !distributeNullabilityTypeAttr(state, type, attr)) {
7608         unsigned endIndex;
7609         if (TAL == TAL_DeclChunk)
7610           endIndex = state.getCurrentChunkIndex();
7611         else
7612           endIndex = state.getDeclarator().getNumTypeObjects();
7613         bool allowOnArrayType =
7614             state.getDeclarator().isPrototypeContext() &&
7615             !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
7616         if (checkNullabilityTypeSpecifier(
7617               state,
7618               type,
7619               attr,
7620               allowOnArrayType)) {
7621           attr.setInvalid();
7622         }
7623 
7624         attr.setUsedAsTypeAttr();
7625       }
7626       break;
7627 
7628     case ParsedAttr::AT_ObjCKindOf:
7629       // '__kindof' must be part of the decl-specifiers.
7630       switch (TAL) {
7631       case TAL_DeclSpec:
7632         break;
7633 
7634       case TAL_DeclChunk:
7635       case TAL_DeclName:
7636         state.getSema().Diag(attr.getLoc(),
7637                              diag::err_objc_kindof_wrong_position)
7638             << FixItHint::CreateRemoval(attr.getLoc())
7639             << FixItHint::CreateInsertion(
7640                    state.getDeclarator().getDeclSpec().getBeginLoc(),
7641                    "__kindof ");
7642         break;
7643       }
7644 
7645       // Apply it regardless.
7646       if (checkObjCKindOfType(state, type, attr))
7647         attr.setInvalid();
7648       break;
7649 
7650     case ParsedAttr::AT_NoThrow:
7651     // Exception Specifications aren't generally supported in C mode throughout
7652     // clang, so revert to attribute-based handling for C.
7653       if (!state.getSema().getLangOpts().CPlusPlus)
7654         break;
7655       LLVM_FALLTHROUGH;
7656     FUNCTION_TYPE_ATTRS_CASELIST:
7657       attr.setUsedAsTypeAttr();
7658 
7659       // Never process function type attributes as part of the
7660       // declaration-specifiers.
7661       if (TAL == TAL_DeclSpec)
7662         distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
7663 
7664       // Otherwise, handle the possible delays.
7665       else if (!handleFunctionTypeAttr(state, attr, type))
7666         distributeFunctionTypeAttr(state, attr, type);
7667       break;
7668     }
7669 
7670     // Handle attributes that are defined in a macro. We do not want this to be
7671     // applied to ObjC builtin attributes.
7672     if (isa<AttributedType>(type) && attr.hasMacroIdentifier() &&
7673         !type.getQualifiers().hasObjCLifetime() &&
7674         !type.getQualifiers().hasObjCGCAttr() &&
7675         attr.getKind() != ParsedAttr::AT_ObjCGC &&
7676         attr.getKind() != ParsedAttr::AT_ObjCOwnership) {
7677       const IdentifierInfo *MacroII = attr.getMacroIdentifier();
7678       type = state.getSema().Context.getMacroQualifiedType(type, MacroII);
7679       state.setExpansionLocForMacroQualifiedType(
7680           cast<MacroQualifiedType>(type.getTypePtr()),
7681           attr.getMacroExpansionLoc());
7682     }
7683   }
7684 
7685   if (!state.getSema().getLangOpts().OpenCL ||
7686       type.getAddressSpace() != LangAS::Default)
7687     return;
7688 
7689   deduceOpenCLImplicitAddrSpace(state, type, TAL);
7690 }
7691 
7692 void Sema::completeExprArrayBound(Expr *E) {
7693   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
7694     if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
7695       if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
7696         auto *Def = Var->getDefinition();
7697         if (!Def) {
7698           SourceLocation PointOfInstantiation = E->getExprLoc();
7699           runWithSufficientStackSpace(PointOfInstantiation, [&] {
7700             InstantiateVariableDefinition(PointOfInstantiation, Var);
7701           });
7702           Def = Var->getDefinition();
7703 
7704           // If we don't already have a point of instantiation, and we managed
7705           // to instantiate a definition, this is the point of instantiation.
7706           // Otherwise, we don't request an end-of-TU instantiation, so this is
7707           // not a point of instantiation.
7708           // FIXME: Is this really the right behavior?
7709           if (Var->getPointOfInstantiation().isInvalid() && Def) {
7710             assert(Var->getTemplateSpecializationKind() ==
7711                        TSK_ImplicitInstantiation &&
7712                    "explicit instantiation with no point of instantiation");
7713             Var->setTemplateSpecializationKind(
7714                 Var->getTemplateSpecializationKind(), PointOfInstantiation);
7715           }
7716         }
7717 
7718         // Update the type to the definition's type both here and within the
7719         // expression.
7720         if (Def) {
7721           DRE->setDecl(Def);
7722           QualType T = Def->getType();
7723           DRE->setType(T);
7724           // FIXME: Update the type on all intervening expressions.
7725           E->setType(T);
7726         }
7727 
7728         // We still go on to try to complete the type independently, as it
7729         // may also require instantiations or diagnostics if it remains
7730         // incomplete.
7731       }
7732     }
7733   }
7734 }
7735 
7736 /// Ensure that the type of the given expression is complete.
7737 ///
7738 /// This routine checks whether the expression \p E has a complete type. If the
7739 /// expression refers to an instantiable construct, that instantiation is
7740 /// performed as needed to complete its type. Furthermore
7741 /// Sema::RequireCompleteType is called for the expression's type (or in the
7742 /// case of a reference type, the referred-to type).
7743 ///
7744 /// \param E The expression whose type is required to be complete.
7745 /// \param Diagnoser The object that will emit a diagnostic if the type is
7746 /// incomplete.
7747 ///
7748 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
7749 /// otherwise.
7750 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) {
7751   QualType T = E->getType();
7752 
7753   // Incomplete array types may be completed by the initializer attached to
7754   // their definitions. For static data members of class templates and for
7755   // variable templates, we need to instantiate the definition to get this
7756   // initializer and complete the type.
7757   if (T->isIncompleteArrayType()) {
7758     completeExprArrayBound(E);
7759     T = E->getType();
7760   }
7761 
7762   // FIXME: Are there other cases which require instantiating something other
7763   // than the type to complete the type of an expression?
7764 
7765   return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
7766 }
7767 
7768 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
7769   BoundTypeDiagnoser<> Diagnoser(DiagID);
7770   return RequireCompleteExprType(E, Diagnoser);
7771 }
7772 
7773 /// Ensure that the type T is a complete type.
7774 ///
7775 /// This routine checks whether the type @p T is complete in any
7776 /// context where a complete type is required. If @p T is a complete
7777 /// type, returns false. If @p T is a class template specialization,
7778 /// this routine then attempts to perform class template
7779 /// instantiation. If instantiation fails, or if @p T is incomplete
7780 /// and cannot be completed, issues the diagnostic @p diag (giving it
7781 /// the type @p T) and returns true.
7782 ///
7783 /// @param Loc  The location in the source that the incomplete type
7784 /// diagnostic should refer to.
7785 ///
7786 /// @param T  The type that this routine is examining for completeness.
7787 ///
7788 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
7789 /// @c false otherwise.
7790 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
7791                                TypeDiagnoser &Diagnoser) {
7792   if (RequireCompleteTypeImpl(Loc, T, &Diagnoser))
7793     return true;
7794   if (const TagType *Tag = T->getAs<TagType>()) {
7795     if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
7796       Tag->getDecl()->setCompleteDefinitionRequired();
7797       Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
7798     }
7799   }
7800   return false;
7801 }
7802 
7803 bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) {
7804   llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
7805   if (!Suggested)
7806     return false;
7807 
7808   // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
7809   // and isolate from other C++ specific checks.
7810   StructuralEquivalenceContext Ctx(
7811       D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls,
7812       StructuralEquivalenceKind::Default,
7813       false /*StrictTypeSpelling*/, true /*Complain*/,
7814       true /*ErrorOnTagTypeMismatch*/);
7815   return Ctx.IsEquivalent(D, Suggested);
7816 }
7817 
7818 /// Determine whether there is any declaration of \p D that was ever a
7819 ///        definition (perhaps before module merging) and is currently visible.
7820 /// \param D The definition of the entity.
7821 /// \param Suggested Filled in with the declaration that should be made visible
7822 ///        in order to provide a definition of this entity.
7823 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
7824 ///        not defined. This only matters for enums with a fixed underlying
7825 ///        type, since in all other cases, a type is complete if and only if it
7826 ///        is defined.
7827 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
7828                                 bool OnlyNeedComplete) {
7829   // Easy case: if we don't have modules, all declarations are visible.
7830   if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
7831     return true;
7832 
7833   // If this definition was instantiated from a template, map back to the
7834   // pattern from which it was instantiated.
7835   if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
7836     // We're in the middle of defining it; this definition should be treated
7837     // as visible.
7838     return true;
7839   } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
7840     if (auto *Pattern = RD->getTemplateInstantiationPattern())
7841       RD = Pattern;
7842     D = RD->getDefinition();
7843   } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
7844     if (auto *Pattern = ED->getTemplateInstantiationPattern())
7845       ED = Pattern;
7846     if (OnlyNeedComplete && ED->isFixed()) {
7847       // If the enum has a fixed underlying type, and we're only looking for a
7848       // complete type (not a definition), any visible declaration of it will
7849       // do.
7850       *Suggested = nullptr;
7851       for (auto *Redecl : ED->redecls()) {
7852         if (isVisible(Redecl))
7853           return true;
7854         if (Redecl->isThisDeclarationADefinition() ||
7855             (Redecl->isCanonicalDecl() && !*Suggested))
7856           *Suggested = Redecl;
7857       }
7858       return false;
7859     }
7860     D = ED->getDefinition();
7861   } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7862     if (auto *Pattern = FD->getTemplateInstantiationPattern())
7863       FD = Pattern;
7864     D = FD->getDefinition();
7865   } else if (auto *VD = dyn_cast<VarDecl>(D)) {
7866     if (auto *Pattern = VD->getTemplateInstantiationPattern())
7867       VD = Pattern;
7868     D = VD->getDefinition();
7869   }
7870   assert(D && "missing definition for pattern of instantiated definition");
7871 
7872   *Suggested = D;
7873 
7874   auto DefinitionIsVisible = [&] {
7875     // The (primary) definition might be in a visible module.
7876     if (isVisible(D))
7877       return true;
7878 
7879     // A visible module might have a merged definition instead.
7880     if (D->isModulePrivate() ? hasMergedDefinitionInCurrentModule(D)
7881                              : hasVisibleMergedDefinition(D)) {
7882       if (CodeSynthesisContexts.empty() &&
7883           !getLangOpts().ModulesLocalVisibility) {
7884         // Cache the fact that this definition is implicitly visible because
7885         // there is a visible merged definition.
7886         D->setVisibleDespiteOwningModule();
7887       }
7888       return true;
7889     }
7890 
7891     return false;
7892   };
7893 
7894   if (DefinitionIsVisible())
7895     return true;
7896 
7897   // The external source may have additional definitions of this entity that are
7898   // visible, so complete the redeclaration chain now and ask again.
7899   if (auto *Source = Context.getExternalSource()) {
7900     Source->CompleteRedeclChain(D);
7901     return DefinitionIsVisible();
7902   }
7903 
7904   return false;
7905 }
7906 
7907 /// Locks in the inheritance model for the given class and all of its bases.
7908 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
7909   RD = RD->getMostRecentNonInjectedDecl();
7910   if (!RD->hasAttr<MSInheritanceAttr>()) {
7911     MSInheritanceAttr::Spelling IM;
7912 
7913     switch (S.MSPointerToMemberRepresentationMethod) {
7914     case LangOptions::PPTMK_BestCase:
7915       IM = RD->calculateInheritanceModel();
7916       break;
7917     case LangOptions::PPTMK_FullGeneralitySingleInheritance:
7918       IM = MSInheritanceAttr::Keyword_single_inheritance;
7919       break;
7920     case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
7921       IM = MSInheritanceAttr::Keyword_multiple_inheritance;
7922       break;
7923     case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
7924       IM = MSInheritanceAttr::Keyword_unspecified_inheritance;
7925       break;
7926     }
7927 
7928     SourceRange Loc =
7929     S.ImplicitMSInheritanceAttrLoc.isValid()
7930                                  ? S.ImplicitMSInheritanceAttrLoc
7931                                  : RD->getSourceRange();
7932   RD->addAttr(MSInheritanceAttr::CreateImplicit(
7933       S.getASTContext(),
7934       /*BestCase=*/S.MSPointerToMemberRepresentationMethod ==
7935           LangOptions::PPTMK_BestCase,
7936       Loc, AttributeCommonInfo::AS_Microsoft, IM));
7937   S.Consumer.AssignInheritanceModel(RD);
7938   }
7939 }
7940 
7941 /// The implementation of RequireCompleteType
7942 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
7943                                    TypeDiagnoser *Diagnoser) {
7944   // FIXME: Add this assertion to make sure we always get instantiation points.
7945   //  assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
7946   // FIXME: Add this assertion to help us flush out problems with
7947   // checking for dependent types and type-dependent expressions.
7948   //
7949   //  assert(!T->isDependentType() &&
7950   //         "Can't ask whether a dependent type is complete");
7951 
7952   if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
7953     if (!MPTy->getClass()->isDependentType()) {
7954       if (getLangOpts().CompleteMemberPointers &&
7955           !MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined() &&
7956           RequireCompleteType(Loc, QualType(MPTy->getClass(), 0),
7957                               diag::err_memptr_incomplete))
7958         return true;
7959 
7960       // We lock in the inheritance model once somebody has asked us to ensure
7961       // that a pointer-to-member type is complete.
7962       if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7963         (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
7964         assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
7965       }
7966     }
7967   }
7968 
7969   NamedDecl *Def = nullptr;
7970   bool Incomplete = T->isIncompleteType(&Def);
7971 
7972   // Check that any necessary explicit specializations are visible. For an
7973   // enum, we just need the declaration, so don't check this.
7974   if (Def && !isa<EnumDecl>(Def))
7975     checkSpecializationVisibility(Loc, Def);
7976 
7977   // If we have a complete type, we're done.
7978   if (!Incomplete) {
7979     // If we know about the definition but it is not visible, complain.
7980     NamedDecl *SuggestedDef = nullptr;
7981     if (Def &&
7982         !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) {
7983       // If the user is going to see an error here, recover by making the
7984       // definition visible.
7985       bool TreatAsComplete = Diagnoser && !isSFINAEContext();
7986       if (Diagnoser && SuggestedDef)
7987         diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition,
7988                               /*Recover*/TreatAsComplete);
7989       return !TreatAsComplete;
7990     } else if (Def && !TemplateInstCallbacks.empty()) {
7991       CodeSynthesisContext TempInst;
7992       TempInst.Kind = CodeSynthesisContext::Memoization;
7993       TempInst.Template = Def;
7994       TempInst.Entity = Def;
7995       TempInst.PointOfInstantiation = Loc;
7996       atTemplateBegin(TemplateInstCallbacks, *this, TempInst);
7997       atTemplateEnd(TemplateInstCallbacks, *this, TempInst);
7998     }
7999 
8000     return false;
8001   }
8002 
8003   TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def);
8004   ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def);
8005 
8006   // Give the external source a chance to provide a definition of the type.
8007   // This is kept separate from completing the redeclaration chain so that
8008   // external sources such as LLDB can avoid synthesizing a type definition
8009   // unless it's actually needed.
8010   if (Tag || IFace) {
8011     // Avoid diagnosing invalid decls as incomplete.
8012     if (Def->isInvalidDecl())
8013       return true;
8014 
8015     // Give the external AST source a chance to complete the type.
8016     if (auto *Source = Context.getExternalSource()) {
8017       if (Tag && Tag->hasExternalLexicalStorage())
8018           Source->CompleteType(Tag);
8019       if (IFace && IFace->hasExternalLexicalStorage())
8020           Source->CompleteType(IFace);
8021       // If the external source completed the type, go through the motions
8022       // again to ensure we're allowed to use the completed type.
8023       if (!T->isIncompleteType())
8024         return RequireCompleteTypeImpl(Loc, T, Diagnoser);
8025     }
8026   }
8027 
8028   // If we have a class template specialization or a class member of a
8029   // class template specialization, or an array with known size of such,
8030   // try to instantiate it.
8031   if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) {
8032     bool Instantiated = false;
8033     bool Diagnosed = false;
8034     if (RD->isDependentContext()) {
8035       // Don't try to instantiate a dependent class (eg, a member template of
8036       // an instantiated class template specialization).
8037       // FIXME: Can this ever happen?
8038     } else if (auto *ClassTemplateSpec =
8039             dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
8040       if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
8041         runWithSufficientStackSpace(Loc, [&] {
8042           Diagnosed = InstantiateClassTemplateSpecialization(
8043               Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
8044               /*Complain=*/Diagnoser);
8045         });
8046         Instantiated = true;
8047       }
8048     } else {
8049       CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass();
8050       if (!RD->isBeingDefined() && Pattern) {
8051         MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo();
8052         assert(MSI && "Missing member specialization information?");
8053         // This record was instantiated from a class within a template.
8054         if (MSI->getTemplateSpecializationKind() !=
8055             TSK_ExplicitSpecialization) {
8056           runWithSufficientStackSpace(Loc, [&] {
8057             Diagnosed = InstantiateClass(Loc, RD, Pattern,
8058                                          getTemplateInstantiationArgs(RD),
8059                                          TSK_ImplicitInstantiation,
8060                                          /*Complain=*/Diagnoser);
8061           });
8062           Instantiated = true;
8063         }
8064       }
8065     }
8066 
8067     if (Instantiated) {
8068       // Instantiate* might have already complained that the template is not
8069       // defined, if we asked it to.
8070       if (Diagnoser && Diagnosed)
8071         return true;
8072       // If we instantiated a definition, check that it's usable, even if
8073       // instantiation produced an error, so that repeated calls to this
8074       // function give consistent answers.
8075       if (!T->isIncompleteType())
8076         return RequireCompleteTypeImpl(Loc, T, Diagnoser);
8077     }
8078   }
8079 
8080   // FIXME: If we didn't instantiate a definition because of an explicit
8081   // specialization declaration, check that it's visible.
8082 
8083   if (!Diagnoser)
8084     return true;
8085 
8086   Diagnoser->diagnose(*this, Loc, T);
8087 
8088   // If the type was a forward declaration of a class/struct/union
8089   // type, produce a note.
8090   if (Tag && !Tag->isInvalidDecl())
8091     Diag(Tag->getLocation(),
8092          Tag->isBeingDefined() ? diag::note_type_being_defined
8093                                : diag::note_forward_declaration)
8094       << Context.getTagDeclType(Tag);
8095 
8096   // If the Objective-C class was a forward declaration, produce a note.
8097   if (IFace && !IFace->isInvalidDecl())
8098     Diag(IFace->getLocation(), diag::note_forward_class);
8099 
8100   // If we have external information that we can use to suggest a fix,
8101   // produce a note.
8102   if (ExternalSource)
8103     ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
8104 
8105   return true;
8106 }
8107 
8108 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
8109                                unsigned DiagID) {
8110   BoundTypeDiagnoser<> Diagnoser(DiagID);
8111   return RequireCompleteType(Loc, T, Diagnoser);
8112 }
8113 
8114 /// Get diagnostic %select index for tag kind for
8115 /// literal type diagnostic message.
8116 /// WARNING: Indexes apply to particular diagnostics only!
8117 ///
8118 /// \returns diagnostic %select index.
8119 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
8120   switch (Tag) {
8121   case TTK_Struct: return 0;
8122   case TTK_Interface: return 1;
8123   case TTK_Class:  return 2;
8124   default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
8125   }
8126 }
8127 
8128 /// Ensure that the type T is a literal type.
8129 ///
8130 /// This routine checks whether the type @p T is a literal type. If @p T is an
8131 /// incomplete type, an attempt is made to complete it. If @p T is a literal
8132 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
8133 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
8134 /// it the type @p T), along with notes explaining why the type is not a
8135 /// literal type, and returns true.
8136 ///
8137 /// @param Loc  The location in the source that the non-literal type
8138 /// diagnostic should refer to.
8139 ///
8140 /// @param T  The type that this routine is examining for literalness.
8141 ///
8142 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
8143 ///
8144 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
8145 /// @c false otherwise.
8146 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
8147                               TypeDiagnoser &Diagnoser) {
8148   assert(!T->isDependentType() && "type should not be dependent");
8149 
8150   QualType ElemType = Context.getBaseElementType(T);
8151   if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
8152       T->isLiteralType(Context))
8153     return false;
8154 
8155   Diagnoser.diagnose(*this, Loc, T);
8156 
8157   if (T->isVariableArrayType())
8158     return true;
8159 
8160   const RecordType *RT = ElemType->getAs<RecordType>();
8161   if (!RT)
8162     return true;
8163 
8164   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
8165 
8166   // A partially-defined class type can't be a literal type, because a literal
8167   // class type must have a trivial destructor (which can't be checked until
8168   // the class definition is complete).
8169   if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
8170     return true;
8171 
8172   // [expr.prim.lambda]p3:
8173   //   This class type is [not] a literal type.
8174   if (RD->isLambda() && !getLangOpts().CPlusPlus17) {
8175     Diag(RD->getLocation(), diag::note_non_literal_lambda);
8176     return true;
8177   }
8178 
8179   // If the class has virtual base classes, then it's not an aggregate, and
8180   // cannot have any constexpr constructors or a trivial default constructor,
8181   // so is non-literal. This is better to diagnose than the resulting absence
8182   // of constexpr constructors.
8183   if (RD->getNumVBases()) {
8184     Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
8185       << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
8186     for (const auto &I : RD->vbases())
8187       Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
8188           << I.getSourceRange();
8189   } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
8190              !RD->hasTrivialDefaultConstructor()) {
8191     Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
8192   } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
8193     for (const auto &I : RD->bases()) {
8194       if (!I.getType()->isLiteralType(Context)) {
8195         Diag(I.getBeginLoc(), diag::note_non_literal_base_class)
8196             << RD << I.getType() << I.getSourceRange();
8197         return true;
8198       }
8199     }
8200     for (const auto *I : RD->fields()) {
8201       if (!I->getType()->isLiteralType(Context) ||
8202           I->getType().isVolatileQualified()) {
8203         Diag(I->getLocation(), diag::note_non_literal_field)
8204           << RD << I << I->getType()
8205           << I->getType().isVolatileQualified();
8206         return true;
8207       }
8208     }
8209   } else if (!RD->hasTrivialDestructor()) {
8210     // All fields and bases are of literal types, so have trivial destructors.
8211     // If this class's destructor is non-trivial it must be user-declared.
8212     CXXDestructorDecl *Dtor = RD->getDestructor();
8213     assert(Dtor && "class has literal fields and bases but no dtor?");
8214     if (!Dtor)
8215       return true;
8216 
8217     Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
8218          diag::note_non_literal_user_provided_dtor :
8219          diag::note_non_literal_nontrivial_dtor) << RD;
8220     if (!Dtor->isUserProvided())
8221       SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI,
8222                              /*Diagnose*/true);
8223   }
8224 
8225   return true;
8226 }
8227 
8228 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
8229   BoundTypeDiagnoser<> Diagnoser(DiagID);
8230   return RequireLiteralType(Loc, T, Diagnoser);
8231 }
8232 
8233 /// Retrieve a version of the type 'T' that is elaborated by Keyword, qualified
8234 /// by the nested-name-specifier contained in SS, and that is (re)declared by
8235 /// OwnedTagDecl, which is nullptr if this is not a (re)declaration.
8236 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
8237                                  const CXXScopeSpec &SS, QualType T,
8238                                  TagDecl *OwnedTagDecl) {
8239   if (T.isNull())
8240     return T;
8241   NestedNameSpecifier *NNS;
8242   if (SS.isValid())
8243     NNS = SS.getScopeRep();
8244   else {
8245     if (Keyword == ETK_None)
8246       return T;
8247     NNS = nullptr;
8248   }
8249   return Context.getElaboratedType(Keyword, NNS, T, OwnedTagDecl);
8250 }
8251 
8252 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
8253   assert(!E->hasPlaceholderType() && "unexpected placeholder");
8254 
8255   if (!getLangOpts().CPlusPlus && E->refersToBitField())
8256     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2;
8257 
8258   if (!E->isTypeDependent()) {
8259     QualType T = E->getType();
8260     if (const TagType *TT = T->getAs<TagType>())
8261       DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
8262   }
8263   return Context.getTypeOfExprType(E);
8264 }
8265 
8266 /// getDecltypeForExpr - Given an expr, will return the decltype for
8267 /// that expression, according to the rules in C++11
8268 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
8269 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
8270   if (E->isTypeDependent())
8271     return S.Context.DependentTy;
8272 
8273   // C++11 [dcl.type.simple]p4:
8274   //   The type denoted by decltype(e) is defined as follows:
8275   //
8276   //     - if e is an unparenthesized id-expression or an unparenthesized class
8277   //       member access (5.2.5), decltype(e) is the type of the entity named
8278   //       by e. If there is no such entity, or if e names a set of overloaded
8279   //       functions, the program is ill-formed;
8280   //
8281   // We apply the same rules for Objective-C ivar and property references.
8282   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8283     const ValueDecl *VD = DRE->getDecl();
8284     return VD->getType();
8285   } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
8286     if (const ValueDecl *VD = ME->getMemberDecl())
8287       if (isa<FieldDecl>(VD) || isa<VarDecl>(VD))
8288         return VD->getType();
8289   } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
8290     return IR->getDecl()->getType();
8291   } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
8292     if (PR->isExplicitProperty())
8293       return PR->getExplicitProperty()->getType();
8294   } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) {
8295     return PE->getType();
8296   }
8297 
8298   // C++11 [expr.lambda.prim]p18:
8299   //   Every occurrence of decltype((x)) where x is a possibly
8300   //   parenthesized id-expression that names an entity of automatic
8301   //   storage duration is treated as if x were transformed into an
8302   //   access to a corresponding data member of the closure type that
8303   //   would have been declared if x were an odr-use of the denoted
8304   //   entity.
8305   using namespace sema;
8306   if (S.getCurLambda()) {
8307     if (isa<ParenExpr>(E)) {
8308       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
8309         if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
8310           QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
8311           if (!T.isNull())
8312             return S.Context.getLValueReferenceType(T);
8313         }
8314       }
8315     }
8316   }
8317 
8318 
8319   // C++11 [dcl.type.simple]p4:
8320   //   [...]
8321   QualType T = E->getType();
8322   switch (E->getValueKind()) {
8323   //     - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
8324   //       type of e;
8325   case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
8326   //     - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
8327   //       type of e;
8328   case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
8329   //  - otherwise, decltype(e) is the type of e.
8330   case VK_RValue: break;
8331   }
8332 
8333   return T;
8334 }
8335 
8336 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc,
8337                                  bool AsUnevaluated) {
8338   assert(!E->hasPlaceholderType() && "unexpected placeholder");
8339 
8340   if (AsUnevaluated && CodeSynthesisContexts.empty() &&
8341       E->HasSideEffects(Context, false)) {
8342     // The expression operand for decltype is in an unevaluated expression
8343     // context, so side effects could result in unintended consequences.
8344     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
8345   }
8346 
8347   return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
8348 }
8349 
8350 QualType Sema::BuildUnaryTransformType(QualType BaseType,
8351                                        UnaryTransformType::UTTKind UKind,
8352                                        SourceLocation Loc) {
8353   switch (UKind) {
8354   case UnaryTransformType::EnumUnderlyingType:
8355     if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
8356       Diag(Loc, diag::err_only_enums_have_underlying_types);
8357       return QualType();
8358     } else {
8359       QualType Underlying = BaseType;
8360       if (!BaseType->isDependentType()) {
8361         // The enum could be incomplete if we're parsing its definition or
8362         // recovering from an error.
8363         NamedDecl *FwdDecl = nullptr;
8364         if (BaseType->isIncompleteType(&FwdDecl)) {
8365           Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
8366           Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
8367           return QualType();
8368         }
8369 
8370         EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
8371         assert(ED && "EnumType has no EnumDecl");
8372 
8373         DiagnoseUseOfDecl(ED, Loc);
8374 
8375         Underlying = ED->getIntegerType();
8376         assert(!Underlying.isNull());
8377       }
8378       return Context.getUnaryTransformType(BaseType, Underlying,
8379                                         UnaryTransformType::EnumUnderlyingType);
8380     }
8381   }
8382   llvm_unreachable("unknown unary transform type");
8383 }
8384 
8385 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
8386   if (!T->isDependentType()) {
8387     // FIXME: It isn't entirely clear whether incomplete atomic types
8388     // are allowed or not; for simplicity, ban them for the moment.
8389     if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
8390       return QualType();
8391 
8392     int DisallowedKind = -1;
8393     if (T->isArrayType())
8394       DisallowedKind = 1;
8395     else if (T->isFunctionType())
8396       DisallowedKind = 2;
8397     else if (T->isReferenceType())
8398       DisallowedKind = 3;
8399     else if (T->isAtomicType())
8400       DisallowedKind = 4;
8401     else if (T.hasQualifiers())
8402       DisallowedKind = 5;
8403     else if (!T.isTriviallyCopyableType(Context))
8404       // Some other non-trivially-copyable type (probably a C++ class)
8405       DisallowedKind = 6;
8406 
8407     if (DisallowedKind != -1) {
8408       Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
8409       return QualType();
8410     }
8411 
8412     // FIXME: Do we need any handling for ARC here?
8413   }
8414 
8415   // Build the pointer type.
8416   return Context.getAtomicType(T);
8417 }
8418