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