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