]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaType.cpp
Merge ^/head r284644 through r284736.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Sema / SemaType.cpp
1 //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements type-related semantic analysis.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Sema/SemaInternal.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/TypeLoc.h"
24 #include "clang/AST/TypeLocVisitor.h"
25 #include "clang/Lex/Preprocessor.h"
26 #include "clang/Basic/PartialDiagnostic.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Parse/ParseDiagnostic.h"
30 #include "clang/Sema/DeclSpec.h"
31 #include "clang/Sema/DelayedDiagnostic.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "clang/Sema/Template.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallString.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() != Declarator::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 AttributeList &attr,
67                                      QualType type) {
68   TypeDiagSelector WhichType;
69   bool useExpansionLoc = true;
70   switch (attr.getKind()) {
71   case AttributeList::AT_ObjCGC:        WhichType = TDS_Pointer; break;
72   case AttributeList::AT_ObjCOwnership: WhichType = TDS_ObjCObjOrBlock; break;
73   default:
74     // Assume everything else was a function attribute.
75     WhichType = TDS_Function;
76     useExpansionLoc = false;
77     break;
78   }
79
80   SourceLocation loc = attr.getLoc();
81   StringRef name = attr.getName()->getName();
82
83   // The GC attributes are usually written with macros;  special-case them.
84   IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
85                                           : nullptr;
86   if (useExpansionLoc && loc.isMacroID() && II) {
87     if (II->isStr("strong")) {
88       if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
89     } else if (II->isStr("weak")) {
90       if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
91     }
92   }
93
94   S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
95     << type;
96 }
97
98 // objc_gc applies to Objective-C pointers or, otherwise, to the
99 // smallest available pointer type (i.e. 'void*' in 'void**').
100 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
101     case AttributeList::AT_ObjCGC: \
102     case AttributeList::AT_ObjCOwnership
103
104 // Function type attributes.
105 #define FUNCTION_TYPE_ATTRS_CASELIST \
106     case AttributeList::AT_NoReturn: \
107     case AttributeList::AT_CDecl: \
108     case AttributeList::AT_FastCall: \
109     case AttributeList::AT_StdCall: \
110     case AttributeList::AT_ThisCall: \
111     case AttributeList::AT_Pascal: \
112     case AttributeList::AT_VectorCall: \
113     case AttributeList::AT_MSABI: \
114     case AttributeList::AT_SysVABI: \
115     case AttributeList::AT_Regparm: \
116     case AttributeList::AT_Pcs: \
117     case AttributeList::AT_IntelOclBicc
118
119 // Microsoft-specific type qualifiers.
120 #define MS_TYPE_ATTRS_CASELIST  \
121     case AttributeList::AT_Ptr32: \
122     case AttributeList::AT_Ptr64: \
123     case AttributeList::AT_SPtr: \
124     case AttributeList::AT_UPtr
125
126 // Nullability qualifiers.
127 #define NULLABILITY_TYPE_ATTRS_CASELIST         \
128     case AttributeList::AT_TypeNonNull:         \
129     case AttributeList::AT_TypeNullable:        \
130     case AttributeList::AT_TypeNullUnspecified
131
132 namespace {
133   /// An object which stores processing state for the entire
134   /// GetTypeForDeclarator process.
135   class TypeProcessingState {
136     Sema &sema;
137
138     /// The declarator being processed.
139     Declarator &declarator;
140
141     /// The index of the declarator chunk we're currently processing.
142     /// May be the total number of valid chunks, indicating the
143     /// DeclSpec.
144     unsigned chunkIndex;
145
146     /// Whether there are non-trivial modifications to the decl spec.
147     bool trivial;
148
149     /// Whether we saved the attributes in the decl spec.
150     bool hasSavedAttrs;
151
152     /// The original set of attributes on the DeclSpec.
153     SmallVector<AttributeList*, 2> savedAttrs;
154
155     /// A list of attributes to diagnose the uselessness of when the
156     /// processing is complete.
157     SmallVector<AttributeList*, 2> ignoredTypeAttrs;
158
159   public:
160     TypeProcessingState(Sema &sema, Declarator &declarator)
161       : sema(sema), declarator(declarator),
162         chunkIndex(declarator.getNumTypeObjects()),
163         trivial(true), hasSavedAttrs(false) {}
164
165     Sema &getSema() const {
166       return sema;
167     }
168
169     Declarator &getDeclarator() const {
170       return declarator;
171     }
172
173     bool isProcessingDeclSpec() const {
174       return chunkIndex == declarator.getNumTypeObjects();
175     }
176
177     unsigned getCurrentChunkIndex() const {
178       return chunkIndex;
179     }
180
181     void setCurrentChunkIndex(unsigned idx) {
182       assert(idx <= declarator.getNumTypeObjects());
183       chunkIndex = idx;
184     }
185
186     AttributeList *&getCurrentAttrListRef() const {
187       if (isProcessingDeclSpec())
188         return getMutableDeclSpec().getAttributes().getListRef();
189       return declarator.getTypeObject(chunkIndex).getAttrListRef();
190     }
191
192     /// Save the current set of attributes on the DeclSpec.
193     void saveDeclSpecAttrs() {
194       // Don't try to save them multiple times.
195       if (hasSavedAttrs) return;
196
197       DeclSpec &spec = getMutableDeclSpec();
198       for (AttributeList *attr = spec.getAttributes().getList(); attr;
199              attr = attr->getNext())
200         savedAttrs.push_back(attr);
201       trivial &= savedAttrs.empty();
202       hasSavedAttrs = true;
203     }
204
205     /// Record that we had nowhere to put the given type attribute.
206     /// We will diagnose such attributes later.
207     void addIgnoredTypeAttr(AttributeList &attr) {
208       ignoredTypeAttrs.push_back(&attr);
209     }
210
211     /// Diagnose all the ignored type attributes, given that the
212     /// declarator worked out to the given type.
213     void diagnoseIgnoredTypeAttrs(QualType type) const {
214       for (SmallVectorImpl<AttributeList*>::const_iterator
215              i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end();
216            i != e; ++i)
217         diagnoseBadTypeAttribute(getSema(), **i, type);
218     }
219
220     ~TypeProcessingState() {
221       if (trivial) return;
222
223       restoreDeclSpecAttrs();
224     }
225
226   private:
227     DeclSpec &getMutableDeclSpec() const {
228       return const_cast<DeclSpec&>(declarator.getDeclSpec());
229     }
230
231     void restoreDeclSpecAttrs() {
232       assert(hasSavedAttrs);
233
234       if (savedAttrs.empty()) {
235         getMutableDeclSpec().getAttributes().set(nullptr);
236         return;
237       }
238
239       getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
240       for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
241         savedAttrs[i]->setNext(savedAttrs[i+1]);
242       savedAttrs.back()->setNext(nullptr);
243     }
244   };
245 }
246
247 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
248   attr.setNext(head);
249   head = &attr;
250 }
251
252 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
253   if (head == &attr) {
254     head = attr.getNext();
255     return;
256   }
257
258   AttributeList *cur = head;
259   while (true) {
260     assert(cur && cur->getNext() && "ran out of attrs?");
261     if (cur->getNext() == &attr) {
262       cur->setNext(attr.getNext());
263       return;
264     }
265     cur = cur->getNext();
266   }
267 }
268
269 static void moveAttrFromListToList(AttributeList &attr,
270                                    AttributeList *&fromList,
271                                    AttributeList *&toList) {
272   spliceAttrOutOfList(attr, fromList);
273   spliceAttrIntoList(attr, toList);
274 }
275
276 /// The location of a type attribute.
277 enum TypeAttrLocation {
278   /// The attribute is in the decl-specifier-seq.
279   TAL_DeclSpec,
280   /// The attribute is part of a DeclaratorChunk.
281   TAL_DeclChunk,
282   /// The attribute is immediately after the declaration's name.
283   TAL_DeclName
284 };
285
286 static void processTypeAttrs(TypeProcessingState &state,
287                              QualType &type, TypeAttrLocation TAL,
288                              AttributeList *attrs);
289
290 static bool handleFunctionTypeAttr(TypeProcessingState &state,
291                                    AttributeList &attr,
292                                    QualType &type);
293
294 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
295                                              AttributeList &attr,
296                                              QualType &type);
297
298 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
299                                  AttributeList &attr, QualType &type);
300
301 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
302                                        AttributeList &attr, QualType &type);
303
304 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
305                                       AttributeList &attr, QualType &type) {
306   if (attr.getKind() == AttributeList::AT_ObjCGC)
307     return handleObjCGCTypeAttr(state, attr, type);
308   assert(attr.getKind() == AttributeList::AT_ObjCOwnership);
309   return handleObjCOwnershipTypeAttr(state, attr, type);
310 }
311
312 /// Given the index of a declarator chunk, check whether that chunk
313 /// directly specifies the return type of a function and, if so, find
314 /// an appropriate place for it.
315 ///
316 /// \param i - a notional index which the search will start
317 ///   immediately inside
318 ///
319 /// \param onlyBlockPointers Whether we should only look into block
320 /// pointer types (vs. all pointer types).
321 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
322                                                 unsigned i,
323                                                 bool onlyBlockPointers) {
324   assert(i <= declarator.getNumTypeObjects());
325
326   DeclaratorChunk *result = nullptr;
327
328   // First, look inwards past parens for a function declarator.
329   for (; i != 0; --i) {
330     DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
331     switch (fnChunk.Kind) {
332     case DeclaratorChunk::Paren:
333       continue;
334
335     // If we find anything except a function, bail out.
336     case DeclaratorChunk::Pointer:
337     case DeclaratorChunk::BlockPointer:
338     case DeclaratorChunk::Array:
339     case DeclaratorChunk::Reference:
340     case DeclaratorChunk::MemberPointer:
341       return result;
342
343     // If we do find a function declarator, scan inwards from that,
344     // looking for a (block-)pointer declarator.
345     case DeclaratorChunk::Function:
346       for (--i; i != 0; --i) {
347         DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
348         switch (ptrChunk.Kind) {
349         case DeclaratorChunk::Paren:
350         case DeclaratorChunk::Array:
351         case DeclaratorChunk::Function:
352         case DeclaratorChunk::Reference:
353           continue;
354
355         case DeclaratorChunk::MemberPointer:
356         case DeclaratorChunk::Pointer:
357           if (onlyBlockPointers)
358             continue;
359
360           // fallthrough
361
362         case DeclaratorChunk::BlockPointer:
363           result = &ptrChunk;
364           goto continue_outer;
365         }
366         llvm_unreachable("bad declarator chunk kind");
367       }
368
369       // If we run out of declarators doing that, we're done.
370       return result;
371     }
372     llvm_unreachable("bad declarator chunk kind");
373
374     // Okay, reconsider from our new point.
375   continue_outer: ;
376   }
377
378   // Ran out of chunks, bail out.
379   return result;
380 }
381
382 /// Given that an objc_gc attribute was written somewhere on a
383 /// declaration *other* than on the declarator itself (for which, use
384 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
385 /// didn't apply in whatever position it was written in, try to move
386 /// it to a more appropriate position.
387 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
388                                           AttributeList &attr,
389                                           QualType type) {
390   Declarator &declarator = state.getDeclarator();
391
392   // Move it to the outermost normal or block pointer declarator.
393   for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
394     DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
395     switch (chunk.Kind) {
396     case DeclaratorChunk::Pointer:
397     case DeclaratorChunk::BlockPointer: {
398       // But don't move an ARC ownership attribute to the return type
399       // of a block.
400       DeclaratorChunk *destChunk = nullptr;
401       if (state.isProcessingDeclSpec() &&
402           attr.getKind() == AttributeList::AT_ObjCOwnership)
403         destChunk = maybeMovePastReturnType(declarator, i - 1,
404                                             /*onlyBlockPointers=*/true);
405       if (!destChunk) destChunk = &chunk;
406
407       moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
408                              destChunk->getAttrListRef());
409       return;
410     }
411
412     case DeclaratorChunk::Paren:
413     case DeclaratorChunk::Array:
414       continue;
415
416     // We may be starting at the return type of a block.
417     case DeclaratorChunk::Function:
418       if (state.isProcessingDeclSpec() &&
419           attr.getKind() == AttributeList::AT_ObjCOwnership) {
420         if (DeclaratorChunk *dest = maybeMovePastReturnType(
421                                       declarator, i,
422                                       /*onlyBlockPointers=*/true)) {
423           moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
424                                  dest->getAttrListRef());
425           return;
426         }
427       }
428       goto error;
429
430     // Don't walk through these.
431     case DeclaratorChunk::Reference:
432     case DeclaratorChunk::MemberPointer:
433       goto error;
434     }
435   }
436  error:
437
438   diagnoseBadTypeAttribute(state.getSema(), attr, type);
439 }
440
441 /// Distribute an objc_gc type attribute that was written on the
442 /// declarator.
443 static void
444 distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
445                                             AttributeList &attr,
446                                             QualType &declSpecType) {
447   Declarator &declarator = state.getDeclarator();
448
449   // objc_gc goes on the innermost pointer to something that's not a
450   // pointer.
451   unsigned innermost = -1U;
452   bool considerDeclSpec = true;
453   for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
454     DeclaratorChunk &chunk = declarator.getTypeObject(i);
455     switch (chunk.Kind) {
456     case DeclaratorChunk::Pointer:
457     case DeclaratorChunk::BlockPointer:
458       innermost = i;
459       continue;
460
461     case DeclaratorChunk::Reference:
462     case DeclaratorChunk::MemberPointer:
463     case DeclaratorChunk::Paren:
464     case DeclaratorChunk::Array:
465       continue;
466
467     case DeclaratorChunk::Function:
468       considerDeclSpec = false;
469       goto done;
470     }
471   }
472  done:
473
474   // That might actually be the decl spec if we weren't blocked by
475   // anything in the declarator.
476   if (considerDeclSpec) {
477     if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
478       // Splice the attribute into the decl spec.  Prevents the
479       // attribute from being applied multiple times and gives
480       // the source-location-filler something to work with.
481       state.saveDeclSpecAttrs();
482       moveAttrFromListToList(attr, declarator.getAttrListRef(),
483                declarator.getMutableDeclSpec().getAttributes().getListRef());
484       return;
485     }
486   }
487
488   // Otherwise, if we found an appropriate chunk, splice the attribute
489   // into it.
490   if (innermost != -1U) {
491     moveAttrFromListToList(attr, declarator.getAttrListRef(),
492                        declarator.getTypeObject(innermost).getAttrListRef());
493     return;
494   }
495
496   // Otherwise, diagnose when we're done building the type.
497   spliceAttrOutOfList(attr, declarator.getAttrListRef());
498   state.addIgnoredTypeAttr(attr);
499 }
500
501 /// A function type attribute was written somewhere in a declaration
502 /// *other* than on the declarator itself or in the decl spec.  Given
503 /// that it didn't apply in whatever position it was written in, try
504 /// to move it to a more appropriate position.
505 static void distributeFunctionTypeAttr(TypeProcessingState &state,
506                                        AttributeList &attr,
507                                        QualType type) {
508   Declarator &declarator = state.getDeclarator();
509
510   // Try to push the attribute from the return type of a function to
511   // the function itself.
512   for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
513     DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
514     switch (chunk.Kind) {
515     case DeclaratorChunk::Function:
516       moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
517                              chunk.getAttrListRef());
518       return;
519
520     case DeclaratorChunk::Paren:
521     case DeclaratorChunk::Pointer:
522     case DeclaratorChunk::BlockPointer:
523     case DeclaratorChunk::Array:
524     case DeclaratorChunk::Reference:
525     case DeclaratorChunk::MemberPointer:
526       continue;
527     }
528   }
529
530   diagnoseBadTypeAttribute(state.getSema(), attr, type);
531 }
532
533 /// Try to distribute a function type attribute to the innermost
534 /// function chunk or type.  Returns true if the attribute was
535 /// distributed, false if no location was found.
536 static bool
537 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
538                                       AttributeList &attr,
539                                       AttributeList *&attrList,
540                                       QualType &declSpecType) {
541   Declarator &declarator = state.getDeclarator();
542
543   // Put it on the innermost function chunk, if there is one.
544   for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
545     DeclaratorChunk &chunk = declarator.getTypeObject(i);
546     if (chunk.Kind != DeclaratorChunk::Function) continue;
547
548     moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
549     return true;
550   }
551
552   return handleFunctionTypeAttr(state, attr, declSpecType);
553 }
554
555 /// A function type attribute was written in the decl spec.  Try to
556 /// apply it somewhere.
557 static void
558 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
559                                        AttributeList &attr,
560                                        QualType &declSpecType) {
561   state.saveDeclSpecAttrs();
562
563   // C++11 attributes before the decl specifiers actually appertain to
564   // the declarators. Move them straight there. We don't support the
565   // 'put them wherever you like' semantics we allow for GNU attributes.
566   if (attr.isCXX11Attribute()) {
567     moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
568                            state.getDeclarator().getAttrListRef());
569     return;
570   }
571
572   // Try to distribute to the innermost.
573   if (distributeFunctionTypeAttrToInnermost(state, attr,
574                                             state.getCurrentAttrListRef(),
575                                             declSpecType))
576     return;
577
578   // If that failed, diagnose the bad attribute when the declarator is
579   // fully built.
580   state.addIgnoredTypeAttr(attr);
581 }
582
583 /// A function type attribute was written on the declarator.  Try to
584 /// apply it somewhere.
585 static void
586 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
587                                          AttributeList &attr,
588                                          QualType &declSpecType) {
589   Declarator &declarator = state.getDeclarator();
590
591   // Try to distribute to the innermost.
592   if (distributeFunctionTypeAttrToInnermost(state, attr,
593                                             declarator.getAttrListRef(),
594                                             declSpecType))
595     return;
596
597   // If that failed, diagnose the bad attribute when the declarator is
598   // fully built.
599   spliceAttrOutOfList(attr, declarator.getAttrListRef());
600   state.addIgnoredTypeAttr(attr);
601 }
602
603 /// \brief Given that there are attributes written on the declarator
604 /// itself, try to distribute any type attributes to the appropriate
605 /// declarator chunk.
606 ///
607 /// These are attributes like the following:
608 ///   int f ATTR;
609 ///   int (f ATTR)();
610 /// but not necessarily this:
611 ///   int f() ATTR;
612 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
613                                               QualType &declSpecType) {
614   // Collect all the type attributes from the declarator itself.
615   assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
616   AttributeList *attr = state.getDeclarator().getAttributes();
617   AttributeList *next;
618   do {
619     next = attr->getNext();
620
621     // Do not distribute C++11 attributes. They have strict rules for what
622     // they appertain to.
623     if (attr->isCXX11Attribute())
624       continue;
625
626     switch (attr->getKind()) {
627     OBJC_POINTER_TYPE_ATTRS_CASELIST:
628       distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
629       break;
630
631     case AttributeList::AT_NSReturnsRetained:
632       if (!state.getSema().getLangOpts().ObjCAutoRefCount)
633         break;
634       // fallthrough
635
636     FUNCTION_TYPE_ATTRS_CASELIST:
637       distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
638       break;
639
640     MS_TYPE_ATTRS_CASELIST:
641       // Microsoft type attributes cannot go after the declarator-id.
642       continue;
643
644     NULLABILITY_TYPE_ATTRS_CASELIST:
645       // Nullability specifiers cannot go after the declarator-id.
646       continue;
647
648     default:
649       break;
650     }
651   } while ((attr = next));
652 }
653
654 /// Add a synthetic '()' to a block-literal declarator if it is
655 /// required, given the return type.
656 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
657                                           QualType declSpecType) {
658   Declarator &declarator = state.getDeclarator();
659
660   // First, check whether the declarator would produce a function,
661   // i.e. whether the innermost semantic chunk is a function.
662   if (declarator.isFunctionDeclarator()) {
663     // If so, make that declarator a prototyped declarator.
664     declarator.getFunctionTypeInfo().hasPrototype = true;
665     return;
666   }
667
668   // If there are any type objects, the type as written won't name a
669   // function, regardless of the decl spec type.  This is because a
670   // block signature declarator is always an abstract-declarator, and
671   // abstract-declarators can't just be parentheses chunks.  Therefore
672   // we need to build a function chunk unless there are no type
673   // objects and the decl spec type is a function.
674   if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
675     return;
676
677   // Note that there *are* cases with invalid declarators where
678   // declarators consist solely of parentheses.  In general, these
679   // occur only in failed efforts to make function declarators, so
680   // faking up the function chunk is still the right thing to do.
681
682   // Otherwise, we need to fake up a function declarator.
683   SourceLocation loc = declarator.getLocStart();
684
685   // ...and *prepend* it to the declarator.
686   SourceLocation NoLoc;
687   declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
688       /*HasProto=*/true,
689       /*IsAmbiguous=*/false,
690       /*LParenLoc=*/NoLoc,
691       /*ArgInfo=*/nullptr,
692       /*NumArgs=*/0,
693       /*EllipsisLoc=*/NoLoc,
694       /*RParenLoc=*/NoLoc,
695       /*TypeQuals=*/0,
696       /*RefQualifierIsLvalueRef=*/true,
697       /*RefQualifierLoc=*/NoLoc,
698       /*ConstQualifierLoc=*/NoLoc,
699       /*VolatileQualifierLoc=*/NoLoc,
700       /*RestrictQualifierLoc=*/NoLoc,
701       /*MutableLoc=*/NoLoc, EST_None,
702       /*ESpecLoc=*/NoLoc,
703       /*Exceptions=*/nullptr,
704       /*ExceptionRanges=*/nullptr,
705       /*NumExceptions=*/0,
706       /*NoexceptExpr=*/nullptr,
707       /*ExceptionSpecTokens=*/nullptr,
708       loc, loc, declarator));
709
710   // For consistency, make sure the state still has us as processing
711   // the decl spec.
712   assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
713   state.setCurrentChunkIndex(declarator.getNumTypeObjects());
714 }
715
716 static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
717                                             unsigned &TypeQuals,
718                                             QualType TypeSoFar,
719                                             unsigned RemoveTQs,
720                                             unsigned DiagID) {
721   // If this occurs outside a template instantiation, warn the user about
722   // it; they probably didn't mean to specify a redundant qualifier.
723   typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
724   for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
725                        QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
726                        QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
727     if (!(RemoveTQs & Qual.first))
728       continue;
729
730     if (S.ActiveTemplateInstantiations.empty()) {
731       if (TypeQuals & Qual.first)
732         S.Diag(Qual.second, DiagID)
733           << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
734           << FixItHint::CreateRemoval(Qual.second);
735     }
736
737     TypeQuals &= ~Qual.first;
738   }
739 }
740
741 /// \brief Convert the specified declspec to the appropriate type
742 /// object.
743 /// \param state Specifies the declarator containing the declaration specifier
744 /// to be converted, along with other associated processing state.
745 /// \returns The type described by the declaration specifiers.  This function
746 /// never returns null.
747 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
748   // FIXME: Should move the logic from DeclSpec::Finish to here for validity
749   // checking.
750
751   Sema &S = state.getSema();
752   Declarator &declarator = state.getDeclarator();
753   const DeclSpec &DS = declarator.getDeclSpec();
754   SourceLocation DeclLoc = declarator.getIdentifierLoc();
755   if (DeclLoc.isInvalid())
756     DeclLoc = DS.getLocStart();
757
758   ASTContext &Context = S.Context;
759
760   QualType Result;
761   switch (DS.getTypeSpecType()) {
762   case DeclSpec::TST_void:
763     Result = Context.VoidTy;
764     break;
765   case DeclSpec::TST_char:
766     if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
767       Result = Context.CharTy;
768     else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
769       Result = Context.SignedCharTy;
770     else {
771       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
772              "Unknown TSS value");
773       Result = Context.UnsignedCharTy;
774     }
775     break;
776   case DeclSpec::TST_wchar:
777     if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
778       Result = Context.WCharTy;
779     else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
780       S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
781         << DS.getSpecifierName(DS.getTypeSpecType(),
782                                Context.getPrintingPolicy());
783       Result = Context.getSignedWCharType();
784     } else {
785       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
786         "Unknown TSS value");
787       S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
788         << DS.getSpecifierName(DS.getTypeSpecType(),
789                                Context.getPrintingPolicy());
790       Result = Context.getUnsignedWCharType();
791     }
792     break;
793   case DeclSpec::TST_char16:
794       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
795         "Unknown TSS value");
796       Result = Context.Char16Ty;
797     break;
798   case DeclSpec::TST_char32:
799       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
800         "Unknown TSS value");
801       Result = Context.Char32Ty;
802     break;
803   case DeclSpec::TST_unspecified:
804     // "<proto1,proto2>" is an objc qualified ID with a missing id.
805     if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
806       Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
807                                          (ObjCProtocolDecl*const*)PQ,
808                                          DS.getNumProtocolQualifiers());
809       Result = Context.getObjCObjectPointerType(Result);
810       break;
811     }
812
813     // If this is a missing declspec in a block literal return context, then it
814     // is inferred from the return statements inside the block.
815     // The declspec is always missing in a lambda expr context; it is either
816     // specified with a trailing return type or inferred.
817     if (S.getLangOpts().CPlusPlus14 &&
818         declarator.getContext() == Declarator::LambdaExprContext) {
819       // In C++1y, a lambda's implicit return type is 'auto'.
820       Result = Context.getAutoDeductType();
821       break;
822     } else if (declarator.getContext() == Declarator::LambdaExprContext ||
823                isOmittedBlockReturnType(declarator)) {
824       Result = Context.DependentTy;
825       break;
826     }
827
828     // Unspecified typespec defaults to int in C90.  However, the C90 grammar
829     // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
830     // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
831     // Note that the one exception to this is function definitions, which are
832     // allowed to be completely missing a declspec.  This is handled in the
833     // parser already though by it pretending to have seen an 'int' in this
834     // case.
835     if (S.getLangOpts().ImplicitInt) {
836       // In C89 mode, we only warn if there is a completely missing declspec
837       // when one is not allowed.
838       if (DS.isEmpty()) {
839         S.Diag(DeclLoc, diag::ext_missing_declspec)
840           << DS.getSourceRange()
841         << FixItHint::CreateInsertion(DS.getLocStart(), "int");
842       }
843     } else if (!DS.hasTypeSpecifier()) {
844       // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
845       // "At least one type specifier shall be given in the declaration
846       // specifiers in each declaration, and in the specifier-qualifier list in
847       // each struct declaration and type name."
848       if (S.getLangOpts().CPlusPlus) {
849         S.Diag(DeclLoc, diag::err_missing_type_specifier)
850           << DS.getSourceRange();
851
852         // When this occurs in C++ code, often something is very broken with the
853         // value being declared, poison it as invalid so we don't get chains of
854         // errors.
855         declarator.setInvalidType(true);
856       } else {
857         S.Diag(DeclLoc, diag::ext_missing_type_specifier)
858           << DS.getSourceRange();
859       }
860     }
861
862     // FALL THROUGH.
863   case DeclSpec::TST_int: {
864     if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
865       switch (DS.getTypeSpecWidth()) {
866       case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
867       case DeclSpec::TSW_short:       Result = Context.ShortTy; break;
868       case DeclSpec::TSW_long:        Result = Context.LongTy; break;
869       case DeclSpec::TSW_longlong:
870         Result = Context.LongLongTy;
871
872         // 'long long' is a C99 or C++11 feature.
873         if (!S.getLangOpts().C99) {
874           if (S.getLangOpts().CPlusPlus)
875             S.Diag(DS.getTypeSpecWidthLoc(),
876                    S.getLangOpts().CPlusPlus11 ?
877                    diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
878           else
879             S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
880         }
881         break;
882       }
883     } else {
884       switch (DS.getTypeSpecWidth()) {
885       case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
886       case DeclSpec::TSW_short:       Result = Context.UnsignedShortTy; break;
887       case DeclSpec::TSW_long:        Result = Context.UnsignedLongTy; break;
888       case DeclSpec::TSW_longlong:
889         Result = Context.UnsignedLongLongTy;
890
891         // 'long long' is a C99 or C++11 feature.
892         if (!S.getLangOpts().C99) {
893           if (S.getLangOpts().CPlusPlus)
894             S.Diag(DS.getTypeSpecWidthLoc(),
895                    S.getLangOpts().CPlusPlus11 ?
896                    diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
897           else
898             S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
899         }
900         break;
901       }
902     }
903     break;
904   }
905   case DeclSpec::TST_int128:
906     if (!S.Context.getTargetInfo().hasInt128Type())
907       S.Diag(DS.getTypeSpecTypeLoc(), diag::err_int128_unsupported);
908     if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
909       Result = Context.UnsignedInt128Ty;
910     else
911       Result = Context.Int128Ty;
912     break;
913   case DeclSpec::TST_half: Result = Context.HalfTy; break;
914   case DeclSpec::TST_float: Result = Context.FloatTy; break;
915   case DeclSpec::TST_double:
916     if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
917       Result = Context.LongDoubleTy;
918     else
919       Result = Context.DoubleTy;
920
921     if (S.getLangOpts().OpenCL &&
922         !((S.getLangOpts().OpenCLVersion >= 120) ||
923           S.getOpenCLOptions().cl_khr_fp64)) {
924       S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
925           << Result << "cl_khr_fp64";
926       declarator.setInvalidType(true);
927     }
928     break;
929   case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
930   case DeclSpec::TST_decimal32:    // _Decimal32
931   case DeclSpec::TST_decimal64:    // _Decimal64
932   case DeclSpec::TST_decimal128:   // _Decimal128
933     S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
934     Result = Context.IntTy;
935     declarator.setInvalidType(true);
936     break;
937   case DeclSpec::TST_class:
938   case DeclSpec::TST_enum:
939   case DeclSpec::TST_union:
940   case DeclSpec::TST_struct:
941   case DeclSpec::TST_interface: {
942     TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
943     if (!D) {
944       // This can happen in C++ with ambiguous lookups.
945       Result = Context.IntTy;
946       declarator.setInvalidType(true);
947       break;
948     }
949
950     // If the type is deprecated or unavailable, diagnose it.
951     S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
952
953     assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
954            DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
955
956     // TypeQuals handled by caller.
957     Result = Context.getTypeDeclType(D);
958
959     // In both C and C++, make an ElaboratedType.
960     ElaboratedTypeKeyword Keyword
961       = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
962     Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
963     break;
964   }
965   case DeclSpec::TST_typename: {
966     assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
967            DS.getTypeSpecSign() == 0 &&
968            "Can't handle qualifiers on typedef names yet!");
969     Result = S.GetTypeFromParser(DS.getRepAsType());
970     if (Result.isNull())
971       declarator.setInvalidType(true);
972     else if (DeclSpec::ProtocolQualifierListTy PQ
973                = DS.getProtocolQualifiers()) {
974       if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
975         // Silently drop any existing protocol qualifiers.
976         // TODO: determine whether that's the right thing to do.
977         if (ObjT->getNumProtocols())
978           Result = ObjT->getBaseType();
979
980         if (DS.getNumProtocolQualifiers())
981           Result = Context.getObjCObjectType(Result,
982                                              (ObjCProtocolDecl*const*) PQ,
983                                              DS.getNumProtocolQualifiers());
984       } else if (Result->isObjCIdType()) {
985         // id<protocol-list>
986         Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
987                                            (ObjCProtocolDecl*const*) PQ,
988                                            DS.getNumProtocolQualifiers());
989         Result = Context.getObjCObjectPointerType(Result);
990       } else if (Result->isObjCClassType()) {
991         // Class<protocol-list>
992         Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
993                                            (ObjCProtocolDecl*const*) PQ,
994                                            DS.getNumProtocolQualifiers());
995         Result = Context.getObjCObjectPointerType(Result);
996       } else {
997         S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
998           << DS.getSourceRange();
999         declarator.setInvalidType(true);
1000       }
1001     } else if (S.getLangOpts().OpenCL) {
1002       if (const AtomicType *AT = Result->getAs<AtomicType>()) {
1003         const BuiltinType *BT = AT->getValueType()->getAs<BuiltinType>();
1004         bool NoExtTypes = BT && (BT->getKind() == BuiltinType::Int ||
1005                                  BT->getKind() == BuiltinType::UInt ||
1006                                  BT->getKind() == BuiltinType::Float);
1007         if (!S.getOpenCLOptions().cl_khr_int64_base_atomics && !NoExtTypes) {
1008           S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1009               << Result << "cl_khr_int64_base_atomics";
1010           declarator.setInvalidType(true);
1011         }
1012         if (!S.getOpenCLOptions().cl_khr_int64_extended_atomics &&
1013             !NoExtTypes) {
1014           S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1015               << Result << "cl_khr_int64_extended_atomics";
1016           declarator.setInvalidType(true);
1017         }
1018         if (!S.getOpenCLOptions().cl_khr_fp64 && BT &&
1019             BT->getKind() == BuiltinType::Double) {
1020           S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1021               << Result << "cl_khr_fp64";
1022           declarator.setInvalidType(true);
1023         }
1024       }
1025     }
1026
1027     // TypeQuals handled by caller.
1028     break;
1029   }
1030   case DeclSpec::TST_typeofType:
1031     // FIXME: Preserve type source info.
1032     Result = S.GetTypeFromParser(DS.getRepAsType());
1033     assert(!Result.isNull() && "Didn't get a type for typeof?");
1034     if (!Result->isDependentType())
1035       if (const TagType *TT = Result->getAs<TagType>())
1036         S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1037     // TypeQuals handled by caller.
1038     Result = Context.getTypeOfType(Result);
1039     break;
1040   case DeclSpec::TST_typeofExpr: {
1041     Expr *E = DS.getRepAsExpr();
1042     assert(E && "Didn't get an expression for typeof?");
1043     // TypeQuals handled by caller.
1044     Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
1045     if (Result.isNull()) {
1046       Result = Context.IntTy;
1047       declarator.setInvalidType(true);
1048     }
1049     break;
1050   }
1051   case DeclSpec::TST_decltype: {
1052     Expr *E = DS.getRepAsExpr();
1053     assert(E && "Didn't get an expression for decltype?");
1054     // TypeQuals handled by caller.
1055     Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
1056     if (Result.isNull()) {
1057       Result = Context.IntTy;
1058       declarator.setInvalidType(true);
1059     }
1060     break;
1061   }
1062   case DeclSpec::TST_underlyingType:
1063     Result = S.GetTypeFromParser(DS.getRepAsType());
1064     assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
1065     Result = S.BuildUnaryTransformType(Result,
1066                                        UnaryTransformType::EnumUnderlyingType,
1067                                        DS.getTypeSpecTypeLoc());
1068     if (Result.isNull()) {
1069       Result = Context.IntTy;
1070       declarator.setInvalidType(true);
1071     }
1072     break;
1073
1074   case DeclSpec::TST_auto:
1075     // TypeQuals handled by caller.
1076     // If auto is mentioned in a lambda parameter context, convert it to a 
1077     // template parameter type immediately, with the appropriate depth and 
1078     // index, and update sema's state (LambdaScopeInfo) for the current lambda 
1079     // being analyzed (which tracks the invented type template parameter).
1080     if (declarator.getContext() == Declarator::LambdaExprParameterContext) {
1081       sema::LambdaScopeInfo *LSI = S.getCurLambda();
1082       assert(LSI && "No LambdaScopeInfo on the stack!");
1083       const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
1084       const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size();
1085       const bool IsParameterPack = declarator.hasEllipsis();
1086
1087       // Turns out we must create the TemplateTypeParmDecl here to 
1088       // retrieve the corresponding template parameter type. 
1089       TemplateTypeParmDecl *CorrespondingTemplateParam =
1090         TemplateTypeParmDecl::Create(Context, 
1091         // Temporarily add to the TranslationUnit DeclContext.  When the 
1092         // associated TemplateParameterList is attached to a template
1093         // declaration (such as FunctionTemplateDecl), the DeclContext 
1094         // for each template parameter gets updated appropriately via
1095         // a call to AdoptTemplateParameterList. 
1096         Context.getTranslationUnitDecl(), 
1097         /*KeyLoc*/ SourceLocation(), 
1098         /*NameLoc*/ declarator.getLocStart(),  
1099         TemplateParameterDepth, 
1100         AutoParameterPosition,  // our template param index 
1101         /* Identifier*/ nullptr, false, IsParameterPack);
1102       LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam);
1103       // Replace the 'auto' in the function parameter with this invented 
1104       // template type parameter.
1105       Result = QualType(CorrespondingTemplateParam->getTypeForDecl(), 0);
1106     } else {
1107       Result = Context.getAutoType(QualType(), /*decltype(auto)*/false, false);
1108     }
1109     break;
1110
1111   case DeclSpec::TST_decltype_auto:
1112     Result = Context.getAutoType(QualType(), 
1113                                  /*decltype(auto)*/true, 
1114                                  /*IsDependent*/   false);
1115     break;
1116
1117   case DeclSpec::TST_unknown_anytype:
1118     Result = Context.UnknownAnyTy;
1119     break;
1120
1121   case DeclSpec::TST_atomic:
1122     Result = S.GetTypeFromParser(DS.getRepAsType());
1123     assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1124     Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1125     if (Result.isNull()) {
1126       Result = Context.IntTy;
1127       declarator.setInvalidType(true);
1128     }
1129     break;
1130
1131   case DeclSpec::TST_error:
1132     Result = Context.IntTy;
1133     declarator.setInvalidType(true);
1134     break;
1135   }
1136
1137   // Handle complex types.
1138   if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1139     if (S.getLangOpts().Freestanding)
1140       S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1141     Result = Context.getComplexType(Result);
1142   } else if (DS.isTypeAltiVecVector()) {
1143     unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1144     assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1145     VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1146     if (DS.isTypeAltiVecPixel())
1147       VecKind = VectorType::AltiVecPixel;
1148     else if (DS.isTypeAltiVecBool())
1149       VecKind = VectorType::AltiVecBool;
1150     Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1151   }
1152
1153   // FIXME: Imaginary.
1154   if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1155     S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1156
1157   // Before we process any type attributes, synthesize a block literal
1158   // function declarator if necessary.
1159   if (declarator.getContext() == Declarator::BlockLiteralContext)
1160     maybeSynthesizeBlockSignature(state, Result);
1161
1162   // Apply any type attributes from the decl spec.  This may cause the
1163   // list of type attributes to be temporarily saved while the type
1164   // attributes are pushed around.
1165   if (AttributeList *attrs = DS.getAttributes().getList())
1166     processTypeAttrs(state, Result, TAL_DeclSpec, attrs);
1167
1168   // Apply const/volatile/restrict qualifiers to T.
1169   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1170     // Warn about CV qualifiers on function types.
1171     // C99 6.7.3p8:
1172     //   If the specification of a function type includes any type qualifiers,
1173     //   the behavior is undefined.
1174     // C++11 [dcl.fct]p7:
1175     //   The effect of a cv-qualifier-seq in a function declarator is not the
1176     //   same as adding cv-qualification on top of the function type. In the
1177     //   latter case, the cv-qualifiers are ignored.
1178     if (TypeQuals && Result->isFunctionType()) {
1179       diagnoseAndRemoveTypeQualifiers(
1180           S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1181           S.getLangOpts().CPlusPlus
1182               ? diag::warn_typecheck_function_qualifiers_ignored
1183               : diag::warn_typecheck_function_qualifiers_unspecified);
1184       // No diagnostic for 'restrict' or '_Atomic' applied to a
1185       // function type; we'll diagnose those later, in BuildQualifiedType.
1186     }
1187
1188     // C++11 [dcl.ref]p1:
1189     //   Cv-qualified references are ill-formed except when the
1190     //   cv-qualifiers are introduced through the use of a typedef-name
1191     //   or decltype-specifier, in which case the cv-qualifiers are ignored.
1192     //
1193     // There don't appear to be any other contexts in which a cv-qualified
1194     // reference type could be formed, so the 'ill-formed' clause here appears
1195     // to never happen.
1196     if (TypeQuals && Result->isReferenceType()) {
1197       diagnoseAndRemoveTypeQualifiers(
1198           S, DS, TypeQuals, Result,
1199           DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1200           diag::warn_typecheck_reference_qualifiers);
1201     }
1202
1203     // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1204     // than once in the same specifier-list or qualifier-list, either directly
1205     // or via one or more typedefs."
1206     if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1207         && TypeQuals & Result.getCVRQualifiers()) {
1208       if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1209         S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1210           << "const";
1211       }
1212
1213       if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1214         S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1215           << "volatile";
1216       }
1217
1218       // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1219       // produce a warning in this case.
1220     }
1221
1222     QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1223
1224     // If adding qualifiers fails, just use the unqualified type.
1225     if (Qualified.isNull())
1226       declarator.setInvalidType(true);
1227     else
1228       Result = Qualified;
1229   }
1230
1231   assert(!Result.isNull() && "This function should not return a null type");
1232   return Result;
1233 }
1234
1235 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1236   if (Entity)
1237     return Entity.getAsString();
1238
1239   return "type name";
1240 }
1241
1242 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1243                                   Qualifiers Qs, const DeclSpec *DS) {
1244   if (T.isNull())
1245     return QualType();
1246
1247   // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1248   // object or incomplete types shall not be restrict-qualified."
1249   if (Qs.hasRestrict()) {
1250     unsigned DiagID = 0;
1251     QualType ProblemTy;
1252
1253     if (T->isAnyPointerType() || T->isReferenceType() ||
1254         T->isMemberPointerType()) {
1255       QualType EltTy;
1256       if (T->isObjCObjectPointerType())
1257         EltTy = T;
1258       else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1259         EltTy = PTy->getPointeeType();
1260       else
1261         EltTy = T->getPointeeType();
1262
1263       // If we have a pointer or reference, the pointee must have an object
1264       // incomplete type.
1265       if (!EltTy->isIncompleteOrObjectType()) {
1266         DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1267         ProblemTy = EltTy;
1268       }
1269     } else if (!T->isDependentType()) {
1270       DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1271       ProblemTy = T;
1272     }
1273
1274     if (DiagID) {
1275       Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1276       Qs.removeRestrict();
1277     }
1278   }
1279
1280   return Context.getQualifiedType(T, Qs);
1281 }
1282
1283 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1284                                   unsigned CVRA, const DeclSpec *DS) {
1285   if (T.isNull())
1286     return QualType();
1287
1288   // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic.
1289   unsigned CVR = CVRA & ~DeclSpec::TQ_atomic;
1290
1291   // C11 6.7.3/5:
1292   //   If the same qualifier appears more than once in the same
1293   //   specifier-qualifier-list, either directly or via one or more typedefs,
1294   //   the behavior is the same as if it appeared only once.
1295   //
1296   // It's not specified what happens when the _Atomic qualifier is applied to
1297   // a type specified with the _Atomic specifier, but we assume that this
1298   // should be treated as if the _Atomic qualifier appeared multiple times.
1299   if (CVRA & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1300     // C11 6.7.3/5:
1301     //   If other qualifiers appear along with the _Atomic qualifier in a
1302     //   specifier-qualifier-list, the resulting type is the so-qualified
1303     //   atomic type.
1304     //
1305     // Don't need to worry about array types here, since _Atomic can't be
1306     // applied to such types.
1307     SplitQualType Split = T.getSplitUnqualifiedType();
1308     T = BuildAtomicType(QualType(Split.Ty, 0),
1309                         DS ? DS->getAtomicSpecLoc() : Loc);
1310     if (T.isNull())
1311       return T;
1312     Split.Quals.addCVRQualifiers(CVR);
1313     return BuildQualifiedType(T, Loc, Split.Quals);
1314   }
1315
1316   return BuildQualifiedType(T, Loc, Qualifiers::fromCVRMask(CVR), DS);
1317 }
1318
1319 /// \brief Build a paren type including \p T.
1320 QualType Sema::BuildParenType(QualType T) {
1321   return Context.getParenType(T);
1322 }
1323
1324 /// Given that we're building a pointer or reference to the given
1325 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1326                                            SourceLocation loc,
1327                                            bool isReference) {
1328   // Bail out if retention is unrequired or already specified.
1329   if (!type->isObjCLifetimeType() ||
1330       type.getObjCLifetime() != Qualifiers::OCL_None)
1331     return type;
1332
1333   Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1334
1335   // If the object type is const-qualified, we can safely use
1336   // __unsafe_unretained.  This is safe (because there are no read
1337   // barriers), and it'll be safe to coerce anything but __weak* to
1338   // the resulting type.
1339   if (type.isConstQualified()) {
1340     implicitLifetime = Qualifiers::OCL_ExplicitNone;
1341
1342   // Otherwise, check whether the static type does not require
1343   // retaining.  This currently only triggers for Class (possibly
1344   // protocol-qualifed, and arrays thereof).
1345   } else if (type->isObjCARCImplicitlyUnretainedType()) {
1346     implicitLifetime = Qualifiers::OCL_ExplicitNone;
1347
1348   // If we are in an unevaluated context, like sizeof, skip adding a
1349   // qualification.
1350   } else if (S.isUnevaluatedContext()) {
1351     return type;
1352
1353   // If that failed, give an error and recover using __strong.  __strong
1354   // is the option most likely to prevent spurious second-order diagnostics,
1355   // like when binding a reference to a field.
1356   } else {
1357     // These types can show up in private ivars in system headers, so
1358     // we need this to not be an error in those cases.  Instead we
1359     // want to delay.
1360     if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1361       S.DelayedDiagnostics.add(
1362           sema::DelayedDiagnostic::makeForbiddenType(loc,
1363               diag::err_arc_indirect_no_ownership, type, isReference));
1364     } else {
1365       S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1366     }
1367     implicitLifetime = Qualifiers::OCL_Strong;
1368   }
1369   assert(implicitLifetime && "didn't infer any lifetime!");
1370
1371   Qualifiers qs;
1372   qs.addObjCLifetime(implicitLifetime);
1373   return S.Context.getQualifiedType(type, qs);
1374 }
1375
1376 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1377   std::string Quals =
1378     Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
1379
1380   switch (FnTy->getRefQualifier()) {
1381   case RQ_None:
1382     break;
1383
1384   case RQ_LValue:
1385     if (!Quals.empty())
1386       Quals += ' ';
1387     Quals += '&';
1388     break;
1389
1390   case RQ_RValue:
1391     if (!Quals.empty())
1392       Quals += ' ';
1393     Quals += "&&";
1394     break;
1395   }
1396
1397   return Quals;
1398 }
1399
1400 namespace {
1401 /// Kinds of declarator that cannot contain a qualified function type.
1402 ///
1403 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1404 ///     a function type with a cv-qualifier or a ref-qualifier can only appear
1405 ///     at the topmost level of a type.
1406 ///
1407 /// Parens and member pointers are permitted. We don't diagnose array and
1408 /// function declarators, because they don't allow function types at all.
1409 ///
1410 /// The values of this enum are used in diagnostics.
1411 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1412 }
1413
1414 /// Check whether the type T is a qualified function type, and if it is,
1415 /// diagnose that it cannot be contained within the given kind of declarator.
1416 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
1417                                    QualifiedFunctionKind QFK) {
1418   // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1419   const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1420   if (!FPT || (FPT->getTypeQuals() == 0 && FPT->getRefQualifier() == RQ_None))
1421     return false;
1422
1423   S.Diag(Loc, diag::err_compound_qualified_function_type)
1424     << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1425     << getFunctionQualifiersAsString(FPT);
1426   return true;
1427 }
1428
1429 /// \brief Build a pointer type.
1430 ///
1431 /// \param T The type to which we'll be building a pointer.
1432 ///
1433 /// \param Loc The location of the entity whose type involves this
1434 /// pointer type or, if there is no such entity, the location of the
1435 /// type that will have pointer type.
1436 ///
1437 /// \param Entity The name of the entity that involves the pointer
1438 /// type, if known.
1439 ///
1440 /// \returns A suitable pointer type, if there are no
1441 /// errors. Otherwise, returns a NULL type.
1442 QualType Sema::BuildPointerType(QualType T,
1443                                 SourceLocation Loc, DeclarationName Entity) {
1444   if (T->isReferenceType()) {
1445     // C++ 8.3.2p4: There shall be no ... pointers to references ...
1446     Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1447       << getPrintableNameForEntity(Entity) << T;
1448     return QualType();
1449   }
1450
1451   if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1452     return QualType();
1453
1454   assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1455
1456   // In ARC, it is forbidden to build pointers to unqualified pointers.
1457   if (getLangOpts().ObjCAutoRefCount)
1458     T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1459
1460   // Build the pointer type.
1461   return Context.getPointerType(T);
1462 }
1463
1464 /// \brief Build a reference type.
1465 ///
1466 /// \param T The type to which we'll be building a reference.
1467 ///
1468 /// \param Loc The location of the entity whose type involves this
1469 /// reference type or, if there is no such entity, the location of the
1470 /// type that will have reference type.
1471 ///
1472 /// \param Entity The name of the entity that involves the reference
1473 /// type, if known.
1474 ///
1475 /// \returns A suitable reference type, if there are no
1476 /// errors. Otherwise, returns a NULL type.
1477 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1478                                   SourceLocation Loc,
1479                                   DeclarationName Entity) {
1480   assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1481          "Unresolved overloaded function type");
1482
1483   // C++0x [dcl.ref]p6:
1484   //   If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1485   //   decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1486   //   type T, an attempt to create the type "lvalue reference to cv TR" creates
1487   //   the type "lvalue reference to T", while an attempt to create the type
1488   //   "rvalue reference to cv TR" creates the type TR.
1489   bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1490
1491   // C++ [dcl.ref]p4: There shall be no references to references.
1492   //
1493   // According to C++ DR 106, references to references are only
1494   // diagnosed when they are written directly (e.g., "int & &"),
1495   // but not when they happen via a typedef:
1496   //
1497   //   typedef int& intref;
1498   //   typedef intref& intref2;
1499   //
1500   // Parser::ParseDeclaratorInternal diagnoses the case where
1501   // references are written directly; here, we handle the
1502   // collapsing of references-to-references as described in C++0x.
1503   // DR 106 and 540 introduce reference-collapsing into C++98/03.
1504
1505   // C++ [dcl.ref]p1:
1506   //   A declarator that specifies the type "reference to cv void"
1507   //   is ill-formed.
1508   if (T->isVoidType()) {
1509     Diag(Loc, diag::err_reference_to_void);
1510     return QualType();
1511   }
1512
1513   if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
1514     return QualType();
1515
1516   // In ARC, it is forbidden to build references to unqualified pointers.
1517   if (getLangOpts().ObjCAutoRefCount)
1518     T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1519
1520   // Handle restrict on references.
1521   if (LValueRef)
1522     return Context.getLValueReferenceType(T, SpelledAsLValue);
1523   return Context.getRValueReferenceType(T);
1524 }
1525
1526 /// Check whether the specified array size makes the array type a VLA.  If so,
1527 /// return true, if not, return the size of the array in SizeVal.
1528 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
1529   // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
1530   // (like gnu99, but not c99) accept any evaluatable value as an extension.
1531   class VLADiagnoser : public Sema::VerifyICEDiagnoser {
1532   public:
1533     VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
1534
1535     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
1536     }
1537
1538     void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override {
1539       S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
1540     }
1541   } Diagnoser;
1542
1543   return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
1544                                            S.LangOpts.GNUMode).isInvalid();
1545 }
1546
1547
1548 /// \brief Build an array type.
1549 ///
1550 /// \param T The type of each element in the array.
1551 ///
1552 /// \param ASM C99 array size modifier (e.g., '*', 'static').
1553 ///
1554 /// \param ArraySize Expression describing the size of the array.
1555 ///
1556 /// \param Brackets The range from the opening '[' to the closing ']'.
1557 ///
1558 /// \param Entity The name of the entity that involves the array
1559 /// type, if known.
1560 ///
1561 /// \returns A suitable array type, if there are no errors. Otherwise,
1562 /// returns a NULL type.
1563 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1564                               Expr *ArraySize, unsigned Quals,
1565                               SourceRange Brackets, DeclarationName Entity) {
1566
1567   SourceLocation Loc = Brackets.getBegin();
1568   if (getLangOpts().CPlusPlus) {
1569     // C++ [dcl.array]p1:
1570     //   T is called the array element type; this type shall not be a reference
1571     //   type, the (possibly cv-qualified) type void, a function type or an
1572     //   abstract class type.
1573     //
1574     // C++ [dcl.array]p3:
1575     //   When several "array of" specifications are adjacent, [...] only the
1576     //   first of the constant expressions that specify the bounds of the arrays
1577     //   may be omitted.
1578     //
1579     // Note: function types are handled in the common path with C.
1580     if (T->isReferenceType()) {
1581       Diag(Loc, diag::err_illegal_decl_array_of_references)
1582       << getPrintableNameForEntity(Entity) << T;
1583       return QualType();
1584     }
1585
1586     if (T->isVoidType() || T->isIncompleteArrayType()) {
1587       Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
1588       return QualType();
1589     }
1590
1591     if (RequireNonAbstractType(Brackets.getBegin(), T,
1592                                diag::err_array_of_abstract_type))
1593       return QualType();
1594
1595     // Mentioning a member pointer type for an array type causes us to lock in
1596     // an inheritance model, even if it's inside an unused typedef.
1597     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
1598       if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
1599         if (!MPTy->getClass()->isDependentType())
1600           RequireCompleteType(Loc, T, 0);
1601
1602   } else {
1603     // C99 6.7.5.2p1: If the element type is an incomplete or function type,
1604     // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
1605     if (RequireCompleteType(Loc, T,
1606                             diag::err_illegal_decl_array_incomplete_type))
1607       return QualType();
1608   }
1609
1610   if (T->isFunctionType()) {
1611     Diag(Loc, diag::err_illegal_decl_array_of_functions)
1612       << getPrintableNameForEntity(Entity) << T;
1613     return QualType();
1614   }
1615
1616   if (const RecordType *EltTy = T->getAs<RecordType>()) {
1617     // If the element type is a struct or union that contains a variadic
1618     // array, accept it as a GNU extension: C99 6.7.2.1p2.
1619     if (EltTy->getDecl()->hasFlexibleArrayMember())
1620       Diag(Loc, diag::ext_flexible_array_in_array) << T;
1621   } else if (T->isObjCObjectType()) {
1622     Diag(Loc, diag::err_objc_array_of_interfaces) << T;
1623     return QualType();
1624   }
1625
1626   // Do placeholder conversions on the array size expression.
1627   if (ArraySize && ArraySize->hasPlaceholderType()) {
1628     ExprResult Result = CheckPlaceholderExpr(ArraySize);
1629     if (Result.isInvalid()) return QualType();
1630     ArraySize = Result.get();
1631   }
1632
1633   // Do lvalue-to-rvalue conversions on the array size expression.
1634   if (ArraySize && !ArraySize->isRValue()) {
1635     ExprResult Result = DefaultLvalueConversion(ArraySize);
1636     if (Result.isInvalid())
1637       return QualType();
1638
1639     ArraySize = Result.get();
1640   }
1641
1642   // C99 6.7.5.2p1: The size expression shall have integer type.
1643   // C++11 allows contextual conversions to such types.
1644   if (!getLangOpts().CPlusPlus11 &&
1645       ArraySize && !ArraySize->isTypeDependent() &&
1646       !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1647     Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1648       << ArraySize->getType() << ArraySize->getSourceRange();
1649     return QualType();
1650   }
1651
1652   llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
1653   if (!ArraySize) {
1654     if (ASM == ArrayType::Star)
1655       T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
1656     else
1657       T = Context.getIncompleteArrayType(T, ASM, Quals);
1658   } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
1659     T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
1660   } else if ((!T->isDependentType() && !T->isIncompleteType() &&
1661               !T->isConstantSizeType()) ||
1662              isArraySizeVLA(*this, ArraySize, ConstVal)) {
1663     // Even in C++11, don't allow contextual conversions in the array bound
1664     // of a VLA.
1665     if (getLangOpts().CPlusPlus11 &&
1666         !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1667       Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1668         << ArraySize->getType() << ArraySize->getSourceRange();
1669       return QualType();
1670     }
1671
1672     // C99: an array with an element type that has a non-constant-size is a VLA.
1673     // C99: an array with a non-ICE size is a VLA.  We accept any expression
1674     // that we can fold to a non-zero positive value as an extension.
1675     T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
1676   } else {
1677     // C99 6.7.5.2p1: If the expression is a constant expression, it shall
1678     // have a value greater than zero.
1679     if (ConstVal.isSigned() && ConstVal.isNegative()) {
1680       if (Entity)
1681         Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
1682           << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
1683       else
1684         Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
1685           << ArraySize->getSourceRange();
1686       return QualType();
1687     }
1688     if (ConstVal == 0) {
1689       // GCC accepts zero sized static arrays. We allow them when
1690       // we're not in a SFINAE context.
1691       Diag(ArraySize->getLocStart(),
1692            isSFINAEContext()? diag::err_typecheck_zero_array_size
1693                             : diag::ext_typecheck_zero_array_size)
1694         << ArraySize->getSourceRange();
1695
1696       if (ASM == ArrayType::Static) {
1697         Diag(ArraySize->getLocStart(),
1698              diag::warn_typecheck_zero_static_array_size)
1699           << ArraySize->getSourceRange();
1700         ASM = ArrayType::Normal;
1701       }
1702     } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
1703                !T->isIncompleteType() && !T->isUndeducedType()) {
1704       // Is the array too large?
1705       unsigned ActiveSizeBits
1706         = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
1707       if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
1708         Diag(ArraySize->getLocStart(), diag::err_array_too_large)
1709           << ConstVal.toString(10)
1710           << ArraySize->getSourceRange();
1711         return QualType();
1712       }
1713     }
1714
1715     T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
1716   }
1717
1718   // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
1719   if (getLangOpts().OpenCL && T->isVariableArrayType()) {
1720     Diag(Loc, diag::err_opencl_vla);
1721     return QualType();
1722   }
1723   // If this is not C99, extwarn about VLA's and C99 array size modifiers.
1724   if (!getLangOpts().C99) {
1725     if (T->isVariableArrayType()) {
1726       // Prohibit the use of non-POD types in VLAs.
1727       QualType BaseT = Context.getBaseElementType(T);
1728       if (!T->isDependentType() &&
1729           !RequireCompleteType(Loc, BaseT, 0) &&
1730           !BaseT.isPODType(Context) &&
1731           !BaseT->isObjCLifetimeType()) {
1732         Diag(Loc, diag::err_vla_non_pod)
1733           << BaseT;
1734         return QualType();
1735       }
1736       // Prohibit the use of VLAs during template argument deduction.
1737       else if (isSFINAEContext()) {
1738         Diag(Loc, diag::err_vla_in_sfinae);
1739         return QualType();
1740       }
1741       // Just extwarn about VLAs.
1742       else
1743         Diag(Loc, diag::ext_vla);
1744     } else if (ASM != ArrayType::Normal || Quals != 0)
1745       Diag(Loc,
1746            getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
1747                                      : diag::ext_c99_array_usage) << ASM;
1748   }
1749
1750   if (T->isVariableArrayType()) {
1751     // Warn about VLAs for -Wvla.
1752     Diag(Loc, diag::warn_vla_used);
1753   }
1754
1755   return T;
1756 }
1757
1758 /// \brief Build an ext-vector type.
1759 ///
1760 /// Run the required checks for the extended vector type.
1761 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
1762                                   SourceLocation AttrLoc) {
1763   // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1764   // in conjunction with complex types (pointers, arrays, functions, etc.).
1765   if (!T->isDependentType() &&
1766       !T->isIntegerType() && !T->isRealFloatingType()) {
1767     Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
1768     return QualType();
1769   }
1770
1771   if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
1772     llvm::APSInt vecSize(32);
1773     if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
1774       Diag(AttrLoc, diag::err_attribute_argument_type)
1775         << "ext_vector_type" << AANT_ArgumentIntegerConstant
1776         << ArraySize->getSourceRange();
1777       return QualType();
1778     }
1779
1780     // unlike gcc's vector_size attribute, the size is specified as the
1781     // number of elements, not the number of bytes.
1782     unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
1783
1784     if (vectorSize == 0) {
1785       Diag(AttrLoc, diag::err_attribute_zero_size)
1786       << ArraySize->getSourceRange();
1787       return QualType();
1788     }
1789
1790     if (VectorType::isVectorSizeTooLarge(vectorSize)) {
1791       Diag(AttrLoc, diag::err_attribute_size_too_large)
1792         << ArraySize->getSourceRange();
1793       return QualType();
1794     }
1795
1796     return Context.getExtVectorType(T, vectorSize);
1797   }
1798
1799   return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
1800 }
1801
1802 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
1803   if (T->isArrayType() || T->isFunctionType()) {
1804     Diag(Loc, diag::err_func_returning_array_function)
1805       << T->isFunctionType() << T;
1806     return true;
1807   }
1808
1809   // Functions cannot return half FP.
1810   if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
1811     Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
1812       FixItHint::CreateInsertion(Loc, "*");
1813     return true;
1814   }
1815
1816   // Methods cannot return interface types. All ObjC objects are
1817   // passed by reference.
1818   if (T->isObjCObjectType()) {
1819     Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) << 0 << T;
1820     return 0;
1821   }
1822
1823   return false;
1824 }
1825
1826 QualType Sema::BuildFunctionType(QualType T,
1827                                  MutableArrayRef<QualType> ParamTypes,
1828                                  SourceLocation Loc, DeclarationName Entity,
1829                                  const FunctionProtoType::ExtProtoInfo &EPI) {
1830   bool Invalid = false;
1831
1832   Invalid |= CheckFunctionReturnType(T, Loc);
1833
1834   for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
1835     // FIXME: Loc is too inprecise here, should use proper locations for args.
1836     QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
1837     if (ParamType->isVoidType()) {
1838       Diag(Loc, diag::err_param_with_void_type);
1839       Invalid = true;
1840     } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
1841       // Disallow half FP arguments.
1842       Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
1843         FixItHint::CreateInsertion(Loc, "*");
1844       Invalid = true;
1845     }
1846
1847     ParamTypes[Idx] = ParamType;
1848   }
1849
1850   if (Invalid)
1851     return QualType();
1852
1853   return Context.getFunctionType(T, ParamTypes, EPI);
1854 }
1855
1856 /// \brief Build a member pointer type \c T Class::*.
1857 ///
1858 /// \param T the type to which the member pointer refers.
1859 /// \param Class the class type into which the member pointer points.
1860 /// \param Loc the location where this type begins
1861 /// \param Entity the name of the entity that will have this member pointer type
1862 ///
1863 /// \returns a member pointer type, if successful, or a NULL type if there was
1864 /// an error.
1865 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
1866                                       SourceLocation Loc,
1867                                       DeclarationName Entity) {
1868   // Verify that we're not building a pointer to pointer to function with
1869   // exception specification.
1870   if (CheckDistantExceptionSpec(T)) {
1871     Diag(Loc, diag::err_distant_exception_spec);
1872     return QualType();
1873   }
1874
1875   // C++ 8.3.3p3: A pointer to member shall not point to ... a member
1876   //   with reference type, or "cv void."
1877   if (T->isReferenceType()) {
1878     Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
1879       << getPrintableNameForEntity(Entity) << T;
1880     return QualType();
1881   }
1882
1883   if (T->isVoidType()) {
1884     Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
1885       << getPrintableNameForEntity(Entity);
1886     return QualType();
1887   }
1888
1889   if (!Class->isDependentType() && !Class->isRecordType()) {
1890     Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
1891     return QualType();
1892   }
1893
1894   // Adjust the default free function calling convention to the default method
1895   // calling convention.
1896   if (T->isFunctionType())
1897     adjustMemberFunctionCC(T, /*IsStatic=*/false);
1898
1899   return Context.getMemberPointerType(T, Class.getTypePtr());
1900 }
1901
1902 /// \brief Build a block pointer type.
1903 ///
1904 /// \param T The type to which we'll be building a block pointer.
1905 ///
1906 /// \param Loc The source location, used for diagnostics.
1907 ///
1908 /// \param Entity The name of the entity that involves the block pointer
1909 /// type, if known.
1910 ///
1911 /// \returns A suitable block pointer type, if there are no
1912 /// errors. Otherwise, returns a NULL type.
1913 QualType Sema::BuildBlockPointerType(QualType T,
1914                                      SourceLocation Loc,
1915                                      DeclarationName Entity) {
1916   if (!T->isFunctionType()) {
1917     Diag(Loc, diag::err_nonfunction_block_type);
1918     return QualType();
1919   }
1920
1921   if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
1922     return QualType();
1923
1924   return Context.getBlockPointerType(T);
1925 }
1926
1927 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
1928   QualType QT = Ty.get();
1929   if (QT.isNull()) {
1930     if (TInfo) *TInfo = nullptr;
1931     return QualType();
1932   }
1933
1934   TypeSourceInfo *DI = nullptr;
1935   if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
1936     QT = LIT->getType();
1937     DI = LIT->getTypeSourceInfo();
1938   }
1939
1940   if (TInfo) *TInfo = DI;
1941   return QT;
1942 }
1943
1944 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
1945                                             Qualifiers::ObjCLifetime ownership,
1946                                             unsigned chunkIndex);
1947
1948 /// Given that this is the declaration of a parameter under ARC,
1949 /// attempt to infer attributes and such for pointer-to-whatever
1950 /// types.
1951 static void inferARCWriteback(TypeProcessingState &state,
1952                               QualType &declSpecType) {
1953   Sema &S = state.getSema();
1954   Declarator &declarator = state.getDeclarator();
1955
1956   // TODO: should we care about decl qualifiers?
1957
1958   // Check whether the declarator has the expected form.  We walk
1959   // from the inside out in order to make the block logic work.
1960   unsigned outermostPointerIndex = 0;
1961   bool isBlockPointer = false;
1962   unsigned numPointers = 0;
1963   for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
1964     unsigned chunkIndex = i;
1965     DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
1966     switch (chunk.Kind) {
1967     case DeclaratorChunk::Paren:
1968       // Ignore parens.
1969       break;
1970
1971     case DeclaratorChunk::Reference:
1972     case DeclaratorChunk::Pointer:
1973       // Count the number of pointers.  Treat references
1974       // interchangeably as pointers; if they're mis-ordered, normal
1975       // type building will discover that.
1976       outermostPointerIndex = chunkIndex;
1977       numPointers++;
1978       break;
1979
1980     case DeclaratorChunk::BlockPointer:
1981       // If we have a pointer to block pointer, that's an acceptable
1982       // indirect reference; anything else is not an application of
1983       // the rules.
1984       if (numPointers != 1) return;
1985       numPointers++;
1986       outermostPointerIndex = chunkIndex;
1987       isBlockPointer = true;
1988
1989       // We don't care about pointer structure in return values here.
1990       goto done;
1991
1992     case DeclaratorChunk::Array: // suppress if written (id[])?
1993     case DeclaratorChunk::Function:
1994     case DeclaratorChunk::MemberPointer:
1995       return;
1996     }
1997   }
1998  done:
1999
2000   // If we have *one* pointer, then we want to throw the qualifier on
2001   // the declaration-specifiers, which means that it needs to be a
2002   // retainable object type.
2003   if (numPointers == 1) {
2004     // If it's not a retainable object type, the rule doesn't apply.
2005     if (!declSpecType->isObjCRetainableType()) return;
2006
2007     // If it already has lifetime, don't do anything.
2008     if (declSpecType.getObjCLifetime()) return;
2009
2010     // Otherwise, modify the type in-place.
2011     Qualifiers qs;
2012
2013     if (declSpecType->isObjCARCImplicitlyUnretainedType())
2014       qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
2015     else
2016       qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
2017     declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2018
2019   // If we have *two* pointers, then we want to throw the qualifier on
2020   // the outermost pointer.
2021   } else if (numPointers == 2) {
2022     // If we don't have a block pointer, we need to check whether the
2023     // declaration-specifiers gave us something that will turn into a
2024     // retainable object pointer after we slap the first pointer on it.
2025     if (!isBlockPointer && !declSpecType->isObjCObjectType())
2026       return;
2027
2028     // Look for an explicit lifetime attribute there.
2029     DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2030     if (chunk.Kind != DeclaratorChunk::Pointer &&
2031         chunk.Kind != DeclaratorChunk::BlockPointer)
2032       return;
2033     for (const AttributeList *attr = chunk.getAttrs(); attr;
2034            attr = attr->getNext())
2035       if (attr->getKind() == AttributeList::AT_ObjCOwnership)
2036         return;
2037
2038     transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
2039                                           outermostPointerIndex);
2040
2041   // Any other number of pointers/references does not trigger the rule.
2042   } else return;
2043
2044   // TODO: mark whether we did this inference?
2045 }
2046
2047 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2048                                      SourceLocation FallbackLoc,
2049                                      SourceLocation ConstQualLoc,
2050                                      SourceLocation VolatileQualLoc,
2051                                      SourceLocation RestrictQualLoc,
2052                                      SourceLocation AtomicQualLoc) {
2053   if (!Quals)
2054     return;
2055
2056   struct Qual {
2057     unsigned Mask;
2058     const char *Name;
2059     SourceLocation Loc;
2060   } const QualKinds[4] = {
2061     { DeclSpec::TQ_const, "const", ConstQualLoc },
2062     { DeclSpec::TQ_volatile, "volatile", VolatileQualLoc },
2063     { DeclSpec::TQ_restrict, "restrict", RestrictQualLoc },
2064     { DeclSpec::TQ_atomic, "_Atomic", AtomicQualLoc }
2065   };
2066
2067   SmallString<32> QualStr;
2068   unsigned NumQuals = 0;
2069   SourceLocation Loc;
2070   FixItHint FixIts[4];
2071
2072   // Build a string naming the redundant qualifiers.
2073   for (unsigned I = 0; I != 4; ++I) {
2074     if (Quals & QualKinds[I].Mask) {
2075       if (!QualStr.empty()) QualStr += ' ';
2076       QualStr += QualKinds[I].Name;
2077
2078       // If we have a location for the qualifier, offer a fixit.
2079       SourceLocation QualLoc = QualKinds[I].Loc;
2080       if (!QualLoc.isInvalid()) {
2081         FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2082         if (Loc.isInvalid() ||
2083             getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2084           Loc = QualLoc;
2085       }
2086
2087       ++NumQuals;
2088     }
2089   }
2090
2091   Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2092     << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2093 }
2094
2095 // Diagnose pointless type qualifiers on the return type of a function.
2096 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
2097                                                   Declarator &D,
2098                                                   unsigned FunctionChunkIndex) {
2099   if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
2100     // FIXME: TypeSourceInfo doesn't preserve location information for
2101     // qualifiers.
2102     S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2103                                 RetTy.getLocalCVRQualifiers(),
2104                                 D.getIdentifierLoc());
2105     return;
2106   }
2107
2108   for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
2109                 End = D.getNumTypeObjects();
2110        OuterChunkIndex != End; ++OuterChunkIndex) {
2111     DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
2112     switch (OuterChunk.Kind) {
2113     case DeclaratorChunk::Paren:
2114       continue;
2115
2116     case DeclaratorChunk::Pointer: {
2117       DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
2118       S.diagnoseIgnoredQualifiers(
2119           diag::warn_qual_return_type,
2120           PTI.TypeQuals,
2121           SourceLocation(),
2122           SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2123           SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2124           SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
2125           SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc));
2126       return;
2127     }
2128
2129     case DeclaratorChunk::Function:
2130     case DeclaratorChunk::BlockPointer:
2131     case DeclaratorChunk::Reference:
2132     case DeclaratorChunk::Array:
2133     case DeclaratorChunk::MemberPointer:
2134       // FIXME: We can't currently provide an accurate source location and a
2135       // fix-it hint for these.
2136       unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
2137       S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2138                                   RetTy.getCVRQualifiers() | AtomicQual,
2139                                   D.getIdentifierLoc());
2140       return;
2141     }
2142
2143     llvm_unreachable("unknown declarator chunk kind");
2144   }
2145
2146   // If the qualifiers come from a conversion function type, don't diagnose
2147   // them -- they're not necessarily redundant, since such a conversion
2148   // operator can be explicitly called as "x.operator const int()".
2149   if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2150     return;
2151
2152   // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
2153   // which are present there.
2154   S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2155                               D.getDeclSpec().getTypeQualifiers(),
2156                               D.getIdentifierLoc(),
2157                               D.getDeclSpec().getConstSpecLoc(),
2158                               D.getDeclSpec().getVolatileSpecLoc(),
2159                               D.getDeclSpec().getRestrictSpecLoc(),
2160                               D.getDeclSpec().getAtomicSpecLoc());
2161 }
2162
2163 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
2164                                              TypeSourceInfo *&ReturnTypeInfo) {
2165   Sema &SemaRef = state.getSema();
2166   Declarator &D = state.getDeclarator();
2167   QualType T;
2168   ReturnTypeInfo = nullptr;
2169
2170   // The TagDecl owned by the DeclSpec.
2171   TagDecl *OwnedTagDecl = nullptr;
2172
2173   bool ContainsPlaceholderType = false;
2174
2175   switch (D.getName().getKind()) {
2176   case UnqualifiedId::IK_ImplicitSelfParam:
2177   case UnqualifiedId::IK_OperatorFunctionId:
2178   case UnqualifiedId::IK_Identifier:
2179   case UnqualifiedId::IK_LiteralOperatorId:
2180   case UnqualifiedId::IK_TemplateId:
2181     T = ConvertDeclSpecToType(state);
2182     ContainsPlaceholderType = D.getDeclSpec().containsPlaceholderType();
2183
2184     if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
2185       OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2186       // Owned declaration is embedded in declarator.
2187       OwnedTagDecl->setEmbeddedInDeclarator(true);
2188     }
2189     break;
2190
2191   case UnqualifiedId::IK_ConstructorName:
2192   case UnqualifiedId::IK_ConstructorTemplateId:
2193   case UnqualifiedId::IK_DestructorName:
2194     // Constructors and destructors don't have return types. Use
2195     // "void" instead.
2196     T = SemaRef.Context.VoidTy;
2197     if (AttributeList *attrs = D.getDeclSpec().getAttributes().getList())
2198       processTypeAttrs(state, T, TAL_DeclSpec, attrs);
2199     break;
2200
2201   case UnqualifiedId::IK_ConversionFunctionId:
2202     // The result type of a conversion function is the type that it
2203     // converts to.
2204     T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
2205                                   &ReturnTypeInfo);
2206     ContainsPlaceholderType = T->getContainedAutoType();
2207     break;
2208   }
2209
2210   if (D.getAttributes())
2211     distributeTypeAttrsFromDeclarator(state, T);
2212
2213   // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
2214   // In C++11, a function declarator using 'auto' must have a trailing return
2215   // type (this is checked later) and we can skip this. In other languages
2216   // using auto, we need to check regardless.
2217   // C++14 In generic lambdas allow 'auto' in their parameters.
2218   if (ContainsPlaceholderType &&
2219       (!SemaRef.getLangOpts().CPlusPlus11 || !D.isFunctionDeclarator())) {
2220     int Error = -1;
2221
2222     switch (D.getContext()) {
2223     case Declarator::KNRTypeListContext:
2224       llvm_unreachable("K&R type lists aren't allowed in C++");
2225     case Declarator::LambdaExprContext:
2226       llvm_unreachable("Can't specify a type specifier in lambda grammar");
2227     case Declarator::ObjCParameterContext:
2228     case Declarator::ObjCResultContext:
2229     case Declarator::PrototypeContext:
2230       Error = 0;  
2231       break;
2232     case Declarator::LambdaExprParameterContext:
2233       if (!(SemaRef.getLangOpts().CPlusPlus14 
2234               && D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto))
2235         Error = 14;
2236       break;
2237     case Declarator::MemberContext:
2238       if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
2239         break;
2240       switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
2241       case TTK_Enum: llvm_unreachable("unhandled tag kind");
2242       case TTK_Struct: Error = 1; /* Struct member */ break;
2243       case TTK_Union:  Error = 2; /* Union member */ break;
2244       case TTK_Class:  Error = 3; /* Class member */ break;
2245       case TTK_Interface: Error = 4; /* Interface member */ break;
2246       }
2247       break;
2248     case Declarator::CXXCatchContext:
2249     case Declarator::ObjCCatchContext:
2250       Error = 5; // Exception declaration
2251       break;
2252     case Declarator::TemplateParamContext:
2253       Error = 6; // Template parameter
2254       break;
2255     case Declarator::BlockLiteralContext:
2256       Error = 7; // Block literal
2257       break;
2258     case Declarator::TemplateTypeArgContext:
2259       Error = 8; // Template type argument
2260       break;
2261     case Declarator::AliasDeclContext:
2262     case Declarator::AliasTemplateContext:
2263       Error = 10; // Type alias
2264       break;
2265     case Declarator::TrailingReturnContext:
2266       if (!SemaRef.getLangOpts().CPlusPlus14)
2267         Error = 11; // Function return type
2268       break;
2269     case Declarator::ConversionIdContext:
2270       if (!SemaRef.getLangOpts().CPlusPlus14)
2271         Error = 12; // conversion-type-id
2272       break;
2273     case Declarator::TypeNameContext:
2274       Error = 13; // Generic
2275       break;
2276     case Declarator::FileContext:
2277     case Declarator::BlockContext:
2278     case Declarator::ForContext:
2279     case Declarator::ConditionContext:
2280     case Declarator::CXXNewContext:
2281       break;
2282     }
2283
2284     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2285       Error = 9;
2286
2287     // In Objective-C it is an error to use 'auto' on a function declarator.
2288     if (D.isFunctionDeclarator())
2289       Error = 11;
2290
2291     // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
2292     // contains a trailing return type. That is only legal at the outermost
2293     // level. Check all declarator chunks (outermost first) anyway, to give
2294     // better diagnostics.
2295     if (SemaRef.getLangOpts().CPlusPlus11 && Error != -1) {
2296       for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2297         unsigned chunkIndex = e - i - 1;
2298         state.setCurrentChunkIndex(chunkIndex);
2299         DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
2300         if (DeclType.Kind == DeclaratorChunk::Function) {
2301           const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2302           if (FTI.hasTrailingReturnType()) {
2303             Error = -1;
2304             break;
2305           }
2306         }
2307       }
2308     }
2309
2310     SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
2311     if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2312       AutoRange = D.getName().getSourceRange();
2313
2314     if (Error != -1) {
2315       const bool IsDeclTypeAuto = 
2316           D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_decltype_auto;
2317       SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
2318         << IsDeclTypeAuto << Error << AutoRange;
2319       T = SemaRef.Context.IntTy;
2320       D.setInvalidType(true);
2321     } else
2322       SemaRef.Diag(AutoRange.getBegin(),
2323                    diag::warn_cxx98_compat_auto_type_specifier)
2324         << AutoRange;
2325   }
2326
2327   if (SemaRef.getLangOpts().CPlusPlus &&
2328       OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
2329     // Check the contexts where C++ forbids the declaration of a new class
2330     // or enumeration in a type-specifier-seq.
2331     switch (D.getContext()) {
2332     case Declarator::TrailingReturnContext:
2333       // Class and enumeration definitions are syntactically not allowed in
2334       // trailing return types.
2335       llvm_unreachable("parser should not have allowed this");
2336       break;
2337     case Declarator::FileContext:
2338     case Declarator::MemberContext:
2339     case Declarator::BlockContext:
2340     case Declarator::ForContext:
2341     case Declarator::BlockLiteralContext:
2342     case Declarator::LambdaExprContext:
2343       // C++11 [dcl.type]p3:
2344       //   A type-specifier-seq shall not define a class or enumeration unless
2345       //   it appears in the type-id of an alias-declaration (7.1.3) that is not
2346       //   the declaration of a template-declaration.
2347     case Declarator::AliasDeclContext:
2348       break;
2349     case Declarator::AliasTemplateContext:
2350       SemaRef.Diag(OwnedTagDecl->getLocation(),
2351              diag::err_type_defined_in_alias_template)
2352         << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2353       D.setInvalidType(true);
2354       break;
2355     case Declarator::TypeNameContext:
2356     case Declarator::ConversionIdContext:
2357     case Declarator::TemplateParamContext:
2358     case Declarator::CXXNewContext:
2359     case Declarator::CXXCatchContext:
2360     case Declarator::ObjCCatchContext:
2361     case Declarator::TemplateTypeArgContext:
2362       SemaRef.Diag(OwnedTagDecl->getLocation(),
2363              diag::err_type_defined_in_type_specifier)
2364         << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2365       D.setInvalidType(true);
2366       break;
2367     case Declarator::PrototypeContext:
2368     case Declarator::LambdaExprParameterContext:
2369     case Declarator::ObjCParameterContext:
2370     case Declarator::ObjCResultContext:
2371     case Declarator::KNRTypeListContext:
2372       // C++ [dcl.fct]p6:
2373       //   Types shall not be defined in return or parameter types.
2374       SemaRef.Diag(OwnedTagDecl->getLocation(),
2375                    diag::err_type_defined_in_param_type)
2376         << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2377       D.setInvalidType(true);
2378       break;
2379     case Declarator::ConditionContext:
2380       // C++ 6.4p2:
2381       // The type-specifier-seq shall not contain typedef and shall not declare
2382       // a new class or enumeration.
2383       SemaRef.Diag(OwnedTagDecl->getLocation(),
2384                    diag::err_type_defined_in_condition);
2385       D.setInvalidType(true);
2386       break;
2387     }
2388   }
2389
2390   assert(!T.isNull() && "This function should not return a null type");
2391   return T;
2392 }
2393
2394 /// Produce an appropriate diagnostic for an ambiguity between a function
2395 /// declarator and a C++ direct-initializer.
2396 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
2397                                        DeclaratorChunk &DeclType, QualType RT) {
2398   const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2399   assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
2400
2401   // If the return type is void there is no ambiguity.
2402   if (RT->isVoidType())
2403     return;
2404
2405   // An initializer for a non-class type can have at most one argument.
2406   if (!RT->isRecordType() && FTI.NumParams > 1)
2407     return;
2408
2409   // An initializer for a reference must have exactly one argument.
2410   if (RT->isReferenceType() && FTI.NumParams != 1)
2411     return;
2412
2413   // Only warn if this declarator is declaring a function at block scope, and
2414   // doesn't have a storage class (such as 'extern') specified.
2415   if (!D.isFunctionDeclarator() ||
2416       D.getFunctionDefinitionKind() != FDK_Declaration ||
2417       !S.CurContext->isFunctionOrMethod() ||
2418       D.getDeclSpec().getStorageClassSpec()
2419         != DeclSpec::SCS_unspecified)
2420     return;
2421
2422   // Inside a condition, a direct initializer is not permitted. We allow one to
2423   // be parsed in order to give better diagnostics in condition parsing.
2424   if (D.getContext() == Declarator::ConditionContext)
2425     return;
2426
2427   SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
2428
2429   S.Diag(DeclType.Loc,
2430          FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
2431                        : diag::warn_empty_parens_are_function_decl)
2432       << ParenRange;
2433
2434   // If the declaration looks like:
2435   //   T var1,
2436   //   f();
2437   // and name lookup finds a function named 'f', then the ',' was
2438   // probably intended to be a ';'.
2439   if (!D.isFirstDeclarator() && D.getIdentifier()) {
2440     FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
2441     FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
2442     if (Comma.getFileID() != Name.getFileID() ||
2443         Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
2444       LookupResult Result(S, D.getIdentifier(), SourceLocation(),
2445                           Sema::LookupOrdinaryName);
2446       if (S.LookupName(Result, S.getCurScope()))
2447         S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
2448           << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
2449           << D.getIdentifier();
2450     }
2451   }
2452
2453   if (FTI.NumParams > 0) {
2454     // For a declaration with parameters, eg. "T var(T());", suggest adding
2455     // parens around the first parameter to turn the declaration into a
2456     // variable declaration.
2457     SourceRange Range = FTI.Params[0].Param->getSourceRange();
2458     SourceLocation B = Range.getBegin();
2459     SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
2460     // FIXME: Maybe we should suggest adding braces instead of parens
2461     // in C++11 for classes that don't have an initializer_list constructor.
2462     S.Diag(B, diag::note_additional_parens_for_variable_declaration)
2463       << FixItHint::CreateInsertion(B, "(")
2464       << FixItHint::CreateInsertion(E, ")");
2465   } else {
2466     // For a declaration without parameters, eg. "T var();", suggest replacing
2467     // the parens with an initializer to turn the declaration into a variable
2468     // declaration.
2469     const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
2470
2471     // Empty parens mean value-initialization, and no parens mean
2472     // default initialization. These are equivalent if the default
2473     // constructor is user-provided or if zero-initialization is a
2474     // no-op.
2475     if (RD && RD->hasDefinition() &&
2476         (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
2477       S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
2478         << FixItHint::CreateRemoval(ParenRange);
2479     else {
2480       std::string Init =
2481           S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
2482       if (Init.empty() && S.LangOpts.CPlusPlus11)
2483         Init = "{}";
2484       if (!Init.empty())
2485         S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
2486           << FixItHint::CreateReplacement(ParenRange, Init);
2487     }
2488   }
2489 }
2490
2491 /// Helper for figuring out the default CC for a function declarator type.  If
2492 /// this is the outermost chunk, then we can determine the CC from the
2493 /// declarator context.  If not, then this could be either a member function
2494 /// type or normal function type.
2495 static CallingConv
2496 getCCForDeclaratorChunk(Sema &S, Declarator &D,
2497                         const DeclaratorChunk::FunctionTypeInfo &FTI,
2498                         unsigned ChunkIndex) {
2499   assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
2500
2501   bool IsCXXInstanceMethod = false;
2502
2503   if (S.getLangOpts().CPlusPlus) {
2504     // Look inwards through parentheses to see if this chunk will form a
2505     // member pointer type or if we're the declarator.  Any type attributes
2506     // between here and there will override the CC we choose here.
2507     unsigned I = ChunkIndex;
2508     bool FoundNonParen = false;
2509     while (I && !FoundNonParen) {
2510       --I;
2511       if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
2512         FoundNonParen = true;
2513     }
2514
2515     if (FoundNonParen) {
2516       // If we're not the declarator, we're a regular function type unless we're
2517       // in a member pointer.
2518       IsCXXInstanceMethod =
2519           D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
2520     } else if (D.getContext() == Declarator::LambdaExprContext) {
2521       // This can only be a call operator for a lambda, which is an instance
2522       // method.
2523       IsCXXInstanceMethod = true;
2524     } else {
2525       // We're the innermost decl chunk, so must be a function declarator.
2526       assert(D.isFunctionDeclarator());
2527
2528       // If we're inside a record, we're declaring a method, but it could be
2529       // explicitly or implicitly static.
2530       IsCXXInstanceMethod =
2531           D.isFirstDeclarationOfMember() &&
2532           D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
2533           !D.isStaticMember();
2534     }
2535   }
2536
2537   CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
2538                                                          IsCXXInstanceMethod);
2539
2540   // Attribute AT_OpenCLKernel affects the calling convention only on
2541   // the SPIR target, hence it cannot be treated as a calling
2542   // convention attribute. This is the simplest place to infer
2543   // "spir_kernel" for OpenCL kernels on SPIR.
2544   if (CC == CC_SpirFunction) {
2545     for (const AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
2546          Attr; Attr = Attr->getNext()) {
2547       if (Attr->getKind() == AttributeList::AT_OpenCLKernel) {
2548         CC = CC_SpirKernel;
2549         break;
2550       }
2551     }
2552   }
2553
2554   return CC;
2555 }
2556
2557 namespace {
2558   /// A simple notion of pointer kinds, which matches up with the various
2559   /// pointer declarators.
2560   enum class SimplePointerKind {
2561     Pointer,
2562     BlockPointer,
2563     MemberPointer,
2564   };
2565 }
2566
2567 IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
2568   switch (nullability) {
2569   case NullabilityKind::NonNull:
2570     if (!Ident___nonnull)
2571       Ident___nonnull = PP.getIdentifierInfo("__nonnull");
2572     return Ident___nonnull;
2573
2574   case NullabilityKind::Nullable:
2575     if (!Ident___nullable)
2576       Ident___nullable = PP.getIdentifierInfo("__nullable");
2577     return Ident___nullable;
2578
2579   case NullabilityKind::Unspecified:
2580     if (!Ident___null_unspecified)
2581       Ident___null_unspecified = PP.getIdentifierInfo("__null_unspecified");
2582     return Ident___null_unspecified;
2583   }
2584   llvm_unreachable("Unknown nullability kind.");
2585 }
2586
2587 /// Retrieve the identifier "NSError".
2588 IdentifierInfo *Sema::getNSErrorIdent() {
2589   if (!Ident_NSError)
2590     Ident_NSError = PP.getIdentifierInfo("NSError");
2591
2592   return Ident_NSError;
2593 }
2594
2595 /// Check whether there is a nullability attribute of any kind in the given
2596 /// attribute list.
2597 static bool hasNullabilityAttr(const AttributeList *attrs) {
2598   for (const AttributeList *attr = attrs; attr;
2599        attr = attr->getNext()) {
2600     if (attr->getKind() == AttributeList::AT_TypeNonNull ||
2601         attr->getKind() == AttributeList::AT_TypeNullable ||
2602         attr->getKind() == AttributeList::AT_TypeNullUnspecified)
2603       return true;
2604   }
2605
2606   return false;
2607 }
2608
2609 namespace {
2610   /// Describes the kind of a pointer a declarator describes.
2611   enum class PointerDeclaratorKind {
2612     // Not a pointer.
2613     NonPointer,
2614     // Single-level pointer.
2615     SingleLevelPointer,
2616     // Multi-level pointer (of any pointer kind).
2617     MultiLevelPointer,
2618     // CFFooRef*
2619     MaybePointerToCFRef,
2620     // CFErrorRef*
2621     CFErrorRefPointer,
2622     // NSError**
2623     NSErrorPointerPointer,
2624   };
2625 }
2626
2627 /// Classify the given declarator, whose type-specified is \c type, based on
2628 /// what kind of pointer it refers to.
2629 ///
2630 /// This is used to determine the default nullability.
2631 static PointerDeclaratorKind classifyPointerDeclarator(Sema &S,
2632                                                        QualType type,
2633                                                        Declarator &declarator) {
2634   unsigned numNormalPointers = 0;
2635
2636   // For any dependent type, we consider it a non-pointer.
2637   if (type->isDependentType())
2638     return PointerDeclaratorKind::NonPointer;
2639
2640   // Look through the declarator chunks to identify pointers.
2641   for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
2642     DeclaratorChunk &chunk = declarator.getTypeObject(i);
2643     switch (chunk.Kind) {
2644     case DeclaratorChunk::Array:
2645     case DeclaratorChunk::Function:
2646       break;
2647
2648     case DeclaratorChunk::BlockPointer:
2649     case DeclaratorChunk::MemberPointer:
2650       return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
2651                                    : PointerDeclaratorKind::SingleLevelPointer;
2652
2653     case DeclaratorChunk::Paren:
2654     case DeclaratorChunk::Reference:
2655       continue;
2656
2657     case DeclaratorChunk::Pointer:
2658       ++numNormalPointers;
2659       if (numNormalPointers > 2)
2660         return PointerDeclaratorKind::MultiLevelPointer;
2661       continue;
2662     }
2663   }
2664
2665   // Then, dig into the type specifier itself.
2666   unsigned numTypeSpecifierPointers = 0;
2667   do {
2668     // Decompose normal pointers.
2669     if (auto ptrType = type->getAs<PointerType>()) {
2670       ++numNormalPointers;
2671
2672       if (numNormalPointers > 2)
2673         return PointerDeclaratorKind::MultiLevelPointer;
2674
2675       type = ptrType->getPointeeType();
2676       ++numTypeSpecifierPointers;
2677       continue;
2678     }
2679
2680     // Decompose block pointers.
2681     if (type->getAs<BlockPointerType>()) {
2682       return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
2683                                    : PointerDeclaratorKind::SingleLevelPointer;
2684     }
2685
2686     // Decompose member pointers.
2687     if (type->getAs<MemberPointerType>()) {
2688       return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
2689                                    : PointerDeclaratorKind::SingleLevelPointer;
2690     }
2691
2692     // Look at Objective-C object pointers.
2693     if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
2694       ++numNormalPointers;
2695       ++numTypeSpecifierPointers;
2696
2697       // If this is NSError**, report that.
2698       if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
2699         if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
2700             numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
2701           return PointerDeclaratorKind::NSErrorPointerPointer;
2702         }
2703       }
2704
2705       break;
2706     }
2707
2708     // Look at Objective-C class types.
2709     if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
2710       if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
2711         if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
2712           return PointerDeclaratorKind::NSErrorPointerPointer;;
2713       }
2714
2715       break;
2716     }
2717
2718     // If at this point we haven't seen a pointer, we won't see one.
2719     if (numNormalPointers == 0)
2720       return PointerDeclaratorKind::NonPointer;
2721
2722     if (auto recordType = type->getAs<RecordType>()) {
2723       RecordDecl *recordDecl = recordType->getDecl();
2724
2725       bool isCFError = false;
2726       if (S.CFError) {
2727         // If we already know about CFError, test it directly.
2728         isCFError = (S.CFError == recordDecl);
2729       } else {
2730         // Check whether this is CFError, which we identify based on its bridge
2731         // to NSError.
2732         if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) {
2733           if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>()) {
2734             if (bridgeAttr->getBridgedType() == S.getNSErrorIdent()) {
2735               S.CFError = recordDecl;
2736               isCFError = true;
2737             }
2738           }
2739         }
2740       }
2741
2742       // If this is CFErrorRef*, report it as such.
2743       if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
2744         return PointerDeclaratorKind::CFErrorRefPointer;
2745       }
2746       break;
2747     }
2748
2749     break;
2750   } while (true);
2751
2752
2753   switch (numNormalPointers) {
2754   case 0:
2755     return PointerDeclaratorKind::NonPointer;
2756
2757   case 1:
2758     return PointerDeclaratorKind::SingleLevelPointer;
2759
2760   case 2:
2761     return PointerDeclaratorKind::MaybePointerToCFRef;
2762
2763   default:
2764     return PointerDeclaratorKind::MultiLevelPointer;
2765   }
2766 }
2767
2768 static FileID getNullabilityCompletenessCheckFileID(Sema &S,
2769                                                     SourceLocation loc) {
2770   // If we're anywhere in a function, method, or closure context, don't perform
2771   // completeness checks.
2772   for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
2773     if (ctx->isFunctionOrMethod())
2774       return FileID();
2775
2776     if (ctx->isFileContext())
2777       break;
2778   }
2779
2780   // We only care about the expansion location.
2781   loc = S.SourceMgr.getExpansionLoc(loc);
2782   FileID file = S.SourceMgr.getFileID(loc);
2783   if (file.isInvalid())
2784     return FileID();
2785
2786   // Retrieve file information.
2787   bool invalid = false;
2788   const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
2789   if (invalid || !sloc.isFile())
2790     return FileID();
2791
2792   // We don't want to perform completeness checks on the main file or in
2793   // system headers.
2794   const SrcMgr::FileInfo &fileInfo = sloc.getFile();
2795   if (fileInfo.getIncludeLoc().isInvalid())
2796     return FileID();
2797   if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
2798       S.Diags.getSuppressSystemWarnings()) {
2799     return FileID();
2800   }
2801
2802   return file;
2803 }
2804
2805 /// Check for consistent use of nullability.
2806 static void checkNullabilityConsistency(TypeProcessingState &state,
2807                                         SimplePointerKind pointerKind,
2808                                         SourceLocation pointerLoc) {
2809   Sema &S = state.getSema();
2810
2811   // Determine which file we're performing consistency checking for.
2812   FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
2813   if (file.isInvalid())
2814     return;
2815
2816   // If we haven't seen any type nullability in this file, we won't warn now
2817   // about anything.
2818   FileNullability &fileNullability = S.NullabilityMap[file];
2819   if (!fileNullability.SawTypeNullability) {
2820     // If this is the first pointer declarator in the file, record it.
2821     if (fileNullability.PointerLoc.isInvalid() &&
2822         !S.Context.getDiagnostics().isIgnored(diag::warn_nullability_missing,
2823                                               pointerLoc)) {
2824       fileNullability.PointerLoc = pointerLoc;
2825       fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
2826     }
2827
2828     return;
2829   }
2830
2831   // Complain about missing nullability.
2832   S.Diag(pointerLoc, diag::warn_nullability_missing)
2833     << static_cast<unsigned>(pointerKind);
2834 }
2835
2836 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
2837                                                 QualType declSpecType,
2838                                                 TypeSourceInfo *TInfo) {
2839   // The TypeSourceInfo that this function returns will not be a null type.
2840   // If there is an error, this function will fill in a dummy type as fallback.
2841   QualType T = declSpecType;
2842   Declarator &D = state.getDeclarator();
2843   Sema &S = state.getSema();
2844   ASTContext &Context = S.Context;
2845   const LangOptions &LangOpts = S.getLangOpts();
2846
2847   // The name we're declaring, if any.
2848   DeclarationName Name;
2849   if (D.getIdentifier())
2850     Name = D.getIdentifier();
2851
2852   // Does this declaration declare a typedef-name?
2853   bool IsTypedefName =
2854     D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
2855     D.getContext() == Declarator::AliasDeclContext ||
2856     D.getContext() == Declarator::AliasTemplateContext;
2857
2858   // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
2859   bool IsQualifiedFunction = T->isFunctionProtoType() &&
2860       (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
2861        T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
2862
2863   // If T is 'decltype(auto)', the only declarators we can have are parens
2864   // and at most one function declarator if this is a function declaration.
2865   if (const AutoType *AT = T->getAs<AutoType>()) {
2866     if (AT->isDecltypeAuto()) {
2867       for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
2868         unsigned Index = E - I - 1;
2869         DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
2870         unsigned DiagId = diag::err_decltype_auto_compound_type;
2871         unsigned DiagKind = 0;
2872         switch (DeclChunk.Kind) {
2873         case DeclaratorChunk::Paren:
2874           continue;
2875         case DeclaratorChunk::Function: {
2876           unsigned FnIndex;
2877           if (D.isFunctionDeclarationContext() &&
2878               D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
2879             continue;
2880           DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
2881           break;
2882         }
2883         case DeclaratorChunk::Pointer:
2884         case DeclaratorChunk::BlockPointer:
2885         case DeclaratorChunk::MemberPointer:
2886           DiagKind = 0;
2887           break;
2888         case DeclaratorChunk::Reference:
2889           DiagKind = 1;
2890           break;
2891         case DeclaratorChunk::Array:
2892           DiagKind = 2;
2893           break;
2894         }
2895
2896         S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
2897         D.setInvalidType(true);
2898         break;
2899       }
2900     }
2901   }
2902
2903   // Determine whether we should infer __nonnull on pointer types.
2904   Optional<NullabilityKind> inferNullability;
2905   bool inferNullabilityCS = false;
2906   bool inferNullabilityInnerOnly = false;
2907   bool inferNullabilityInnerOnlyComplete = false;
2908
2909   // Are we in an assume-nonnull region?
2910   bool inAssumeNonNullRegion = false;
2911   if (S.PP.getPragmaAssumeNonNullLoc().isValid() &&
2912       !state.getDeclarator().isObjCWeakProperty() &&
2913       !S.deduceWeakPropertyFromType(T)) {
2914     inAssumeNonNullRegion = true;
2915     // Determine which file we saw the assume-nonnull region in.
2916     FileID file = getNullabilityCompletenessCheckFileID(
2917                     S, S.PP.getPragmaAssumeNonNullLoc());
2918     if (!file.isInvalid()) {
2919       FileNullability &fileNullability = S.NullabilityMap[file];
2920
2921       // If we haven't seen any type nullability before, now we have.
2922       if (!fileNullability.SawTypeNullability) {
2923         if (fileNullability.PointerLoc.isValid()) {
2924           S.Diag(fileNullability.PointerLoc, diag::warn_nullability_missing)
2925             << static_cast<unsigned>(fileNullability.PointerKind);
2926         }
2927
2928         fileNullability.SawTypeNullability = true;
2929       }
2930     }
2931   }
2932
2933   // Whether to complain about missing nullability specifiers or not.
2934   enum {
2935     /// Never complain.
2936     CAMN_No,
2937     /// Complain on the inner pointers (but not the outermost
2938     /// pointer).
2939     CAMN_InnerPointers,
2940     /// Complain about any pointers that don't have nullability
2941     /// specified or inferred.
2942     CAMN_Yes
2943   } complainAboutMissingNullability = CAMN_No;
2944   unsigned NumPointersRemaining = 0;
2945
2946   if (IsTypedefName) {
2947     // For typedefs, we do not infer any nullability (the default),
2948     // and we only complain about missing nullability specifiers on
2949     // inner pointers.
2950     complainAboutMissingNullability = CAMN_InnerPointers;
2951
2952     if (T->canHaveNullability() && !T->getNullability(S.Context)) {
2953       ++NumPointersRemaining;
2954     }
2955
2956     for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
2957       DeclaratorChunk &chunk = D.getTypeObject(i);
2958       switch (chunk.Kind) {
2959       case DeclaratorChunk::Array:
2960       case DeclaratorChunk::Function:
2961         break;
2962
2963       case DeclaratorChunk::BlockPointer:
2964       case DeclaratorChunk::MemberPointer:
2965         ++NumPointersRemaining;
2966         break;
2967
2968       case DeclaratorChunk::Paren:
2969       case DeclaratorChunk::Reference:
2970         continue;
2971
2972       case DeclaratorChunk::Pointer:
2973         ++NumPointersRemaining;
2974         continue;
2975       }
2976     }
2977   } else {
2978     bool isFunctionOrMethod = false;
2979     switch (auto context = state.getDeclarator().getContext()) {
2980     case Declarator::ObjCParameterContext:
2981     case Declarator::ObjCResultContext:
2982     case Declarator::PrototypeContext:
2983     case Declarator::TrailingReturnContext:
2984       isFunctionOrMethod = true;
2985       // fallthrough
2986
2987     case Declarator::MemberContext:
2988       if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
2989         complainAboutMissingNullability = CAMN_No;
2990         break;
2991       }
2992       // fallthrough
2993
2994     case Declarator::FileContext:
2995     case Declarator::KNRTypeListContext:
2996       complainAboutMissingNullability = CAMN_Yes;
2997
2998       // Nullability inference depends on the type and declarator.
2999       switch (classifyPointerDeclarator(S, T, D)) {
3000       case PointerDeclaratorKind::NonPointer:
3001       case PointerDeclaratorKind::MultiLevelPointer:
3002         // Cannot infer nullability.
3003         break;
3004
3005       case PointerDeclaratorKind::SingleLevelPointer:
3006         // Infer __nonnull if we are in an assumes-nonnull region.
3007         if (inAssumeNonNullRegion) {
3008           inferNullability = NullabilityKind::NonNull;
3009           inferNullabilityCS = (context == Declarator::ObjCParameterContext ||
3010                                 context == Declarator::ObjCResultContext);
3011         }
3012         break;
3013
3014       case PointerDeclaratorKind::CFErrorRefPointer:
3015       case PointerDeclaratorKind::NSErrorPointerPointer:
3016         // Within a function or method signature, infer __nullable at both
3017         // levels.
3018         if (isFunctionOrMethod && inAssumeNonNullRegion)
3019           inferNullability = NullabilityKind::Nullable;
3020         break;
3021
3022       case PointerDeclaratorKind::MaybePointerToCFRef:
3023         if (isFunctionOrMethod) {
3024           // On pointer-to-pointer parameters marked cf_returns_retained or
3025           // cf_returns_not_retained, if the outer pointer is explicit then
3026           // infer the inner pointer as __nullable.
3027           auto hasCFReturnsAttr = [](const AttributeList *NextAttr) -> bool {
3028             while (NextAttr) {
3029               if (NextAttr->getKind() == AttributeList::AT_CFReturnsRetained ||
3030                   NextAttr->getKind() == AttributeList::AT_CFReturnsNotRetained)
3031                 return true;
3032               NextAttr = NextAttr->getNext();
3033             }
3034             return false;
3035           };
3036           if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
3037             if (hasCFReturnsAttr(D.getAttributes()) ||
3038                 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
3039                 hasCFReturnsAttr(D.getDeclSpec().getAttributes().getList())) {
3040               inferNullability = NullabilityKind::Nullable;
3041               inferNullabilityInnerOnly = true;
3042             }
3043           }
3044         }
3045         break;
3046       }
3047       break;
3048
3049     case Declarator::ConversionIdContext:
3050       complainAboutMissingNullability = CAMN_Yes;
3051       break;
3052
3053     case Declarator::AliasDeclContext:
3054     case Declarator::AliasTemplateContext:
3055     case Declarator::BlockContext:
3056     case Declarator::BlockLiteralContext:
3057     case Declarator::ConditionContext:
3058     case Declarator::CXXCatchContext:
3059     case Declarator::CXXNewContext:
3060     case Declarator::ForContext:
3061     case Declarator::LambdaExprContext:
3062     case Declarator::LambdaExprParameterContext:
3063     case Declarator::ObjCCatchContext:
3064     case Declarator::TemplateParamContext:
3065     case Declarator::TemplateTypeArgContext:
3066     case Declarator::TypeNameContext:
3067       // Don't infer in these contexts.
3068       break;
3069     }
3070   }
3071
3072   // Local function that checks the nullability for a given pointer declarator.
3073   // Returns true if __nonnull was inferred.
3074   auto inferPointerNullability = [&](SimplePointerKind pointerKind,
3075                                      SourceLocation pointerLoc,
3076                                      AttributeList *&attrs) -> AttributeList * {
3077     // We've seen a pointer.
3078     if (NumPointersRemaining > 0)
3079       --NumPointersRemaining;
3080
3081     // If a nullability attribute is present, there's nothing to do.
3082     if (hasNullabilityAttr(attrs))
3083       return nullptr;
3084
3085     // If we're supposed to infer nullability, do so now.
3086     if (inferNullability && !inferNullabilityInnerOnlyComplete) {
3087       AttributeList::Syntax syntax
3088         = inferNullabilityCS ? AttributeList::AS_ContextSensitiveKeyword
3089                              : AttributeList::AS_Keyword;
3090       AttributeList *nullabilityAttr = state.getDeclarator().getAttributePool()
3091                                          .create(
3092                                            S.getNullabilityKeyword(
3093                                              *inferNullability),
3094                                            SourceRange(pointerLoc),
3095                                            nullptr, SourceLocation(),
3096                                            nullptr, 0, syntax);
3097
3098       spliceAttrIntoList(*nullabilityAttr, attrs);
3099
3100       if (inferNullabilityInnerOnly)
3101         inferNullabilityInnerOnlyComplete = true;
3102       return nullabilityAttr;
3103     }
3104
3105     // If we're supposed to complain about missing nullability, do so
3106     // now if it's truly missing.
3107     switch (complainAboutMissingNullability) {
3108     case CAMN_No:
3109       break;
3110
3111     case CAMN_InnerPointers:
3112       if (NumPointersRemaining == 0)
3113         break;
3114       // Fallthrough.
3115
3116     case CAMN_Yes:
3117       checkNullabilityConsistency(state, pointerKind, pointerLoc);
3118     }
3119
3120     return nullptr;
3121   };
3122
3123   // If the type itself could have nullability but does not, infer pointer
3124   // nullability and perform consistency checking.
3125   if (T->canHaveNullability() && S.ActiveTemplateInstantiations.empty() &&
3126       !T->getNullability(S.Context)) {
3127     SimplePointerKind pointerKind = SimplePointerKind::Pointer;
3128     if (T->isBlockPointerType())
3129       pointerKind = SimplePointerKind::BlockPointer;
3130     else if (T->isMemberPointerType())
3131       pointerKind = SimplePointerKind::MemberPointer;
3132
3133     if (auto *attr = inferPointerNullability(
3134                        pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
3135                        D.getMutableDeclSpec().getAttributes().getListRef())) {
3136       T = Context.getAttributedType(
3137             AttributedType::getNullabilityAttrKind(*inferNullability), T, T);
3138       attr->setUsedAsTypeAttr();
3139     }
3140   }
3141
3142   // Walk the DeclTypeInfo, building the recursive type as we go.
3143   // DeclTypeInfos are ordered from the identifier out, which is
3144   // opposite of what we want :).
3145   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3146     unsigned chunkIndex = e - i - 1;
3147     state.setCurrentChunkIndex(chunkIndex);
3148     DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
3149     IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
3150     switch (DeclType.Kind) {
3151     case DeclaratorChunk::Paren:
3152       T = S.BuildParenType(T);
3153       break;
3154     case DeclaratorChunk::BlockPointer:
3155       // If blocks are disabled, emit an error.
3156       if (!LangOpts.Blocks)
3157         S.Diag(DeclType.Loc, diag::err_blocks_disable);
3158
3159       // Handle pointer nullability.
3160       inferPointerNullability(SimplePointerKind::BlockPointer,
3161                               DeclType.Loc, DeclType.getAttrListRef());
3162
3163       T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
3164       if (DeclType.Cls.TypeQuals)
3165         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
3166       break;
3167     case DeclaratorChunk::Pointer:
3168       // Verify that we're not building a pointer to pointer to function with
3169       // exception specification.
3170       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
3171         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
3172         D.setInvalidType(true);
3173         // Build the type anyway.
3174       }
3175
3176       // Handle pointer nullability
3177       inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
3178                               DeclType.getAttrListRef());
3179
3180       if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
3181         T = Context.getObjCObjectPointerType(T);
3182         if (DeclType.Ptr.TypeQuals)
3183           T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
3184         break;
3185       }
3186       T = S.BuildPointerType(T, DeclType.Loc, Name);
3187       if (DeclType.Ptr.TypeQuals)
3188         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
3189
3190       break;
3191     case DeclaratorChunk::Reference: {
3192       // Verify that we're not building a reference to pointer to function with
3193       // exception specification.
3194       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
3195         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
3196         D.setInvalidType(true);
3197         // Build the type anyway.
3198       }
3199       T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
3200
3201       if (DeclType.Ref.HasRestrict)
3202         T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
3203       break;
3204     }
3205     case DeclaratorChunk::Array: {
3206       // Verify that we're not building an array of pointers to function with
3207       // exception specification.
3208       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
3209         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
3210         D.setInvalidType(true);
3211         // Build the type anyway.
3212       }
3213       DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
3214       Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
3215       ArrayType::ArraySizeModifier ASM;
3216       if (ATI.isStar)
3217         ASM = ArrayType::Star;
3218       else if (ATI.hasStatic)
3219         ASM = ArrayType::Static;
3220       else
3221         ASM = ArrayType::Normal;
3222       if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
3223         // FIXME: This check isn't quite right: it allows star in prototypes
3224         // for function definitions, and disallows some edge cases detailed
3225         // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
3226         S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
3227         ASM = ArrayType::Normal;
3228         D.setInvalidType(true);
3229       }
3230
3231       // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
3232       // shall appear only in a declaration of a function parameter with an
3233       // array type, ...
3234       if (ASM == ArrayType::Static || ATI.TypeQuals) {
3235         if (!(D.isPrototypeContext() ||
3236               D.getContext() == Declarator::KNRTypeListContext)) {
3237           S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
3238               (ASM == ArrayType::Static ? "'static'" : "type qualifier");
3239           // Remove the 'static' and the type qualifiers.
3240           if (ASM == ArrayType::Static)
3241             ASM = ArrayType::Normal;
3242           ATI.TypeQuals = 0;
3243           D.setInvalidType(true);
3244         }
3245
3246         // C99 6.7.5.2p1: ... and then only in the outermost array type
3247         // derivation.
3248         unsigned x = chunkIndex;
3249         while (x != 0) {
3250           // Walk outwards along the declarator chunks.
3251           x--;
3252           const DeclaratorChunk &DC = D.getTypeObject(x);
3253           switch (DC.Kind) {
3254           case DeclaratorChunk::Paren:
3255             continue;
3256           case DeclaratorChunk::Array:
3257           case DeclaratorChunk::Pointer:
3258           case DeclaratorChunk::Reference:
3259           case DeclaratorChunk::MemberPointer:
3260             S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
3261               (ASM == ArrayType::Static ? "'static'" : "type qualifier");
3262             if (ASM == ArrayType::Static)
3263               ASM = ArrayType::Normal;
3264             ATI.TypeQuals = 0;
3265             D.setInvalidType(true);
3266             break;
3267           case DeclaratorChunk::Function:
3268           case DeclaratorChunk::BlockPointer:
3269             // These are invalid anyway, so just ignore.
3270             break;
3271           }
3272         }
3273       }
3274       const AutoType *AT = T->getContainedAutoType();
3275       // Allow arrays of auto if we are a generic lambda parameter.
3276       // i.e. [](auto (&array)[5]) { return array[0]; }; OK
3277       if (AT && D.getContext() != Declarator::LambdaExprParameterContext) {
3278         // We've already diagnosed this for decltype(auto).
3279         if (!AT->isDecltypeAuto())
3280           S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
3281             << getPrintableNameForEntity(Name) << T;
3282         T = QualType();
3283         break;
3284       }
3285
3286       T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
3287                            SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
3288       break;
3289     }
3290     case DeclaratorChunk::Function: {
3291       // If the function declarator has a prototype (i.e. it is not () and
3292       // does not have a K&R-style identifier list), then the arguments are part
3293       // of the type, otherwise the argument list is ().
3294       const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3295       IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
3296
3297       // Check for auto functions and trailing return type and adjust the
3298       // return type accordingly.
3299       if (!D.isInvalidType()) {
3300         // trailing-return-type is only required if we're declaring a function,
3301         // and not, for instance, a pointer to a function.
3302         if (D.getDeclSpec().containsPlaceholderType() &&
3303             !FTI.hasTrailingReturnType() && chunkIndex == 0 &&
3304             !S.getLangOpts().CPlusPlus14) {
3305           S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
3306                  D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
3307                      ? diag::err_auto_missing_trailing_return
3308                      : diag::err_deduced_return_type);
3309           T = Context.IntTy;
3310           D.setInvalidType(true);
3311         } else if (FTI.hasTrailingReturnType()) {
3312           // T must be exactly 'auto' at this point. See CWG issue 681.
3313           if (isa<ParenType>(T)) {
3314             S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
3315                  diag::err_trailing_return_in_parens)
3316               << T << D.getDeclSpec().getSourceRange();
3317             D.setInvalidType(true);
3318           } else if (D.getContext() != Declarator::LambdaExprContext &&
3319                      (T.hasQualifiers() || !isa<AutoType>(T) ||
3320                       cast<AutoType>(T)->isDecltypeAuto())) {
3321             S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
3322                  diag::err_trailing_return_without_auto)
3323               << T << D.getDeclSpec().getSourceRange();
3324             D.setInvalidType(true);
3325           }
3326           T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
3327           if (T.isNull()) {
3328             // An error occurred parsing the trailing return type.
3329             T = Context.IntTy;
3330             D.setInvalidType(true);
3331           }
3332         }
3333       }
3334
3335       // C99 6.7.5.3p1: The return type may not be a function or array type.
3336       // For conversion functions, we'll diagnose this particular error later.
3337       if ((T->isArrayType() || T->isFunctionType()) &&
3338           (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
3339         unsigned diagID = diag::err_func_returning_array_function;
3340         // Last processing chunk in block context means this function chunk
3341         // represents the block.
3342         if (chunkIndex == 0 &&
3343             D.getContext() == Declarator::BlockLiteralContext)
3344           diagID = diag::err_block_returning_array_function;
3345         S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
3346         T = Context.IntTy;
3347         D.setInvalidType(true);
3348       }
3349
3350       // Do not allow returning half FP value.
3351       // FIXME: This really should be in BuildFunctionType.
3352       if (T->isHalfType()) {
3353         if (S.getLangOpts().OpenCL) {
3354           if (!S.getOpenCLOptions().cl_khr_fp16) {
3355             S.Diag(D.getIdentifierLoc(), diag::err_opencl_half_return) << T;
3356             D.setInvalidType(true);
3357           } 
3358         } else if (!S.getLangOpts().HalfArgsAndReturns) {
3359           S.Diag(D.getIdentifierLoc(),
3360             diag::err_parameters_retval_cannot_have_fp16_type) << 1;
3361           D.setInvalidType(true);
3362         }
3363       }
3364
3365       // Methods cannot return interface types. All ObjC objects are
3366       // passed by reference.
3367       if (T->isObjCObjectType()) {
3368         SourceLocation DiagLoc, FixitLoc;
3369         if (TInfo) {
3370           DiagLoc = TInfo->getTypeLoc().getLocStart();
3371           FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd());
3372         } else {
3373           DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
3374           FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd());
3375         }
3376         S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
3377           << 0 << T
3378           << FixItHint::CreateInsertion(FixitLoc, "*");
3379
3380         T = Context.getObjCObjectPointerType(T);
3381         if (TInfo) {
3382           TypeLocBuilder TLB;
3383           TLB.pushFullCopy(TInfo->getTypeLoc());
3384           ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
3385           TLoc.setStarLoc(FixitLoc);
3386           TInfo = TLB.getTypeSourceInfo(Context, T);
3387         }
3388
3389         D.setInvalidType(true);
3390       }
3391
3392       // cv-qualifiers on return types are pointless except when the type is a
3393       // class type in C++.
3394       if ((T.getCVRQualifiers() || T->isAtomicType()) &&
3395           !(S.getLangOpts().CPlusPlus &&
3396             (T->isDependentType() || T->isRecordType()))) {
3397         if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
3398             D.getFunctionDefinitionKind() == FDK_Definition) {
3399           // [6.9.1/3] qualified void return is invalid on a C
3400           // function definition.  Apparently ok on declarations and
3401           // in C++ though (!)
3402           S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
3403         } else
3404           diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
3405       }
3406
3407       // Objective-C ARC ownership qualifiers are ignored on the function
3408       // return type (by type canonicalization). Complain if this attribute
3409       // was written here.
3410       if (T.getQualifiers().hasObjCLifetime()) {
3411         SourceLocation AttrLoc;
3412         if (chunkIndex + 1 < D.getNumTypeObjects()) {
3413           DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
3414           for (const AttributeList *Attr = ReturnTypeChunk.getAttrs();
3415                Attr; Attr = Attr->getNext()) {
3416             if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
3417               AttrLoc = Attr->getLoc();
3418               break;
3419             }
3420           }
3421         }
3422         if (AttrLoc.isInvalid()) {
3423           for (const AttributeList *Attr
3424                  = D.getDeclSpec().getAttributes().getList();
3425                Attr; Attr = Attr->getNext()) {
3426             if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
3427               AttrLoc = Attr->getLoc();
3428               break;
3429             }
3430           }
3431         }
3432
3433         if (AttrLoc.isValid()) {
3434           // The ownership attributes are almost always written via
3435           // the predefined
3436           // __strong/__weak/__autoreleasing/__unsafe_unretained.
3437           if (AttrLoc.isMacroID())
3438             AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first;
3439
3440           S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
3441             << T.getQualifiers().getObjCLifetime();
3442         }
3443       }
3444
3445       if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
3446         // C++ [dcl.fct]p6:
3447         //   Types shall not be defined in return or parameter types.
3448         TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3449         S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
3450           << Context.getTypeDeclType(Tag);
3451       }
3452
3453       // Exception specs are not allowed in typedefs. Complain, but add it
3454       // anyway.
3455       if (IsTypedefName && FTI.getExceptionSpecType())
3456         S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef)
3457           << (D.getContext() == Declarator::AliasDeclContext ||
3458               D.getContext() == Declarator::AliasTemplateContext);
3459
3460       // If we see "T var();" or "T var(T());" at block scope, it is probably
3461       // an attempt to initialize a variable, not a function declaration.
3462       if (FTI.isAmbiguous)
3463         warnAboutAmbiguousFunction(S, D, DeclType, T);
3464
3465       FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex));
3466
3467       if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus) {
3468         // Simple void foo(), where the incoming T is the result type.
3469         T = Context.getFunctionNoProtoType(T, EI);
3470       } else {
3471         // We allow a zero-parameter variadic function in C if the
3472         // function is marked with the "overloadable" attribute. Scan
3473         // for this attribute now.
3474         if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
3475           bool Overloadable = false;
3476           for (const AttributeList *Attrs = D.getAttributes();
3477                Attrs; Attrs = Attrs->getNext()) {
3478             if (Attrs->getKind() == AttributeList::AT_Overloadable) {
3479               Overloadable = true;
3480               break;
3481             }
3482           }
3483
3484           if (!Overloadable)
3485             S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
3486         }
3487
3488         if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
3489           // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
3490           // definition.
3491           S.Diag(FTI.Params[0].IdentLoc,
3492                  diag::err_ident_list_in_fn_declaration);
3493           D.setInvalidType(true);
3494           // Recover by creating a K&R-style function type.
3495           T = Context.getFunctionNoProtoType(T, EI);
3496           break;
3497         }
3498
3499         FunctionProtoType::ExtProtoInfo EPI;
3500         EPI.ExtInfo = EI;
3501         EPI.Variadic = FTI.isVariadic;
3502         EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
3503         EPI.TypeQuals = FTI.TypeQuals;
3504         EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
3505                     : FTI.RefQualifierIsLValueRef? RQ_LValue
3506                     : RQ_RValue;
3507
3508         // Otherwise, we have a function with a parameter list that is
3509         // potentially variadic.
3510         SmallVector<QualType, 16> ParamTys;
3511         ParamTys.reserve(FTI.NumParams);
3512
3513         SmallVector<bool, 16> ConsumedParameters;
3514         ConsumedParameters.reserve(FTI.NumParams);
3515         bool HasAnyConsumedParameters = false;
3516
3517         for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
3518           ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
3519           QualType ParamTy = Param->getType();
3520           assert(!ParamTy.isNull() && "Couldn't parse type?");
3521
3522           // Look for 'void'.  void is allowed only as a single parameter to a
3523           // function with no other parameters (C99 6.7.5.3p10).  We record
3524           // int(void) as a FunctionProtoType with an empty parameter list.
3525           if (ParamTy->isVoidType()) {
3526             // If this is something like 'float(int, void)', reject it.  'void'
3527             // is an incomplete type (C99 6.2.5p19) and function decls cannot
3528             // have parameters of incomplete type.
3529             if (FTI.NumParams != 1 || FTI.isVariadic) {
3530               S.Diag(DeclType.Loc, diag::err_void_only_param);
3531               ParamTy = Context.IntTy;
3532               Param->setType(ParamTy);
3533             } else if (FTI.Params[i].Ident) {
3534               // Reject, but continue to parse 'int(void abc)'.
3535               S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
3536               ParamTy = Context.IntTy;
3537               Param->setType(ParamTy);
3538             } else {
3539               // Reject, but continue to parse 'float(const void)'.
3540               if (ParamTy.hasQualifiers())
3541                 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
3542
3543               // Do not add 'void' to the list.
3544               break;
3545             }
3546           } else if (ParamTy->isHalfType()) {
3547             // Disallow half FP parameters.
3548             // FIXME: This really should be in BuildFunctionType.
3549             if (S.getLangOpts().OpenCL) {
3550               if (!S.getOpenCLOptions().cl_khr_fp16) {
3551                 S.Diag(Param->getLocation(),
3552                   diag::err_opencl_half_param) << ParamTy;
3553                 D.setInvalidType();
3554                 Param->setInvalidDecl();
3555               }
3556             } else if (!S.getLangOpts().HalfArgsAndReturns) {
3557               S.Diag(Param->getLocation(),
3558                 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
3559               D.setInvalidType();
3560             }
3561           } else if (!FTI.hasPrototype) {
3562             if (ParamTy->isPromotableIntegerType()) {
3563               ParamTy = Context.getPromotedIntegerType(ParamTy);
3564               Param->setKNRPromoted(true);
3565             } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
3566               if (BTy->getKind() == BuiltinType::Float) {
3567                 ParamTy = Context.DoubleTy;
3568                 Param->setKNRPromoted(true);
3569               }
3570             }
3571           }
3572
3573           if (LangOpts.ObjCAutoRefCount) {
3574             bool Consumed = Param->hasAttr<NSConsumedAttr>();
3575             ConsumedParameters.push_back(Consumed);
3576             HasAnyConsumedParameters |= Consumed;
3577           }
3578
3579           ParamTys.push_back(ParamTy);
3580         }
3581
3582         if (HasAnyConsumedParameters)
3583           EPI.ConsumedParameters = ConsumedParameters.data();
3584
3585         SmallVector<QualType, 4> Exceptions;
3586         SmallVector<ParsedType, 2> DynamicExceptions;
3587         SmallVector<SourceRange, 2> DynamicExceptionRanges;
3588         Expr *NoexceptExpr = nullptr;
3589
3590         if (FTI.getExceptionSpecType() == EST_Dynamic) {
3591           // FIXME: It's rather inefficient to have to split into two vectors
3592           // here.
3593           unsigned N = FTI.NumExceptions;
3594           DynamicExceptions.reserve(N);
3595           DynamicExceptionRanges.reserve(N);
3596           for (unsigned I = 0; I != N; ++I) {
3597             DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
3598             DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
3599           }
3600         } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
3601           NoexceptExpr = FTI.NoexceptExpr;
3602         }
3603
3604         S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
3605                                       FTI.getExceptionSpecType(),
3606                                       DynamicExceptions,
3607                                       DynamicExceptionRanges,
3608                                       NoexceptExpr,
3609                                       Exceptions,
3610                                       EPI.ExceptionSpec);
3611
3612         T = Context.getFunctionType(T, ParamTys, EPI);
3613       }
3614
3615       break;
3616     }
3617     case DeclaratorChunk::MemberPointer:
3618       // The scope spec must refer to a class, or be dependent.
3619       CXXScopeSpec &SS = DeclType.Mem.Scope();
3620       QualType ClsType;
3621
3622       // Handle pointer nullability.
3623       inferPointerNullability(SimplePointerKind::MemberPointer,
3624                               DeclType.Loc, DeclType.getAttrListRef());
3625
3626       if (SS.isInvalid()) {
3627         // Avoid emitting extra errors if we already errored on the scope.
3628         D.setInvalidType(true);
3629       } else if (S.isDependentScopeSpecifier(SS) ||
3630                  dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
3631         NestedNameSpecifier *NNS = SS.getScopeRep();
3632         NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
3633         switch (NNS->getKind()) {
3634         case NestedNameSpecifier::Identifier:
3635           ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
3636                                                  NNS->getAsIdentifier());
3637           break;
3638
3639         case NestedNameSpecifier::Namespace:
3640         case NestedNameSpecifier::NamespaceAlias:
3641         case NestedNameSpecifier::Global:
3642         case NestedNameSpecifier::Super:
3643           llvm_unreachable("Nested-name-specifier must name a type");
3644
3645         case NestedNameSpecifier::TypeSpec:
3646         case NestedNameSpecifier::TypeSpecWithTemplate:
3647           ClsType = QualType(NNS->getAsType(), 0);
3648           // Note: if the NNS has a prefix and ClsType is a nondependent
3649           // TemplateSpecializationType, then the NNS prefix is NOT included
3650           // in ClsType; hence we wrap ClsType into an ElaboratedType.
3651           // NOTE: in particular, no wrap occurs if ClsType already is an
3652           // Elaborated, DependentName, or DependentTemplateSpecialization.
3653           if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
3654             ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
3655           break;
3656         }
3657       } else {
3658         S.Diag(DeclType.Mem.Scope().getBeginLoc(),
3659              diag::err_illegal_decl_mempointer_in_nonclass)
3660           << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
3661           << DeclType.Mem.Scope().getRange();
3662         D.setInvalidType(true);
3663       }
3664
3665       if (!ClsType.isNull())
3666         T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
3667                                      D.getIdentifier());
3668       if (T.isNull()) {
3669         T = Context.IntTy;
3670         D.setInvalidType(true);
3671       } else if (DeclType.Mem.TypeQuals) {
3672         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
3673       }
3674       break;
3675     }
3676
3677     if (T.isNull()) {
3678       D.setInvalidType(true);
3679       T = Context.IntTy;
3680     }
3681
3682     // See if there are any attributes on this declarator chunk.
3683     if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
3684       processTypeAttrs(state, T, TAL_DeclChunk, attrs);
3685   }
3686
3687   assert(!T.isNull() && "T must not be null after this point");
3688
3689   if (LangOpts.CPlusPlus && T->isFunctionType()) {
3690     const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
3691     assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
3692
3693     // C++ 8.3.5p4:
3694     //   A cv-qualifier-seq shall only be part of the function type
3695     //   for a nonstatic member function, the function type to which a pointer
3696     //   to member refers, or the top-level function type of a function typedef
3697     //   declaration.
3698     //
3699     // Core issue 547 also allows cv-qualifiers on function types that are
3700     // top-level template type arguments.
3701     bool FreeFunction;
3702     if (!D.getCXXScopeSpec().isSet()) {
3703       FreeFunction = ((D.getContext() != Declarator::MemberContext &&
3704                        D.getContext() != Declarator::LambdaExprContext) ||
3705                       D.getDeclSpec().isFriendSpecified());
3706     } else {
3707       DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
3708       FreeFunction = (DC && !DC->isRecord());
3709     }
3710
3711     // C++11 [dcl.fct]p6 (w/DR1417):
3712     // An attempt to specify a function type with a cv-qualifier-seq or a
3713     // ref-qualifier (including by typedef-name) is ill-formed unless it is:
3714     //  - the function type for a non-static member function,
3715     //  - the function type to which a pointer to member refers,
3716     //  - the top-level function type of a function typedef declaration or
3717     //    alias-declaration,
3718     //  - the type-id in the default argument of a type-parameter, or
3719     //  - the type-id of a template-argument for a type-parameter
3720     //
3721     // FIXME: Checking this here is insufficient. We accept-invalid on:
3722     //
3723     //   template<typename T> struct S { void f(T); };
3724     //   S<int() const> s;
3725     //
3726     // ... for instance.
3727     if (IsQualifiedFunction &&
3728         !(!FreeFunction &&
3729           D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
3730         !IsTypedefName &&
3731         D.getContext() != Declarator::TemplateTypeArgContext) {
3732       SourceLocation Loc = D.getLocStart();
3733       SourceRange RemovalRange;
3734       unsigned I;
3735       if (D.isFunctionDeclarator(I)) {
3736         SmallVector<SourceLocation, 4> RemovalLocs;
3737         const DeclaratorChunk &Chunk = D.getTypeObject(I);
3738         assert(Chunk.Kind == DeclaratorChunk::Function);
3739         if (Chunk.Fun.hasRefQualifier())
3740           RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
3741         if (Chunk.Fun.TypeQuals & Qualifiers::Const)
3742           RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
3743         if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
3744           RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
3745         if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
3746           RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
3747         if (!RemovalLocs.empty()) {
3748           std::sort(RemovalLocs.begin(), RemovalLocs.end(),
3749                     BeforeThanCompare<SourceLocation>(S.getSourceManager()));
3750           RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
3751           Loc = RemovalLocs.front();
3752         }
3753       }
3754
3755       S.Diag(Loc, diag::err_invalid_qualified_function_type)
3756         << FreeFunction << D.isFunctionDeclarator() << T
3757         << getFunctionQualifiersAsString(FnTy)
3758         << FixItHint::CreateRemoval(RemovalRange);
3759
3760       // Strip the cv-qualifiers and ref-qualifiers from the type.
3761       FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
3762       EPI.TypeQuals = 0;
3763       EPI.RefQualifier = RQ_None;
3764
3765       T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
3766                                   EPI);
3767       // Rebuild any parens around the identifier in the function type.
3768       for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3769         if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
3770           break;
3771         T = S.BuildParenType(T);
3772       }
3773     }
3774   }
3775
3776   // Apply any undistributed attributes from the declarator.
3777   if (AttributeList *attrs = D.getAttributes())
3778     processTypeAttrs(state, T, TAL_DeclName, attrs);
3779
3780   // Diagnose any ignored type attributes.
3781   state.diagnoseIgnoredTypeAttrs(T);
3782
3783   // C++0x [dcl.constexpr]p9:
3784   //  A constexpr specifier used in an object declaration declares the object
3785   //  as const.
3786   if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
3787     T.addConst();
3788   }
3789
3790   // If there was an ellipsis in the declarator, the declaration declares a
3791   // parameter pack whose type may be a pack expansion type.
3792   if (D.hasEllipsis()) {
3793     // C++0x [dcl.fct]p13:
3794     //   A declarator-id or abstract-declarator containing an ellipsis shall
3795     //   only be used in a parameter-declaration. Such a parameter-declaration
3796     //   is a parameter pack (14.5.3). [...]
3797     switch (D.getContext()) {
3798     case Declarator::PrototypeContext:
3799     case Declarator::LambdaExprParameterContext:
3800       // C++0x [dcl.fct]p13:
3801       //   [...] When it is part of a parameter-declaration-clause, the
3802       //   parameter pack is a function parameter pack (14.5.3). The type T
3803       //   of the declarator-id of the function parameter pack shall contain
3804       //   a template parameter pack; each template parameter pack in T is
3805       //   expanded by the function parameter pack.
3806       //
3807       // We represent function parameter packs as function parameters whose
3808       // type is a pack expansion.
3809       if (!T->containsUnexpandedParameterPack()) {
3810         S.Diag(D.getEllipsisLoc(),
3811              diag::err_function_parameter_pack_without_parameter_packs)
3812           << T <<  D.getSourceRange();
3813         D.setEllipsisLoc(SourceLocation());
3814       } else {
3815         T = Context.getPackExpansionType(T, None);
3816       }
3817       break;
3818     case Declarator::TemplateParamContext:
3819       // C++0x [temp.param]p15:
3820       //   If a template-parameter is a [...] is a parameter-declaration that
3821       //   declares a parameter pack (8.3.5), then the template-parameter is a
3822       //   template parameter pack (14.5.3).
3823       //
3824       // Note: core issue 778 clarifies that, if there are any unexpanded
3825       // parameter packs in the type of the non-type template parameter, then
3826       // it expands those parameter packs.
3827       if (T->containsUnexpandedParameterPack())
3828         T = Context.getPackExpansionType(T, None);
3829       else
3830         S.Diag(D.getEllipsisLoc(),
3831                LangOpts.CPlusPlus11
3832                  ? diag::warn_cxx98_compat_variadic_templates
3833                  : diag::ext_variadic_templates);
3834       break;
3835
3836     case Declarator::FileContext:
3837     case Declarator::KNRTypeListContext:
3838     case Declarator::ObjCParameterContext:  // FIXME: special diagnostic here?
3839     case Declarator::ObjCResultContext:     // FIXME: special diagnostic here?
3840     case Declarator::TypeNameContext:
3841     case Declarator::CXXNewContext:
3842     case Declarator::AliasDeclContext:
3843     case Declarator::AliasTemplateContext:
3844     case Declarator::MemberContext:
3845     case Declarator::BlockContext:
3846     case Declarator::ForContext:
3847     case Declarator::ConditionContext:
3848     case Declarator::CXXCatchContext:
3849     case Declarator::ObjCCatchContext:
3850     case Declarator::BlockLiteralContext:
3851     case Declarator::LambdaExprContext:
3852     case Declarator::ConversionIdContext:
3853     case Declarator::TrailingReturnContext:
3854     case Declarator::TemplateTypeArgContext:
3855       // FIXME: We may want to allow parameter packs in block-literal contexts
3856       // in the future.
3857       S.Diag(D.getEllipsisLoc(),
3858              diag::err_ellipsis_in_declarator_not_parameter);
3859       D.setEllipsisLoc(SourceLocation());
3860       break;
3861     }
3862   }
3863
3864   assert(!T.isNull() && "T must not be null at the end of this function");
3865   if (D.isInvalidType())
3866     return Context.getTrivialTypeSourceInfo(T);
3867
3868   return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
3869 }
3870
3871 /// GetTypeForDeclarator - Convert the type for the specified
3872 /// declarator to Type instances.
3873 ///
3874 /// The result of this call will never be null, but the associated
3875 /// type may be a null type if there's an unrecoverable error.
3876 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
3877   // Determine the type of the declarator. Not all forms of declarator
3878   // have a type.
3879
3880   TypeProcessingState state(*this, D);
3881
3882   TypeSourceInfo *ReturnTypeInfo = nullptr;
3883   QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
3884
3885   if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
3886     inferARCWriteback(state, T);
3887
3888   return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
3889 }
3890
3891 static void transferARCOwnershipToDeclSpec(Sema &S,
3892                                            QualType &declSpecTy,
3893                                            Qualifiers::ObjCLifetime ownership) {
3894   if (declSpecTy->isObjCRetainableType() &&
3895       declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
3896     Qualifiers qs;
3897     qs.addObjCLifetime(ownership);
3898     declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
3899   }
3900 }
3901
3902 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
3903                                             Qualifiers::ObjCLifetime ownership,
3904                                             unsigned chunkIndex) {
3905   Sema &S = state.getSema();
3906   Declarator &D = state.getDeclarator();
3907
3908   // Look for an explicit lifetime attribute.
3909   DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
3910   for (const AttributeList *attr = chunk.getAttrs(); attr;
3911          attr = attr->getNext())
3912     if (attr->getKind() == AttributeList::AT_ObjCOwnership)
3913       return;
3914
3915   const char *attrStr = nullptr;
3916   switch (ownership) {
3917   case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
3918   case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
3919   case Qualifiers::OCL_Strong: attrStr = "strong"; break;
3920   case Qualifiers::OCL_Weak: attrStr = "weak"; break;
3921   case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
3922   }
3923
3924   IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
3925   Arg->Ident = &S.Context.Idents.get(attrStr);
3926   Arg->Loc = SourceLocation();
3927
3928   ArgsUnion Args(Arg);
3929
3930   // If there wasn't one, add one (with an invalid source location
3931   // so that we don't make an AttributedType for it).
3932   AttributeList *attr = D.getAttributePool()
3933     .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
3934             /*scope*/ nullptr, SourceLocation(),
3935             /*args*/ &Args, 1, AttributeList::AS_GNU);
3936   spliceAttrIntoList(*attr, chunk.getAttrListRef());
3937
3938   // TODO: mark whether we did this inference?
3939 }
3940
3941 /// \brief Used for transferring ownership in casts resulting in l-values.
3942 static void transferARCOwnership(TypeProcessingState &state,
3943                                  QualType &declSpecTy,
3944                                  Qualifiers::ObjCLifetime ownership) {
3945   Sema &S = state.getSema();
3946   Declarator &D = state.getDeclarator();
3947
3948   int inner = -1;
3949   bool hasIndirection = false;
3950   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3951     DeclaratorChunk &chunk = D.getTypeObject(i);
3952     switch (chunk.Kind) {
3953     case DeclaratorChunk::Paren:
3954       // Ignore parens.
3955       break;
3956
3957     case DeclaratorChunk::Array:
3958     case DeclaratorChunk::Reference:
3959     case DeclaratorChunk::Pointer:
3960       if (inner != -1)
3961         hasIndirection = true;
3962       inner = i;
3963       break;
3964
3965     case DeclaratorChunk::BlockPointer:
3966       if (inner != -1)
3967         transferARCOwnershipToDeclaratorChunk(state, ownership, i);
3968       return;
3969
3970     case DeclaratorChunk::Function:
3971     case DeclaratorChunk::MemberPointer:
3972       return;
3973     }
3974   }
3975
3976   if (inner == -1)
3977     return;
3978
3979   DeclaratorChunk &chunk = D.getTypeObject(inner);
3980   if (chunk.Kind == DeclaratorChunk::Pointer) {
3981     if (declSpecTy->isObjCRetainableType())
3982       return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
3983     if (declSpecTy->isObjCObjectType() && hasIndirection)
3984       return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
3985   } else {
3986     assert(chunk.Kind == DeclaratorChunk::Array ||
3987            chunk.Kind == DeclaratorChunk::Reference);
3988     return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
3989   }
3990 }
3991
3992 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
3993   TypeProcessingState state(*this, D);
3994
3995   TypeSourceInfo *ReturnTypeInfo = nullptr;
3996   QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
3997
3998   if (getLangOpts().ObjCAutoRefCount) {
3999     Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
4000     if (ownership != Qualifiers::OCL_None)
4001       transferARCOwnership(state, declSpecTy, ownership);
4002   }
4003
4004   return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
4005 }
4006
4007 /// Map an AttributedType::Kind to an AttributeList::Kind.
4008 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
4009   switch (kind) {
4010   case AttributedType::attr_address_space:
4011     return AttributeList::AT_AddressSpace;
4012   case AttributedType::attr_regparm:
4013     return AttributeList::AT_Regparm;
4014   case AttributedType::attr_vector_size:
4015     return AttributeList::AT_VectorSize;
4016   case AttributedType::attr_neon_vector_type:
4017     return AttributeList::AT_NeonVectorType;
4018   case AttributedType::attr_neon_polyvector_type:
4019     return AttributeList::AT_NeonPolyVectorType;
4020   case AttributedType::attr_objc_gc:
4021     return AttributeList::AT_ObjCGC;
4022   case AttributedType::attr_objc_ownership:
4023     return AttributeList::AT_ObjCOwnership;
4024   case AttributedType::attr_noreturn:
4025     return AttributeList::AT_NoReturn;
4026   case AttributedType::attr_cdecl:
4027     return AttributeList::AT_CDecl;
4028   case AttributedType::attr_fastcall:
4029     return AttributeList::AT_FastCall;
4030   case AttributedType::attr_stdcall:
4031     return AttributeList::AT_StdCall;
4032   case AttributedType::attr_thiscall:
4033     return AttributeList::AT_ThisCall;
4034   case AttributedType::attr_pascal:
4035     return AttributeList::AT_Pascal;
4036   case AttributedType::attr_vectorcall:
4037     return AttributeList::AT_VectorCall;
4038   case AttributedType::attr_pcs:
4039   case AttributedType::attr_pcs_vfp:
4040     return AttributeList::AT_Pcs;
4041   case AttributedType::attr_inteloclbicc:
4042     return AttributeList::AT_IntelOclBicc;
4043   case AttributedType::attr_ms_abi:
4044     return AttributeList::AT_MSABI;
4045   case AttributedType::attr_sysv_abi:
4046     return AttributeList::AT_SysVABI;
4047   case AttributedType::attr_ptr32:
4048     return AttributeList::AT_Ptr32;
4049   case AttributedType::attr_ptr64:
4050     return AttributeList::AT_Ptr64;
4051   case AttributedType::attr_sptr:
4052     return AttributeList::AT_SPtr;
4053   case AttributedType::attr_uptr:
4054     return AttributeList::AT_UPtr;
4055   case AttributedType::attr_nonnull:
4056     return AttributeList::AT_TypeNonNull;
4057   case AttributedType::attr_nullable:
4058     return AttributeList::AT_TypeNullable;
4059   case AttributedType::attr_null_unspecified:
4060     return AttributeList::AT_TypeNullUnspecified;
4061   }
4062   llvm_unreachable("unexpected attribute kind!");
4063 }
4064
4065 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
4066                                   const AttributeList *attrs,
4067                                   const AttributeList *DeclAttrs = nullptr) {
4068   // DeclAttrs and attrs cannot be both empty.
4069   assert((attrs || DeclAttrs) &&
4070          "no type attributes in the expected location!");
4071
4072   AttributeList::Kind parsedKind = getAttrListKind(TL.getAttrKind());
4073   // Try to search for an attribute of matching kind in attrs list.
4074   while (attrs && attrs->getKind() != parsedKind)
4075     attrs = attrs->getNext();
4076   if (!attrs) {
4077     // No matching type attribute in attrs list found.
4078     // Try searching through C++11 attributes in the declarator attribute list.
4079     while (DeclAttrs && (!DeclAttrs->isCXX11Attribute() ||
4080                          DeclAttrs->getKind() != parsedKind))
4081       DeclAttrs = DeclAttrs->getNext();
4082     attrs = DeclAttrs;
4083   }
4084
4085   assert(attrs && "no matching type attribute in expected location!");
4086
4087   TL.setAttrNameLoc(attrs->getLoc());
4088   if (TL.hasAttrExprOperand()) {
4089     assert(attrs->isArgExpr(0) && "mismatched attribute operand kind");
4090     TL.setAttrExprOperand(attrs->getArgAsExpr(0));
4091   } else if (TL.hasAttrEnumOperand()) {
4092     assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) &&
4093            "unexpected attribute operand kind");
4094     if (attrs->isArgIdent(0))
4095       TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc);
4096     else
4097       TL.setAttrEnumOperandLoc(attrs->getArgAsExpr(0)->getExprLoc());
4098   }
4099
4100   // FIXME: preserve this information to here.
4101   if (TL.hasAttrOperand())
4102     TL.setAttrOperandParensRange(SourceRange());
4103 }
4104
4105 namespace {
4106   class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
4107     ASTContext &Context;
4108     const DeclSpec &DS;
4109
4110   public:
4111     TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
4112       : Context(Context), DS(DS) {}
4113
4114     void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
4115       fillAttributedTypeLoc(TL, DS.getAttributes().getList());
4116       Visit(TL.getModifiedLoc());
4117     }
4118     void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4119       Visit(TL.getUnqualifiedLoc());
4120     }
4121     void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
4122       TL.setNameLoc(DS.getTypeSpecTypeLoc());
4123     }
4124     void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
4125       TL.setNameLoc(DS.getTypeSpecTypeLoc());
4126       // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
4127       // addition field. What we have is good enough for dispay of location
4128       // of 'fixit' on interface name.
4129       TL.setNameEndLoc(DS.getLocEnd());
4130     }
4131     void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
4132       // Handle the base type, which might not have been written explicitly.
4133       if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
4134         TL.setHasBaseTypeAsWritten(false);
4135         TL.getBaseLoc().initialize(Context, SourceLocation());
4136       } else {
4137         TL.setHasBaseTypeAsWritten(true);
4138         Visit(TL.getBaseLoc());
4139       }
4140
4141       // Protocol qualifiers.
4142       if (DS.getProtocolQualifiers()) {
4143         assert(TL.getNumProtocols() > 0);
4144         assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
4145         TL.setLAngleLoc(DS.getProtocolLAngleLoc());
4146         TL.setRAngleLoc(DS.getSourceRange().getEnd());
4147         for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
4148           TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
4149       } else {
4150         assert(TL.getNumProtocols() == 0);
4151         TL.setLAngleLoc(SourceLocation());
4152         TL.setRAngleLoc(SourceLocation());
4153       }
4154     }
4155     void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
4156       TL.setStarLoc(SourceLocation());
4157       Visit(TL.getPointeeLoc());
4158     }
4159     void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
4160       TypeSourceInfo *TInfo = nullptr;
4161       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4162
4163       // If we got no declarator info from previous Sema routines,
4164       // just fill with the typespec loc.
4165       if (!TInfo) {
4166         TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
4167         return;
4168       }
4169
4170       TypeLoc OldTL = TInfo->getTypeLoc();
4171       if (TInfo->getType()->getAs<ElaboratedType>()) {
4172         ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
4173         TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
4174             .castAs<TemplateSpecializationTypeLoc>();
4175         TL.copy(NamedTL);
4176       } else {
4177         TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
4178         assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
4179       }
4180         
4181     }
4182     void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
4183       assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
4184       TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
4185       TL.setParensRange(DS.getTypeofParensRange());
4186     }
4187     void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
4188       assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
4189       TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
4190       TL.setParensRange(DS.getTypeofParensRange());
4191       assert(DS.getRepAsType());
4192       TypeSourceInfo *TInfo = nullptr;
4193       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4194       TL.setUnderlyingTInfo(TInfo);
4195     }
4196     void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
4197       // FIXME: This holds only because we only have one unary transform.
4198       assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
4199       TL.setKWLoc(DS.getTypeSpecTypeLoc());
4200       TL.setParensRange(DS.getTypeofParensRange());
4201       assert(DS.getRepAsType());
4202       TypeSourceInfo *TInfo = nullptr;
4203       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4204       TL.setUnderlyingTInfo(TInfo);
4205     }
4206     void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
4207       // By default, use the source location of the type specifier.
4208       TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
4209       if (TL.needsExtraLocalData()) {
4210         // Set info for the written builtin specifiers.
4211         TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
4212         // Try to have a meaningful source location.
4213         if (TL.getWrittenSignSpec() != TSS_unspecified)
4214           // Sign spec loc overrides the others (e.g., 'unsigned long').
4215           TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
4216         else if (TL.getWrittenWidthSpec() != TSW_unspecified)
4217           // Width spec loc overrides type spec loc (e.g., 'short int').
4218           TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
4219       }
4220     }
4221     void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
4222       ElaboratedTypeKeyword Keyword
4223         = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
4224       if (DS.getTypeSpecType() == TST_typename) {
4225         TypeSourceInfo *TInfo = nullptr;
4226         Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4227         if (TInfo) {
4228           TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
4229           return;
4230         }
4231       }
4232       TL.setElaboratedKeywordLoc(Keyword != ETK_None
4233                                  ? DS.getTypeSpecTypeLoc()
4234                                  : SourceLocation());
4235       const CXXScopeSpec& SS = DS.getTypeSpecScope();
4236       TL.setQualifierLoc(SS.getWithLocInContext(Context));
4237       Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
4238     }
4239     void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
4240       assert(DS.getTypeSpecType() == TST_typename);
4241       TypeSourceInfo *TInfo = nullptr;
4242       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4243       assert(TInfo);
4244       TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
4245     }
4246     void VisitDependentTemplateSpecializationTypeLoc(
4247                                  DependentTemplateSpecializationTypeLoc TL) {
4248       assert(DS.getTypeSpecType() == TST_typename);
4249       TypeSourceInfo *TInfo = nullptr;
4250       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4251       assert(TInfo);
4252       TL.copy(
4253           TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
4254     }
4255     void VisitTagTypeLoc(TagTypeLoc TL) {
4256       TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
4257     }
4258     void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
4259       // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
4260       // or an _Atomic qualifier.
4261       if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
4262         TL.setKWLoc(DS.getTypeSpecTypeLoc());
4263         TL.setParensRange(DS.getTypeofParensRange());
4264
4265         TypeSourceInfo *TInfo = nullptr;
4266         Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4267         assert(TInfo);
4268         TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
4269       } else {
4270         TL.setKWLoc(DS.getAtomicSpecLoc());
4271         // No parens, to indicate this was spelled as an _Atomic qualifier.
4272         TL.setParensRange(SourceRange());
4273         Visit(TL.getValueLoc());
4274       }
4275     }
4276
4277     void VisitTypeLoc(TypeLoc TL) {
4278       // FIXME: add other typespec types and change this to an assert.
4279       TL.initialize(Context, DS.getTypeSpecTypeLoc());
4280     }
4281   };
4282
4283   class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
4284     ASTContext &Context;
4285     const DeclaratorChunk &Chunk;
4286
4287   public:
4288     DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
4289       : Context(Context), Chunk(Chunk) {}
4290
4291     void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4292       llvm_unreachable("qualified type locs not expected here!");
4293     }
4294     void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
4295       llvm_unreachable("decayed type locs not expected here!");
4296     }
4297
4298     void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
4299       fillAttributedTypeLoc(TL, Chunk.getAttrs());
4300     }
4301     void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
4302       // nothing
4303     }
4304     void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
4305       assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
4306       TL.setCaretLoc(Chunk.Loc);
4307     }
4308     void VisitPointerTypeLoc(PointerTypeLoc TL) {
4309       assert(Chunk.Kind == DeclaratorChunk::Pointer);
4310       TL.setStarLoc(Chunk.Loc);
4311     }
4312     void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
4313       assert(Chunk.Kind == DeclaratorChunk::Pointer);
4314       TL.setStarLoc(Chunk.Loc);
4315     }
4316     void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
4317       assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
4318       const CXXScopeSpec& SS = Chunk.Mem.Scope();
4319       NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
4320
4321       const Type* ClsTy = TL.getClass();
4322       QualType ClsQT = QualType(ClsTy, 0);
4323       TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
4324       // Now copy source location info into the type loc component.
4325       TypeLoc ClsTL = ClsTInfo->getTypeLoc();
4326       switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
4327       case NestedNameSpecifier::Identifier:
4328         assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
4329         {
4330           DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
4331           DNTLoc.setElaboratedKeywordLoc(SourceLocation());
4332           DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
4333           DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
4334         }
4335         break;
4336
4337       case NestedNameSpecifier::TypeSpec:
4338       case NestedNameSpecifier::TypeSpecWithTemplate:
4339         if (isa<ElaboratedType>(ClsTy)) {
4340           ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
4341           ETLoc.setElaboratedKeywordLoc(SourceLocation());
4342           ETLoc.setQualifierLoc(NNSLoc.getPrefix());
4343           TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
4344           NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
4345         } else {
4346           ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
4347         }
4348         break;
4349
4350       case NestedNameSpecifier::Namespace:
4351       case NestedNameSpecifier::NamespaceAlias:
4352       case NestedNameSpecifier::Global:
4353       case NestedNameSpecifier::Super:
4354         llvm_unreachable("Nested-name-specifier must name a type");
4355       }
4356
4357       // Finally fill in MemberPointerLocInfo fields.
4358       TL.setStarLoc(Chunk.Loc);
4359       TL.setClassTInfo(ClsTInfo);
4360     }
4361     void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
4362       assert(Chunk.Kind == DeclaratorChunk::Reference);
4363       // 'Amp' is misleading: this might have been originally
4364       /// spelled with AmpAmp.
4365       TL.setAmpLoc(Chunk.Loc);
4366     }
4367     void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
4368       assert(Chunk.Kind == DeclaratorChunk::Reference);
4369       assert(!Chunk.Ref.LValueRef);
4370       TL.setAmpAmpLoc(Chunk.Loc);
4371     }
4372     void VisitArrayTypeLoc(ArrayTypeLoc TL) {
4373       assert(Chunk.Kind == DeclaratorChunk::Array);
4374       TL.setLBracketLoc(Chunk.Loc);
4375       TL.setRBracketLoc(Chunk.EndLoc);
4376       TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
4377     }
4378     void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
4379       assert(Chunk.Kind == DeclaratorChunk::Function);
4380       TL.setLocalRangeBegin(Chunk.Loc);
4381       TL.setLocalRangeEnd(Chunk.EndLoc);
4382
4383       const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
4384       TL.setLParenLoc(FTI.getLParenLoc());
4385       TL.setRParenLoc(FTI.getRParenLoc());
4386       for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
4387         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
4388         TL.setParam(tpi++, Param);
4389       }
4390       // FIXME: exception specs
4391     }
4392     void VisitParenTypeLoc(ParenTypeLoc TL) {
4393       assert(Chunk.Kind == DeclaratorChunk::Paren);
4394       TL.setLParenLoc(Chunk.Loc);
4395       TL.setRParenLoc(Chunk.EndLoc);
4396     }
4397
4398     void VisitTypeLoc(TypeLoc TL) {
4399       llvm_unreachable("unsupported TypeLoc kind in declarator!");
4400     }
4401   };
4402 }
4403
4404 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
4405   SourceLocation Loc;
4406   switch (Chunk.Kind) {
4407   case DeclaratorChunk::Function:
4408   case DeclaratorChunk::Array:
4409   case DeclaratorChunk::Paren:
4410     llvm_unreachable("cannot be _Atomic qualified");
4411
4412   case DeclaratorChunk::Pointer:
4413     Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
4414     break;
4415
4416   case DeclaratorChunk::BlockPointer:
4417   case DeclaratorChunk::Reference:
4418   case DeclaratorChunk::MemberPointer:
4419     // FIXME: Provide a source location for the _Atomic keyword.
4420     break;
4421   }
4422
4423   ATL.setKWLoc(Loc);
4424   ATL.setParensRange(SourceRange());
4425 }
4426
4427 /// \brief Create and instantiate a TypeSourceInfo with type source information.
4428 ///
4429 /// \param T QualType referring to the type as written in source code.
4430 ///
4431 /// \param ReturnTypeInfo For declarators whose return type does not show
4432 /// up in the normal place in the declaration specifiers (such as a C++
4433 /// conversion function), this pointer will refer to a type source information
4434 /// for that return type.
4435 TypeSourceInfo *
4436 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
4437                                      TypeSourceInfo *ReturnTypeInfo) {
4438   TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
4439   UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
4440   const AttributeList *DeclAttrs = D.getAttributes();
4441
4442   // Handle parameter packs whose type is a pack expansion.
4443   if (isa<PackExpansionType>(T)) {
4444     CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
4445     CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
4446   }
4447
4448   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4449     // An AtomicTypeLoc might be produced by an atomic qualifier in this
4450     // declarator chunk.
4451     if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
4452       fillAtomicQualLoc(ATL, D.getTypeObject(i));
4453       CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
4454     }
4455
4456     while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
4457       fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs(), DeclAttrs);
4458       CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
4459     }
4460
4461     // FIXME: Ordering here?
4462     while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
4463       CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
4464
4465     DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
4466     CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
4467   }
4468
4469   // If we have different source information for the return type, use
4470   // that.  This really only applies to C++ conversion functions.
4471   if (ReturnTypeInfo) {
4472     TypeLoc TL = ReturnTypeInfo->getTypeLoc();
4473     assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
4474     memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
4475   } else {
4476     TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
4477   }
4478
4479   return TInfo;
4480 }
4481
4482 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
4483 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
4484   // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
4485   // and Sema during declaration parsing. Try deallocating/caching them when
4486   // it's appropriate, instead of allocating them and keeping them around.
4487   LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
4488                                                        TypeAlignment);
4489   new (LocT) LocInfoType(T, TInfo);
4490   assert(LocT->getTypeClass() != T->getTypeClass() &&
4491          "LocInfoType's TypeClass conflicts with an existing Type class");
4492   return ParsedType::make(QualType(LocT, 0));
4493 }
4494
4495 void LocInfoType::getAsStringInternal(std::string &Str,
4496                                       const PrintingPolicy &Policy) const {
4497   llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
4498          " was used directly instead of getting the QualType through"
4499          " GetTypeFromParser");
4500 }
4501
4502 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
4503   // C99 6.7.6: Type names have no identifier.  This is already validated by
4504   // the parser.
4505   assert(D.getIdentifier() == nullptr &&
4506          "Type name should have no identifier!");
4507
4508   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4509   QualType T = TInfo->getType();
4510   if (D.isInvalidType())
4511     return true;
4512
4513   // Make sure there are no unused decl attributes on the declarator.
4514   // We don't want to do this for ObjC parameters because we're going
4515   // to apply them to the actual parameter declaration.
4516   // Likewise, we don't want to do this for alias declarations, because
4517   // we are actually going to build a declaration from this eventually.
4518   if (D.getContext() != Declarator::ObjCParameterContext &&
4519       D.getContext() != Declarator::AliasDeclContext &&
4520       D.getContext() != Declarator::AliasTemplateContext)
4521     checkUnusedDeclAttributes(D);
4522
4523   if (getLangOpts().CPlusPlus) {
4524     // Check that there are no default arguments (C++ only).
4525     CheckExtraCXXDefaultArguments(D);
4526   }
4527
4528   return CreateParsedType(T, TInfo);
4529 }
4530
4531 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
4532   QualType T = Context.getObjCInstanceType();
4533   TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
4534   return CreateParsedType(T, TInfo);
4535 }
4536
4537
4538 //===----------------------------------------------------------------------===//
4539 // Type Attribute Processing
4540 //===----------------------------------------------------------------------===//
4541
4542 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
4543 /// specified type.  The attribute contains 1 argument, the id of the address
4544 /// space for the type.
4545 static void HandleAddressSpaceTypeAttribute(QualType &Type,
4546                                             const AttributeList &Attr, Sema &S){
4547
4548   // If this type is already address space qualified, reject it.
4549   // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
4550   // qualifiers for two or more different address spaces."
4551   if (Type.getAddressSpace()) {
4552     S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
4553     Attr.setInvalid();
4554     return;
4555   }
4556
4557   // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
4558   // qualified by an address-space qualifier."
4559   if (Type->isFunctionType()) {
4560     S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
4561     Attr.setInvalid();
4562     return;
4563   }
4564
4565   unsigned ASIdx;
4566   if (Attr.getKind() == AttributeList::AT_AddressSpace) {
4567     // Check the attribute arguments.
4568     if (Attr.getNumArgs() != 1) {
4569       S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4570         << Attr.getName() << 1;
4571       Attr.setInvalid();
4572       return;
4573     }
4574     Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4575     llvm::APSInt addrSpace(32);
4576     if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
4577         !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
4578       S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
4579         << Attr.getName() << AANT_ArgumentIntegerConstant
4580         << ASArgExpr->getSourceRange();
4581       Attr.setInvalid();
4582       return;
4583     }
4584
4585     // Bounds checking.
4586     if (addrSpace.isSigned()) {
4587       if (addrSpace.isNegative()) {
4588         S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
4589           << ASArgExpr->getSourceRange();
4590         Attr.setInvalid();
4591         return;
4592       }
4593       addrSpace.setIsSigned(false);
4594     }
4595     llvm::APSInt max(addrSpace.getBitWidth());
4596     max = Qualifiers::MaxAddressSpace;
4597     if (addrSpace > max) {
4598       S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
4599         << int(Qualifiers::MaxAddressSpace) << ASArgExpr->getSourceRange();
4600       Attr.setInvalid();
4601       return;
4602     }
4603     ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
4604   } else {
4605     // The keyword-based type attributes imply which address space to use.
4606     switch (Attr.getKind()) {
4607     case AttributeList::AT_OpenCLGlobalAddressSpace:
4608       ASIdx = LangAS::opencl_global; break;
4609     case AttributeList::AT_OpenCLLocalAddressSpace:
4610       ASIdx = LangAS::opencl_local; break;
4611     case AttributeList::AT_OpenCLConstantAddressSpace:
4612       ASIdx = LangAS::opencl_constant; break;
4613     case AttributeList::AT_OpenCLGenericAddressSpace:
4614       ASIdx = LangAS::opencl_generic; break;
4615     default:
4616       assert(Attr.getKind() == AttributeList::AT_OpenCLPrivateAddressSpace);
4617       ASIdx = 0; break;
4618     }
4619   }
4620   
4621   Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
4622 }
4623
4624 /// Does this type have a "direct" ownership qualifier?  That is,
4625 /// is it written like "__strong id", as opposed to something like
4626 /// "typeof(foo)", where that happens to be strong?
4627 static bool hasDirectOwnershipQualifier(QualType type) {
4628   // Fast path: no qualifier at all.
4629   assert(type.getQualifiers().hasObjCLifetime());
4630
4631   while (true) {
4632     // __strong id
4633     if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
4634       if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
4635         return true;
4636
4637       type = attr->getModifiedType();
4638
4639     // X *__strong (...)
4640     } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
4641       type = paren->getInnerType();
4642
4643     // That's it for things we want to complain about.  In particular,
4644     // we do not want to look through typedefs, typeof(expr),
4645     // typeof(type), or any other way that the type is somehow
4646     // abstracted.
4647     } else {
4648
4649       return false;
4650     }
4651   }
4652 }
4653
4654 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
4655 /// attribute on the specified type.
4656 ///
4657 /// Returns 'true' if the attribute was handled.
4658 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
4659                                        AttributeList &attr,
4660                                        QualType &type) {
4661   bool NonObjCPointer = false;
4662
4663   if (!type->isDependentType() && !type->isUndeducedType()) {
4664     if (const PointerType *ptr = type->getAs<PointerType>()) {
4665       QualType pointee = ptr->getPointeeType();
4666       if (pointee->isObjCRetainableType() || pointee->isPointerType())
4667         return false;
4668       // It is important not to lose the source info that there was an attribute
4669       // applied to non-objc pointer. We will create an attributed type but
4670       // its type will be the same as the original type.
4671       NonObjCPointer = true;
4672     } else if (!type->isObjCRetainableType()) {
4673       return false;
4674     }
4675
4676     // Don't accept an ownership attribute in the declspec if it would
4677     // just be the return type of a block pointer.
4678     if (state.isProcessingDeclSpec()) {
4679       Declarator &D = state.getDeclarator();
4680       if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
4681                                   /*onlyBlockPointers=*/true))
4682         return false;
4683     }
4684   }
4685
4686   Sema &S = state.getSema();
4687   SourceLocation AttrLoc = attr.getLoc();
4688   if (AttrLoc.isMacroID())
4689     AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
4690
4691   if (!attr.isArgIdent(0)) {
4692     S.Diag(AttrLoc, diag::err_attribute_argument_type)
4693       << attr.getName() << AANT_ArgumentString;
4694     attr.setInvalid();
4695     return true;
4696   }
4697
4698   // Consume lifetime attributes without further comment outside of
4699   // ARC mode.
4700   if (!S.getLangOpts().ObjCAutoRefCount)
4701     return true;
4702
4703   IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
4704   Qualifiers::ObjCLifetime lifetime;
4705   if (II->isStr("none"))
4706     lifetime = Qualifiers::OCL_ExplicitNone;
4707   else if (II->isStr("strong"))
4708     lifetime = Qualifiers::OCL_Strong;
4709   else if (II->isStr("weak"))
4710     lifetime = Qualifiers::OCL_Weak;
4711   else if (II->isStr("autoreleasing"))
4712     lifetime = Qualifiers::OCL_Autoreleasing;
4713   else {
4714     S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
4715       << attr.getName() << II;
4716     attr.setInvalid();
4717     return true;
4718   }
4719
4720   SplitQualType underlyingType = type.split();
4721
4722   // Check for redundant/conflicting ownership qualifiers.
4723   if (Qualifiers::ObjCLifetime previousLifetime
4724         = type.getQualifiers().getObjCLifetime()) {
4725     // If it's written directly, that's an error.
4726     if (hasDirectOwnershipQualifier(type)) {
4727       S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
4728         << type;
4729       return true;
4730     }
4731
4732     // Otherwise, if the qualifiers actually conflict, pull sugar off
4733     // until we reach a type that is directly qualified.
4734     if (previousLifetime != lifetime) {
4735       // This should always terminate: the canonical type is
4736       // qualified, so some bit of sugar must be hiding it.
4737       while (!underlyingType.Quals.hasObjCLifetime()) {
4738         underlyingType = underlyingType.getSingleStepDesugaredType();
4739       }
4740       underlyingType.Quals.removeObjCLifetime();
4741     }
4742   }
4743
4744   underlyingType.Quals.addObjCLifetime(lifetime);
4745
4746   if (NonObjCPointer) {
4747     StringRef name = attr.getName()->getName();
4748     switch (lifetime) {
4749     case Qualifiers::OCL_None:
4750     case Qualifiers::OCL_ExplicitNone:
4751       break;
4752     case Qualifiers::OCL_Strong: name = "__strong"; break;
4753     case Qualifiers::OCL_Weak: name = "__weak"; break;
4754     case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
4755     }
4756     S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
4757       << TDS_ObjCObjOrBlock << type;
4758   }
4759
4760   QualType origType = type;
4761   if (!NonObjCPointer)
4762     type = S.Context.getQualifiedType(underlyingType);
4763
4764   // If we have a valid source location for the attribute, use an
4765   // AttributedType instead.
4766   if (AttrLoc.isValid())
4767     type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
4768                                        origType, type);
4769
4770   // Forbid __weak if the runtime doesn't support it.
4771   if (lifetime == Qualifiers::OCL_Weak &&
4772       !S.getLangOpts().ObjCARCWeak && !NonObjCPointer) {
4773
4774     // Actually, delay this until we know what we're parsing.
4775     if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
4776       S.DelayedDiagnostics.add(
4777           sema::DelayedDiagnostic::makeForbiddenType(
4778               S.getSourceManager().getExpansionLoc(AttrLoc),
4779               diag::err_arc_weak_no_runtime, type, /*ignored*/ 0));
4780     } else {
4781       S.Diag(AttrLoc, diag::err_arc_weak_no_runtime);
4782     }
4783
4784     attr.setInvalid();
4785     return true;
4786   }
4787
4788   // Forbid __weak for class objects marked as
4789   // objc_arc_weak_reference_unavailable
4790   if (lifetime == Qualifiers::OCL_Weak) {
4791     if (const ObjCObjectPointerType *ObjT =
4792           type->getAs<ObjCObjectPointerType>()) {
4793       if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
4794         if (Class->isArcWeakrefUnavailable()) {
4795             S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
4796             S.Diag(ObjT->getInterfaceDecl()->getLocation(),
4797                    diag::note_class_declared);
4798         }
4799       }
4800     }
4801   }
4802
4803   return true;
4804 }
4805
4806 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
4807 /// attribute on the specified type.  Returns true to indicate that
4808 /// the attribute was handled, false to indicate that the type does
4809 /// not permit the attribute.
4810 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
4811                                  AttributeList &attr,
4812                                  QualType &type) {
4813   Sema &S = state.getSema();
4814
4815   // Delay if this isn't some kind of pointer.
4816   if (!type->isPointerType() &&
4817       !type->isObjCObjectPointerType() &&
4818       !type->isBlockPointerType())
4819     return false;
4820
4821   if (type.getObjCGCAttr() != Qualifiers::GCNone) {
4822     S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
4823     attr.setInvalid();
4824     return true;
4825   }
4826   
4827   // Check the attribute arguments.
4828   if (!attr.isArgIdent(0)) {
4829     S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
4830       << attr.getName() << AANT_ArgumentString;
4831     attr.setInvalid();
4832     return true;
4833   }
4834   Qualifiers::GC GCAttr;
4835   if (attr.getNumArgs() > 1) {
4836     S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4837       << attr.getName() << 1;
4838     attr.setInvalid();
4839     return true;
4840   }
4841
4842   IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
4843   if (II->isStr("weak"))
4844     GCAttr = Qualifiers::Weak;
4845   else if (II->isStr("strong"))
4846     GCAttr = Qualifiers::Strong;
4847   else {
4848     S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
4849       << attr.getName() << II;
4850     attr.setInvalid();
4851     return true;
4852   }
4853
4854   QualType origType = type;
4855   type = S.Context.getObjCGCQualType(origType, GCAttr);
4856
4857   // Make an attributed type to preserve the source information.
4858   if (attr.getLoc().isValid())
4859     type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
4860                                        origType, type);
4861
4862   return true;
4863 }
4864
4865 namespace {
4866   /// A helper class to unwrap a type down to a function for the
4867   /// purposes of applying attributes there.
4868   ///
4869   /// Use:
4870   ///   FunctionTypeUnwrapper unwrapped(SemaRef, T);
4871   ///   if (unwrapped.isFunctionType()) {
4872   ///     const FunctionType *fn = unwrapped.get();
4873   ///     // change fn somehow
4874   ///     T = unwrapped.wrap(fn);
4875   ///   }
4876   struct FunctionTypeUnwrapper {
4877     enum WrapKind {
4878       Desugar,
4879       Parens,
4880       Pointer,
4881       BlockPointer,
4882       Reference,
4883       MemberPointer
4884     };
4885
4886     QualType Original;
4887     const FunctionType *Fn;
4888     SmallVector<unsigned char /*WrapKind*/, 8> Stack;
4889
4890     FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
4891       while (true) {
4892         const Type *Ty = T.getTypePtr();
4893         if (isa<FunctionType>(Ty)) {
4894           Fn = cast<FunctionType>(Ty);
4895           return;
4896         } else if (isa<ParenType>(Ty)) {
4897           T = cast<ParenType>(Ty)->getInnerType();
4898           Stack.push_back(Parens);
4899         } else if (isa<PointerType>(Ty)) {
4900           T = cast<PointerType>(Ty)->getPointeeType();
4901           Stack.push_back(Pointer);
4902         } else if (isa<BlockPointerType>(Ty)) {
4903           T = cast<BlockPointerType>(Ty)->getPointeeType();
4904           Stack.push_back(BlockPointer);
4905         } else if (isa<MemberPointerType>(Ty)) {
4906           T = cast<MemberPointerType>(Ty)->getPointeeType();
4907           Stack.push_back(MemberPointer);
4908         } else if (isa<ReferenceType>(Ty)) {
4909           T = cast<ReferenceType>(Ty)->getPointeeType();
4910           Stack.push_back(Reference);
4911         } else {
4912           const Type *DTy = Ty->getUnqualifiedDesugaredType();
4913           if (Ty == DTy) {
4914             Fn = nullptr;
4915             return;
4916           }
4917
4918           T = QualType(DTy, 0);
4919           Stack.push_back(Desugar);
4920         }
4921       }
4922     }
4923
4924     bool isFunctionType() const { return (Fn != nullptr); }
4925     const FunctionType *get() const { return Fn; }
4926
4927     QualType wrap(Sema &S, const FunctionType *New) {
4928       // If T wasn't modified from the unwrapped type, do nothing.
4929       if (New == get()) return Original;
4930
4931       Fn = New;
4932       return wrap(S.Context, Original, 0);
4933     }
4934
4935   private:
4936     QualType wrap(ASTContext &C, QualType Old, unsigned I) {
4937       if (I == Stack.size())
4938         return C.getQualifiedType(Fn, Old.getQualifiers());
4939
4940       // Build up the inner type, applying the qualifiers from the old
4941       // type to the new type.
4942       SplitQualType SplitOld = Old.split();
4943
4944       // As a special case, tail-recurse if there are no qualifiers.
4945       if (SplitOld.Quals.empty())
4946         return wrap(C, SplitOld.Ty, I);
4947       return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
4948     }
4949
4950     QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
4951       if (I == Stack.size()) return QualType(Fn, 0);
4952
4953       switch (static_cast<WrapKind>(Stack[I++])) {
4954       case Desugar:
4955         // This is the point at which we potentially lose source
4956         // information.
4957         return wrap(C, Old->getUnqualifiedDesugaredType(), I);
4958
4959       case Parens: {
4960         QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
4961         return C.getParenType(New);
4962       }
4963
4964       case Pointer: {
4965         QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
4966         return C.getPointerType(New);
4967       }
4968
4969       case BlockPointer: {
4970         QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
4971         return C.getBlockPointerType(New);
4972       }
4973
4974       case MemberPointer: {
4975         const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
4976         QualType New = wrap(C, OldMPT->getPointeeType(), I);
4977         return C.getMemberPointerType(New, OldMPT->getClass());
4978       }
4979
4980       case Reference: {
4981         const ReferenceType *OldRef = cast<ReferenceType>(Old);
4982         QualType New = wrap(C, OldRef->getPointeeType(), I);
4983         if (isa<LValueReferenceType>(OldRef))
4984           return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
4985         else
4986           return C.getRValueReferenceType(New);
4987       }
4988       }
4989
4990       llvm_unreachable("unknown wrapping kind");
4991     }
4992   };
4993 }
4994
4995 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
4996                                              AttributeList &Attr,
4997                                              QualType &Type) {
4998   Sema &S = State.getSema();
4999
5000   AttributeList::Kind Kind = Attr.getKind();
5001   QualType Desugared = Type;
5002   const AttributedType *AT = dyn_cast<AttributedType>(Type);
5003   while (AT) {
5004     AttributedType::Kind CurAttrKind = AT->getAttrKind();
5005
5006     // You cannot specify duplicate type attributes, so if the attribute has
5007     // already been applied, flag it.
5008     if (getAttrListKind(CurAttrKind) == Kind) {
5009       S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact)
5010         << Attr.getName();
5011       return true;
5012     }
5013
5014     // You cannot have both __sptr and __uptr on the same type, nor can you
5015     // have __ptr32 and __ptr64.
5016     if ((CurAttrKind == AttributedType::attr_ptr32 &&
5017          Kind == AttributeList::AT_Ptr64) ||
5018         (CurAttrKind == AttributedType::attr_ptr64 &&
5019          Kind == AttributeList::AT_Ptr32)) {
5020       S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
5021         << "'__ptr32'" << "'__ptr64'";
5022       return true;
5023     } else if ((CurAttrKind == AttributedType::attr_sptr &&
5024                 Kind == AttributeList::AT_UPtr) ||
5025                (CurAttrKind == AttributedType::attr_uptr &&
5026                 Kind == AttributeList::AT_SPtr)) {
5027       S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
5028         << "'__sptr'" << "'__uptr'";
5029       return true;
5030     }
5031     
5032     Desugared = AT->getEquivalentType();
5033     AT = dyn_cast<AttributedType>(Desugared);
5034   }
5035
5036   // Pointer type qualifiers can only operate on pointer types, but not
5037   // pointer-to-member types.
5038   if (!isa<PointerType>(Desugared)) {
5039     S.Diag(Attr.getLoc(), Type->isMemberPointerType() ?
5040                           diag::err_attribute_no_member_pointers :
5041                           diag::err_attribute_pointers_only) << Attr.getName();
5042     return true;
5043   }
5044
5045   AttributedType::Kind TAK;
5046   switch (Kind) {
5047   default: llvm_unreachable("Unknown attribute kind");
5048   case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break;
5049   case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break;
5050   case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break;
5051   case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break;
5052   }
5053
5054   Type = S.Context.getAttributedType(TAK, Type, Type);
5055   return false;
5056 }
5057
5058 bool Sema::checkNullabilityTypeSpecifier(QualType &type,
5059                                          NullabilityKind nullability,
5060                                          SourceLocation nullabilityLoc,
5061                                          bool isContextSensitive) {
5062   // We saw a nullability type specifier. If this is the first one for
5063   // this file, note that.
5064   FileID file = getNullabilityCompletenessCheckFileID(*this, nullabilityLoc);
5065   if (!file.isInvalid()) {
5066     FileNullability &fileNullability = NullabilityMap[file];
5067     if (!fileNullability.SawTypeNullability) {
5068       // If we have already seen a pointer declarator without a nullability
5069       // annotation, complain about it.
5070       if (fileNullability.PointerLoc.isValid()) {
5071         Diag(fileNullability.PointerLoc, diag::warn_nullability_missing)
5072           << static_cast<unsigned>(fileNullability.PointerKind);
5073       }
5074
5075       fileNullability.SawTypeNullability = true;
5076     }
5077   }
5078
5079   // Check for existing nullability attributes on the type.
5080   QualType desugared = type;
5081   while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
5082     // Check whether there is already a null
5083     if (auto existingNullability = attributed->getImmediateNullability()) {
5084       // Duplicated nullability.
5085       if (nullability == *existingNullability) {
5086         Diag(nullabilityLoc, diag::warn_nullability_duplicate)
5087           << static_cast<unsigned>(nullability)
5088           << isContextSensitive
5089           << FixItHint::CreateRemoval(nullabilityLoc);
5090
5091         break;
5092       } 
5093
5094       // Conflicting nullability.
5095       Diag(nullabilityLoc, diag::err_nullability_conflicting)
5096         << static_cast<unsigned>(nullability) 
5097         << isContextSensitive
5098         << static_cast<unsigned>(*existingNullability)
5099         << false;
5100       return true;
5101     }
5102
5103     desugared = attributed->getModifiedType();
5104   }
5105
5106   // If there is already a different nullability specifier, complain.
5107   // This (unlike the code above) looks through typedefs that might
5108   // have nullability specifiers on them, which means we cannot
5109   // provide a useful Fix-It.
5110   if (auto existingNullability = desugared->getNullability(Context)) {
5111     if (nullability != *existingNullability) {
5112       Diag(nullabilityLoc, diag::err_nullability_conflicting)
5113         << static_cast<unsigned>(nullability)
5114         << isContextSensitive
5115         << static_cast<unsigned>(*existingNullability)
5116         << false;
5117
5118       // Try to find the typedef with the existing nullability specifier.
5119       if (auto typedefType = desugared->getAs<TypedefType>()) {
5120         TypedefNameDecl *typedefDecl = typedefType->getDecl();
5121         QualType underlyingType = typedefDecl->getUnderlyingType();
5122         if (auto typedefNullability
5123               = AttributedType::stripOuterNullability(underlyingType)) {
5124           if (*typedefNullability == *existingNullability) {
5125             Diag(typedefDecl->getLocation(), diag::note_nullability_here)
5126               << static_cast<unsigned>(*existingNullability);
5127           }
5128         }
5129       }
5130
5131       return true;
5132     }
5133   }
5134
5135   // If this definitely isn't a pointer type, reject the specifier.
5136   if (!desugared->canHaveNullability()) {
5137     Diag(nullabilityLoc, diag::err_nullability_nonpointer)
5138       << static_cast<unsigned>(nullability) << isContextSensitive << type;
5139     return true;
5140   }
5141   
5142   // For the context-sensitive keywords/Objective-C property
5143   // attributes, require that the type be a single-level pointer.
5144   if (isContextSensitive) {
5145     // Make sure that the pointee isn't itself a pointer type.
5146     QualType pointeeType = desugared->getPointeeType();
5147     if (pointeeType->isAnyPointerType() ||
5148         pointeeType->isObjCObjectPointerType() ||
5149         pointeeType->isMemberPointerType()) {
5150       Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
5151         << static_cast<unsigned>(nullability)
5152         << type;
5153       Diag(nullabilityLoc, diag::note_nullability_type_specifier)
5154         << static_cast<unsigned>(nullability)
5155         << type
5156         << FixItHint::CreateReplacement(nullabilityLoc,
5157                                         getNullabilitySpelling(nullability));
5158       return true;
5159     }
5160   }
5161
5162   // Form the attributed type.
5163   type = Context.getAttributedType(
5164            AttributedType::getNullabilityAttrKind(nullability), type, type);
5165   return false;
5166 }
5167
5168 /// Map a nullability attribute kind to a nullability kind.
5169 static NullabilityKind mapNullabilityAttrKind(AttributeList::Kind kind) {
5170   switch (kind) {
5171   case AttributeList::AT_TypeNonNull:
5172     return NullabilityKind::NonNull;
5173
5174   case AttributeList::AT_TypeNullable:
5175     return NullabilityKind::Nullable;
5176
5177   case AttributeList::AT_TypeNullUnspecified:
5178     return NullabilityKind::Unspecified;
5179
5180   default:
5181     llvm_unreachable("not a nullability attribute kind");
5182   }
5183 }
5184
5185 /// Distribute a nullability type attribute that cannot be applied to
5186 /// the type specifier to a pointer, block pointer, or member pointer
5187 /// declarator, complaining if necessary.
5188 ///
5189 /// \returns true if the nullability annotation was distributed, false
5190 /// otherwise.
5191 static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
5192                                           QualType type,
5193                                           AttributeList &attr) {
5194   Declarator &declarator = state.getDeclarator();
5195
5196   /// Attempt to move the attribute to the specified chunk.
5197   auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
5198     // If there is already a nullability attribute there, don't add
5199     // one.
5200     if (hasNullabilityAttr(chunk.getAttrListRef()))
5201       return false;
5202
5203     // Complain about the nullability qualifier being in the wrong
5204     // place.
5205     unsigned pointerKind
5206       = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? 3 : 0)
5207         : chunk.Kind == DeclaratorChunk::BlockPointer ? 1
5208         : inFunction? 4 : 2;
5209
5210     auto diag = state.getSema().Diag(attr.getLoc(),
5211                                      diag::warn_nullability_declspec)
5212       << static_cast<unsigned>(mapNullabilityAttrKind(attr.getKind()))
5213       << type
5214       << pointerKind;
5215
5216     // FIXME: MemberPointer chunks don't carry the location of the *.
5217     if (chunk.Kind != DeclaratorChunk::MemberPointer) {
5218       diag << FixItHint::CreateRemoval(attr.getLoc())
5219            << FixItHint::CreateInsertion(
5220                 state.getSema().getPreprocessor()
5221                   .getLocForEndOfToken(chunk.Loc),
5222                 " " + attr.getName()->getName().str() + " ");
5223     }
5224
5225     moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
5226                            chunk.getAttrListRef());
5227     return true;
5228   };
5229
5230   // Move it to the outermost pointer, member pointer, or block
5231   // pointer declarator.
5232   for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
5233     DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
5234     switch (chunk.Kind) {
5235     case DeclaratorChunk::Pointer:
5236     case DeclaratorChunk::BlockPointer:
5237     case DeclaratorChunk::MemberPointer:
5238       return moveToChunk(chunk, false);
5239
5240     case DeclaratorChunk::Paren:
5241     case DeclaratorChunk::Array:
5242       continue;
5243
5244     case DeclaratorChunk::Function:
5245       // Try to move past the return type to a function/block/member
5246       // function pointer.
5247       if (DeclaratorChunk *dest = maybeMovePastReturnType(
5248                                     declarator, i,
5249                                     /*onlyBlockPointers=*/false)) {
5250         return moveToChunk(*dest, true);
5251       }
5252
5253       return false;
5254       
5255     // Don't walk through these.
5256     case DeclaratorChunk::Reference:
5257       return false;
5258     }
5259   }
5260
5261   return false;
5262 }
5263
5264 static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) {
5265   assert(!Attr.isInvalid());
5266   switch (Attr.getKind()) {
5267   default:
5268     llvm_unreachable("not a calling convention attribute");
5269   case AttributeList::AT_CDecl:
5270     return AttributedType::attr_cdecl;
5271   case AttributeList::AT_FastCall:
5272     return AttributedType::attr_fastcall;
5273   case AttributeList::AT_StdCall:
5274     return AttributedType::attr_stdcall;
5275   case AttributeList::AT_ThisCall:
5276     return AttributedType::attr_thiscall;
5277   case AttributeList::AT_Pascal:
5278     return AttributedType::attr_pascal;
5279   case AttributeList::AT_VectorCall:
5280     return AttributedType::attr_vectorcall;
5281   case AttributeList::AT_Pcs: {
5282     // The attribute may have had a fixit applied where we treated an
5283     // identifier as a string literal.  The contents of the string are valid,
5284     // but the form may not be.
5285     StringRef Str;
5286     if (Attr.isArgExpr(0))
5287       Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
5288     else
5289       Str = Attr.getArgAsIdent(0)->Ident->getName();
5290     return llvm::StringSwitch<AttributedType::Kind>(Str)
5291         .Case("aapcs", AttributedType::attr_pcs)
5292         .Case("aapcs-vfp", AttributedType::attr_pcs_vfp);
5293   }
5294   case AttributeList::AT_IntelOclBicc:
5295     return AttributedType::attr_inteloclbicc;
5296   case AttributeList::AT_MSABI:
5297     return AttributedType::attr_ms_abi;
5298   case AttributeList::AT_SysVABI:
5299     return AttributedType::attr_sysv_abi;
5300   }
5301   llvm_unreachable("unexpected attribute kind!");
5302 }
5303
5304 /// Process an individual function attribute.  Returns true to
5305 /// indicate that the attribute was handled, false if it wasn't.
5306 static bool handleFunctionTypeAttr(TypeProcessingState &state,
5307                                    AttributeList &attr,
5308                                    QualType &type) {
5309   Sema &S = state.getSema();
5310
5311   FunctionTypeUnwrapper unwrapped(S, type);
5312
5313   if (attr.getKind() == AttributeList::AT_NoReturn) {
5314     if (S.CheckNoReturnAttr(attr))
5315       return true;
5316
5317     // Delay if this is not a function type.
5318     if (!unwrapped.isFunctionType())
5319       return false;
5320
5321     // Otherwise we can process right away.
5322     FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
5323     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5324     return true;
5325   }
5326
5327   // ns_returns_retained is not always a type attribute, but if we got
5328   // here, we're treating it as one right now.
5329   if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
5330     assert(S.getLangOpts().ObjCAutoRefCount &&
5331            "ns_returns_retained treated as type attribute in non-ARC");
5332     if (attr.getNumArgs()) return true;
5333
5334     // Delay if this is not a function type.
5335     if (!unwrapped.isFunctionType())
5336       return false;
5337
5338     FunctionType::ExtInfo EI
5339       = unwrapped.get()->getExtInfo().withProducesResult(true);
5340     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5341     return true;
5342   }
5343
5344   if (attr.getKind() == AttributeList::AT_Regparm) {
5345     unsigned value;
5346     if (S.CheckRegparmAttr(attr, value))
5347       return true;
5348
5349     // Delay if this is not a function type.
5350     if (!unwrapped.isFunctionType())
5351       return false;
5352
5353     // Diagnose regparm with fastcall.
5354     const FunctionType *fn = unwrapped.get();
5355     CallingConv CC = fn->getCallConv();
5356     if (CC == CC_X86FastCall) {
5357       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
5358         << FunctionType::getNameForCallConv(CC)
5359         << "regparm";
5360       attr.setInvalid();
5361       return true;
5362     }
5363
5364     FunctionType::ExtInfo EI =
5365       unwrapped.get()->getExtInfo().withRegParm(value);
5366     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5367     return true;
5368   }
5369
5370   // Delay if the type didn't work out to a function.
5371   if (!unwrapped.isFunctionType()) return false;
5372
5373   // Otherwise, a calling convention.
5374   CallingConv CC;
5375   if (S.CheckCallingConvAttr(attr, CC))
5376     return true;
5377
5378   const FunctionType *fn = unwrapped.get();
5379   CallingConv CCOld = fn->getCallConv();
5380   AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr);
5381
5382   if (CCOld != CC) {
5383     // Error out on when there's already an attribute on the type
5384     // and the CCs don't match.
5385     const AttributedType *AT = S.getCallingConvAttributedType(type);
5386     if (AT && AT->getAttrKind() != CCAttrKind) {
5387       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
5388         << FunctionType::getNameForCallConv(CC)
5389         << FunctionType::getNameForCallConv(CCOld);
5390       attr.setInvalid();
5391       return true;
5392     }
5393   }
5394
5395   // Diagnose use of callee-cleanup calling convention on variadic functions.
5396   if (!supportsVariadicCall(CC)) {
5397     const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
5398     if (FnP && FnP->isVariadic()) {
5399       unsigned DiagID = diag::err_cconv_varargs;
5400       // stdcall and fastcall are ignored with a warning for GCC and MS
5401       // compatibility.
5402       if (CC == CC_X86StdCall || CC == CC_X86FastCall)
5403         DiagID = diag::warn_cconv_varargs;
5404
5405       S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC);
5406       attr.setInvalid();
5407       return true;
5408     }
5409   }
5410
5411   // Also diagnose fastcall with regparm.
5412   if (CC == CC_X86FastCall && fn->getHasRegParm()) {
5413     S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
5414         << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
5415     attr.setInvalid();
5416     return true;
5417   }
5418
5419   // Modify the CC from the wrapped function type, wrap it all back, and then
5420   // wrap the whole thing in an AttributedType as written.  The modified type
5421   // might have a different CC if we ignored the attribute.
5422   FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
5423   QualType Equivalent =
5424       unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5425   type = S.Context.getAttributedType(CCAttrKind, type, Equivalent);
5426   return true;
5427 }
5428
5429 bool Sema::hasExplicitCallingConv(QualType &T) {
5430   QualType R = T.IgnoreParens();
5431   while (const AttributedType *AT = dyn_cast<AttributedType>(R)) {
5432     if (AT->isCallingConv())
5433       return true;
5434     R = AT->getModifiedType().IgnoreParens();
5435   }
5436   return false;
5437 }
5438
5439 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic) {
5440   FunctionTypeUnwrapper Unwrapped(*this, T);
5441   const FunctionType *FT = Unwrapped.get();
5442   bool IsVariadic = (isa<FunctionProtoType>(FT) &&
5443                      cast<FunctionProtoType>(FT)->isVariadic());
5444
5445   // Only adjust types with the default convention.  For example, on Windows we
5446   // should adjust a __cdecl type to __thiscall for instance methods, and a
5447   // __thiscall type to __cdecl for static methods.
5448   CallingConv CurCC = FT->getCallConv();
5449   CallingConv FromCC =
5450       Context.getDefaultCallingConvention(IsVariadic, IsStatic);
5451   CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
5452   if (CurCC != FromCC || FromCC == ToCC)
5453     return;
5454
5455   if (hasExplicitCallingConv(T))
5456     return;
5457
5458   FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
5459   QualType Wrapped = Unwrapped.wrap(*this, FT);
5460   T = Context.getAdjustedType(T, Wrapped);
5461 }
5462
5463 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
5464 /// and float scalars, although arrays, pointers, and function return values are
5465 /// allowed in conjunction with this construct. Aggregates with this attribute
5466 /// are invalid, even if they are of the same size as a corresponding scalar.
5467 /// The raw attribute should contain precisely 1 argument, the vector size for
5468 /// the variable, measured in bytes. If curType and rawAttr are well formed,
5469 /// this routine will return a new vector type.
5470 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
5471                                  Sema &S) {
5472   // Check the attribute arguments.
5473   if (Attr.getNumArgs() != 1) {
5474     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5475       << Attr.getName() << 1;
5476     Attr.setInvalid();
5477     return;
5478   }
5479   Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5480   llvm::APSInt vecSize(32);
5481   if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
5482       !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
5483     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
5484       << Attr.getName() << AANT_ArgumentIntegerConstant
5485       << sizeExpr->getSourceRange();
5486     Attr.setInvalid();
5487     return;
5488   }
5489   // The base type must be integer (not Boolean or enumeration) or float, and
5490   // can't already be a vector.
5491   if (!CurType->isBuiltinType() || CurType->isBooleanType() ||
5492       (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
5493     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
5494     Attr.setInvalid();
5495     return;
5496   }
5497   unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
5498   // vecSize is specified in bytes - convert to bits.
5499   unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
5500
5501   // the vector size needs to be an integral multiple of the type size.
5502   if (vectorSize % typeSize) {
5503     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
5504       << sizeExpr->getSourceRange();
5505     Attr.setInvalid();
5506     return;
5507   }
5508   if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) {
5509     S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large)
5510       << sizeExpr->getSourceRange();
5511     Attr.setInvalid();
5512     return;
5513   }
5514   if (vectorSize == 0) {
5515     S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
5516       << sizeExpr->getSourceRange();
5517     Attr.setInvalid();
5518     return;
5519   }
5520
5521   // Success! Instantiate the vector type, the number of elements is > 0, and
5522   // not required to be a power of 2, unlike GCC.
5523   CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
5524                                     VectorType::GenericVector);
5525 }
5526
5527 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
5528 /// a type.
5529 static void HandleExtVectorTypeAttr(QualType &CurType,
5530                                     const AttributeList &Attr,
5531                                     Sema &S) {
5532   // check the attribute arguments.
5533   if (Attr.getNumArgs() != 1) {
5534     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5535       << Attr.getName() << 1;
5536     return;
5537   }
5538
5539   Expr *sizeExpr;
5540
5541   // Special case where the argument is a template id.
5542   if (Attr.isArgIdent(0)) {
5543     CXXScopeSpec SS;
5544     SourceLocation TemplateKWLoc;
5545     UnqualifiedId id;
5546     id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
5547
5548     ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
5549                                           id, false, false);
5550     if (Size.isInvalid())
5551       return;
5552
5553     sizeExpr = Size.get();
5554   } else {
5555     sizeExpr = Attr.getArgAsExpr(0);
5556   }
5557
5558   // Create the vector type.
5559   QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
5560   if (!T.isNull())
5561     CurType = T;
5562 }
5563
5564 static bool isPermittedNeonBaseType(QualType &Ty,
5565                                     VectorType::VectorKind VecKind, Sema &S) {
5566   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
5567   if (!BTy)
5568     return false;
5569
5570   llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
5571
5572   // Signed poly is mathematically wrong, but has been baked into some ABIs by
5573   // now.
5574   bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
5575                         Triple.getArch() == llvm::Triple::aarch64_be;
5576   if (VecKind == VectorType::NeonPolyVector) {
5577     if (IsPolyUnsigned) {
5578       // AArch64 polynomial vectors are unsigned and support poly64.
5579       return BTy->getKind() == BuiltinType::UChar ||
5580              BTy->getKind() == BuiltinType::UShort ||
5581              BTy->getKind() == BuiltinType::ULong ||
5582              BTy->getKind() == BuiltinType::ULongLong;
5583     } else {
5584       // AArch32 polynomial vector are signed.
5585       return BTy->getKind() == BuiltinType::SChar ||
5586              BTy->getKind() == BuiltinType::Short;
5587     }
5588   }
5589
5590   // Non-polynomial vector types: the usual suspects are allowed, as well as
5591   // float64_t on AArch64.
5592   bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 ||
5593                  Triple.getArch() == llvm::Triple::aarch64_be;
5594
5595   if (Is64Bit && BTy->getKind() == BuiltinType::Double)
5596     return true;
5597
5598   return BTy->getKind() == BuiltinType::SChar ||
5599          BTy->getKind() == BuiltinType::UChar ||
5600          BTy->getKind() == BuiltinType::Short ||
5601          BTy->getKind() == BuiltinType::UShort ||
5602          BTy->getKind() == BuiltinType::Int ||
5603          BTy->getKind() == BuiltinType::UInt ||
5604          BTy->getKind() == BuiltinType::Long ||
5605          BTy->getKind() == BuiltinType::ULong ||
5606          BTy->getKind() == BuiltinType::LongLong ||
5607          BTy->getKind() == BuiltinType::ULongLong ||
5608          BTy->getKind() == BuiltinType::Float ||
5609          BTy->getKind() == BuiltinType::Half;
5610 }
5611
5612 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
5613 /// "neon_polyvector_type" attributes are used to create vector types that
5614 /// are mangled according to ARM's ABI.  Otherwise, these types are identical
5615 /// to those created with the "vector_size" attribute.  Unlike "vector_size"
5616 /// the argument to these Neon attributes is the number of vector elements,
5617 /// not the vector size in bytes.  The vector width and element type must
5618 /// match one of the standard Neon vector types.
5619 static void HandleNeonVectorTypeAttr(QualType& CurType,
5620                                      const AttributeList &Attr, Sema &S,
5621                                      VectorType::VectorKind VecKind) {
5622   // Target must have NEON
5623   if (!S.Context.getTargetInfo().hasFeature("neon")) {
5624     S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName();
5625     Attr.setInvalid();
5626     return;
5627   }
5628   // Check the attribute arguments.
5629   if (Attr.getNumArgs() != 1) {
5630     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5631       << Attr.getName() << 1;
5632     Attr.setInvalid();
5633     return;
5634   }
5635   // The number of elements must be an ICE.
5636   Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5637   llvm::APSInt numEltsInt(32);
5638   if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
5639       !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
5640     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
5641       << Attr.getName() << AANT_ArgumentIntegerConstant
5642       << numEltsExpr->getSourceRange();
5643     Attr.setInvalid();
5644     return;
5645   }
5646   // Only certain element types are supported for Neon vectors.
5647   if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
5648     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
5649     Attr.setInvalid();
5650     return;
5651   }
5652
5653   // The total size of the vector must be 64 or 128 bits.
5654   unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
5655   unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
5656   unsigned vecSize = typeSize * numElts;
5657   if (vecSize != 64 && vecSize != 128) {
5658     S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
5659     Attr.setInvalid();
5660     return;
5661   }
5662
5663   CurType = S.Context.getVectorType(CurType, numElts, VecKind);
5664 }
5665
5666 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
5667                              TypeAttrLocation TAL, AttributeList *attrs) {
5668   // Scan through and apply attributes to this type where it makes sense.  Some
5669   // attributes (such as __address_space__, __vector_size__, etc) apply to the
5670   // type, but others can be present in the type specifiers even though they
5671   // apply to the decl.  Here we apply type attributes and ignore the rest.
5672
5673   AttributeList *next;
5674   do {
5675     AttributeList &attr = *attrs;
5676     next = attr.getNext();
5677
5678     // Skip attributes that were marked to be invalid.
5679     if (attr.isInvalid())
5680       continue;
5681
5682     if (attr.isCXX11Attribute()) {
5683       // [[gnu::...]] attributes are treated as declaration attributes, so may
5684       // not appertain to a DeclaratorChunk, even if we handle them as type
5685       // attributes.
5686       if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
5687         if (TAL == TAL_DeclChunk) {
5688           state.getSema().Diag(attr.getLoc(),
5689                                diag::warn_cxx11_gnu_attribute_on_type)
5690               << attr.getName();
5691           continue;
5692         }
5693       } else if (TAL != TAL_DeclChunk) {
5694         // Otherwise, only consider type processing for a C++11 attribute if
5695         // it's actually been applied to a type.
5696         continue;
5697       }
5698     }
5699
5700     // If this is an attribute we can handle, do so now,
5701     // otherwise, add it to the FnAttrs list for rechaining.
5702     switch (attr.getKind()) {
5703     default:
5704       // A C++11 attribute on a declarator chunk must appertain to a type.
5705       if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
5706         state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
5707           << attr.getName();
5708         attr.setUsedAsTypeAttr();
5709       }
5710       break;
5711
5712     case AttributeList::UnknownAttribute:
5713       if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
5714         state.getSema().Diag(attr.getLoc(),
5715                              diag::warn_unknown_attribute_ignored)
5716           << attr.getName();
5717       break;
5718
5719     case AttributeList::IgnoredAttribute:
5720       break;
5721
5722     case AttributeList::AT_MayAlias:
5723       // FIXME: This attribute needs to actually be handled, but if we ignore
5724       // it it breaks large amounts of Linux software.
5725       attr.setUsedAsTypeAttr();
5726       break;
5727     case AttributeList::AT_OpenCLPrivateAddressSpace:
5728     case AttributeList::AT_OpenCLGlobalAddressSpace:
5729     case AttributeList::AT_OpenCLLocalAddressSpace:
5730     case AttributeList::AT_OpenCLConstantAddressSpace:
5731     case AttributeList::AT_OpenCLGenericAddressSpace:
5732     case AttributeList::AT_AddressSpace:
5733       HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
5734       attr.setUsedAsTypeAttr();
5735       break;
5736     OBJC_POINTER_TYPE_ATTRS_CASELIST:
5737       if (!handleObjCPointerTypeAttr(state, attr, type))
5738         distributeObjCPointerTypeAttr(state, attr, type);
5739       attr.setUsedAsTypeAttr();
5740       break;
5741     case AttributeList::AT_VectorSize:
5742       HandleVectorSizeAttr(type, attr, state.getSema());
5743       attr.setUsedAsTypeAttr();
5744       break;
5745     case AttributeList::AT_ExtVectorType:
5746       HandleExtVectorTypeAttr(type, attr, state.getSema());
5747       attr.setUsedAsTypeAttr();
5748       break;
5749     case AttributeList::AT_NeonVectorType:
5750       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
5751                                VectorType::NeonVector);
5752       attr.setUsedAsTypeAttr();
5753       break;
5754     case AttributeList::AT_NeonPolyVectorType:
5755       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
5756                                VectorType::NeonPolyVector);
5757       attr.setUsedAsTypeAttr();
5758       break;
5759     case AttributeList::AT_OpenCLImageAccess:
5760       // FIXME: there should be some type checking happening here, I would
5761       // imagine, but the original handler's checking was entirely superfluous.
5762       attr.setUsedAsTypeAttr();
5763       break;
5764
5765     MS_TYPE_ATTRS_CASELIST:
5766       if (!handleMSPointerTypeQualifierAttr(state, attr, type))
5767         attr.setUsedAsTypeAttr();
5768       break;
5769
5770     NULLABILITY_TYPE_ATTRS_CASELIST:
5771       // Either add nullability here or try to distribute it.  We
5772       // don't want to distribute the nullability specifier past any
5773       // dependent type, because that complicates the user model.
5774       if (type->canHaveNullability() || type->isDependentType() ||
5775           !distributeNullabilityTypeAttr(state, type, attr)) {
5776         if (state.getSema().checkNullabilityTypeSpecifier(
5777               type,
5778               mapNullabilityAttrKind(attr.getKind()),
5779               attr.getLoc(),
5780               attr.isContextSensitiveKeywordAttribute())) {
5781           attr.setInvalid();
5782         }
5783
5784         attr.setUsedAsTypeAttr();
5785       }
5786       break;
5787
5788     case AttributeList::AT_NSReturnsRetained:
5789       if (!state.getSema().getLangOpts().ObjCAutoRefCount)
5790         break;
5791       // fallthrough into the function attrs
5792
5793     FUNCTION_TYPE_ATTRS_CASELIST:
5794       attr.setUsedAsTypeAttr();
5795
5796       // Never process function type attributes as part of the
5797       // declaration-specifiers.
5798       if (TAL == TAL_DeclSpec)
5799         distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
5800
5801       // Otherwise, handle the possible delays.
5802       else if (!handleFunctionTypeAttr(state, attr, type))
5803         distributeFunctionTypeAttr(state, attr, type);
5804       break;
5805     }
5806   } while ((attrs = next));
5807 }
5808
5809 /// \brief Ensure that the type of the given expression is complete.
5810 ///
5811 /// This routine checks whether the expression \p E has a complete type. If the
5812 /// expression refers to an instantiable construct, that instantiation is
5813 /// performed as needed to complete its type. Furthermore
5814 /// Sema::RequireCompleteType is called for the expression's type (or in the
5815 /// case of a reference type, the referred-to type).
5816 ///
5817 /// \param E The expression whose type is required to be complete.
5818 /// \param Diagnoser The object that will emit a diagnostic if the type is
5819 /// incomplete.
5820 ///
5821 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
5822 /// otherwise.
5823 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser){
5824   QualType T = E->getType();
5825
5826   // Fast path the case where the type is already complete.
5827   if (!T->isIncompleteType())
5828     // FIXME: The definition might not be visible.
5829     return false;
5830
5831   // Incomplete array types may be completed by the initializer attached to
5832   // their definitions. For static data members of class templates and for
5833   // variable templates, we need to instantiate the definition to get this
5834   // initializer and complete the type.
5835   if (T->isIncompleteArrayType()) {
5836     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
5837       if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
5838         if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
5839           SourceLocation PointOfInstantiation = E->getExprLoc();
5840
5841           if (MemberSpecializationInfo *MSInfo =
5842                   Var->getMemberSpecializationInfo()) {
5843             // If we don't already have a point of instantiation, this is it.
5844             if (MSInfo->getPointOfInstantiation().isInvalid()) {
5845               MSInfo->setPointOfInstantiation(PointOfInstantiation);
5846
5847               // This is a modification of an existing AST node. Notify
5848               // listeners.
5849               if (ASTMutationListener *L = getASTMutationListener())
5850                 L->StaticDataMemberInstantiated(Var);
5851             }
5852           } else {
5853             VarTemplateSpecializationDecl *VarSpec =
5854                 cast<VarTemplateSpecializationDecl>(Var);
5855             if (VarSpec->getPointOfInstantiation().isInvalid())
5856               VarSpec->setPointOfInstantiation(PointOfInstantiation);
5857           }
5858
5859           InstantiateVariableDefinition(PointOfInstantiation, Var);
5860
5861           // Update the type to the newly instantiated definition's type both
5862           // here and within the expression.
5863           if (VarDecl *Def = Var->getDefinition()) {
5864             DRE->setDecl(Def);
5865             T = Def->getType();
5866             DRE->setType(T);
5867             E->setType(T);
5868           }
5869
5870           // We still go on to try to complete the type independently, as it
5871           // may also require instantiations or diagnostics if it remains
5872           // incomplete.
5873         }
5874       }
5875     }
5876   }
5877
5878   // FIXME: Are there other cases which require instantiating something other
5879   // than the type to complete the type of an expression?
5880
5881   // Look through reference types and complete the referred type.
5882   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5883     T = Ref->getPointeeType();
5884
5885   return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
5886 }
5887
5888 namespace {
5889   struct TypeDiagnoserDiag : Sema::TypeDiagnoser {
5890     unsigned DiagID;
5891
5892     TypeDiagnoserDiag(unsigned DiagID)
5893       : Sema::TypeDiagnoser(DiagID == 0), DiagID(DiagID) {}
5894
5895     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5896       if (Suppressed) return;
5897       S.Diag(Loc, DiagID) << T;
5898     }
5899   };
5900 }
5901
5902 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
5903   TypeDiagnoserDiag Diagnoser(DiagID);
5904   return RequireCompleteExprType(E, Diagnoser);
5905 }
5906
5907 /// @brief Ensure that the type T is a complete type.
5908 ///
5909 /// This routine checks whether the type @p T is complete in any
5910 /// context where a complete type is required. If @p T is a complete
5911 /// type, returns false. If @p T is a class template specialization,
5912 /// this routine then attempts to perform class template
5913 /// instantiation. If instantiation fails, or if @p T is incomplete
5914 /// and cannot be completed, issues the diagnostic @p diag (giving it
5915 /// the type @p T) and returns true.
5916 ///
5917 /// @param Loc  The location in the source that the incomplete type
5918 /// diagnostic should refer to.
5919 ///
5920 /// @param T  The type that this routine is examining for completeness.
5921 ///
5922 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
5923 /// @c false otherwise.
5924 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
5925                                TypeDiagnoser &Diagnoser) {
5926   if (RequireCompleteTypeImpl(Loc, T, Diagnoser))
5927     return true;
5928   if (const TagType *Tag = T->getAs<TagType>()) {
5929     if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
5930       Tag->getDecl()->setCompleteDefinitionRequired();
5931       Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
5932     }
5933   }
5934   return false;
5935 }
5936
5937 /// \brief Determine whether there is any declaration of \p D that was ever a
5938 ///        definition (perhaps before module merging) and is currently visible.
5939 /// \param D The definition of the entity.
5940 /// \param Suggested Filled in with the declaration that should be made visible
5941 ///        in order to provide a definition of this entity.
5942 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested) {
5943   // Easy case: if we don't have modules, all declarations are visible.
5944   if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
5945     return true;
5946
5947   // If this definition was instantiated from a template, map back to the
5948   // pattern from which it was instantiated.
5949   if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
5950     // We're in the middle of defining it; this definition should be treated
5951     // as visible.
5952     return true;
5953   } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
5954     if (auto *Pattern = RD->getTemplateInstantiationPattern())
5955       RD = Pattern;
5956     D = RD->getDefinition();
5957   } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
5958     while (auto *NewED = ED->getInstantiatedFromMemberEnum())
5959       ED = NewED;
5960     if (ED->isFixed()) {
5961       // If the enum has a fixed underlying type, any declaration of it will do.
5962       *Suggested = nullptr;
5963       for (auto *Redecl : ED->redecls()) {
5964         if (LookupResult::isVisible(*this, Redecl))
5965           return true;
5966         if (Redecl->isThisDeclarationADefinition() ||
5967             (Redecl->isCanonicalDecl() && !*Suggested))
5968           *Suggested = Redecl;
5969       }
5970       return false;
5971     }
5972     D = ED->getDefinition();
5973   }
5974   assert(D && "missing definition for pattern of instantiated definition");
5975
5976   *Suggested = D;
5977   if (LookupResult::isVisible(*this, D))
5978     return true;
5979
5980   // The external source may have additional definitions of this type that are
5981   // visible, so complete the redeclaration chain now and ask again.
5982   if (auto *Source = Context.getExternalSource()) {
5983     Source->CompleteRedeclChain(D);
5984     return LookupResult::isVisible(*this, D);
5985   }
5986
5987   return false;
5988 }
5989
5990 /// Locks in the inheritance model for the given class and all of its bases.
5991 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
5992   RD = RD->getMostRecentDecl();
5993   if (!RD->hasAttr<MSInheritanceAttr>()) {
5994     MSInheritanceAttr::Spelling IM;
5995
5996     switch (S.MSPointerToMemberRepresentationMethod) {
5997     case LangOptions::PPTMK_BestCase:
5998       IM = RD->calculateInheritanceModel();
5999       break;
6000     case LangOptions::PPTMK_FullGeneralitySingleInheritance:
6001       IM = MSInheritanceAttr::Keyword_single_inheritance;
6002       break;
6003     case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
6004       IM = MSInheritanceAttr::Keyword_multiple_inheritance;
6005       break;
6006     case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
6007       IM = MSInheritanceAttr::Keyword_unspecified_inheritance;
6008       break;
6009     }
6010
6011     RD->addAttr(MSInheritanceAttr::CreateImplicit(
6012         S.getASTContext(), IM,
6013         /*BestCase=*/S.MSPointerToMemberRepresentationMethod ==
6014             LangOptions::PPTMK_BestCase,
6015         S.ImplicitMSInheritanceAttrLoc.isValid()
6016             ? S.ImplicitMSInheritanceAttrLoc
6017             : RD->getSourceRange()));
6018   }
6019 }
6020
6021 /// \brief The implementation of RequireCompleteType
6022 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
6023                                    TypeDiagnoser &Diagnoser) {
6024   // FIXME: Add this assertion to make sure we always get instantiation points.
6025   //  assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
6026   // FIXME: Add this assertion to help us flush out problems with
6027   // checking for dependent types and type-dependent expressions.
6028   //
6029   //  assert(!T->isDependentType() &&
6030   //         "Can't ask whether a dependent type is complete");
6031
6032   // If we have a complete type, we're done.
6033   NamedDecl *Def = nullptr;
6034   if (!T->isIncompleteType(&Def)) {
6035     // If we know about the definition but it is not visible, complain.
6036     NamedDecl *SuggestedDef = nullptr;
6037     if (!Diagnoser.Suppressed && Def &&
6038         !hasVisibleDefinition(Def, &SuggestedDef))
6039       diagnoseMissingImport(Loc, SuggestedDef, /*NeedDefinition*/true);
6040
6041     // We lock in the inheritance model once somebody has asked us to ensure
6042     // that a pointer-to-member type is complete.
6043     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6044       if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
6045         if (!MPTy->getClass()->isDependentType()) {
6046           RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), 0);
6047           assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
6048         }
6049       }
6050     }
6051
6052     return false;
6053   }
6054
6055   const TagType *Tag = T->getAs<TagType>();
6056   const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>();
6057
6058   // If there's an unimported definition of this type in a module (for
6059   // instance, because we forward declared it, then imported the definition),
6060   // import that definition now.
6061   //
6062   // FIXME: What about other cases where an import extends a redeclaration
6063   // chain for a declaration that can be accessed through a mechanism other
6064   // than name lookup (eg, referenced in a template, or a variable whose type
6065   // could be completed by the module)?
6066   if (Tag || IFace) {
6067     NamedDecl *D =
6068         Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl();
6069
6070     // Avoid diagnosing invalid decls as incomplete.
6071     if (D->isInvalidDecl())
6072       return true;
6073
6074     // Give the external AST source a chance to complete the type.
6075     if (auto *Source = Context.getExternalSource()) {
6076       if (Tag)
6077         Source->CompleteType(Tag->getDecl());
6078       else
6079         Source->CompleteType(IFace->getDecl());
6080
6081       // If the external source completed the type, go through the motions
6082       // again to ensure we're allowed to use the completed type.
6083       if (!T->isIncompleteType())
6084         return RequireCompleteTypeImpl(Loc, T, Diagnoser);
6085     }
6086   }
6087
6088   // If we have a class template specialization or a class member of a
6089   // class template specialization, or an array with known size of such,
6090   // try to instantiate it.
6091   QualType MaybeTemplate = T;
6092   while (const ConstantArrayType *Array
6093            = Context.getAsConstantArrayType(MaybeTemplate))
6094     MaybeTemplate = Array->getElementType();
6095   if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
6096     if (ClassTemplateSpecializationDecl *ClassTemplateSpec
6097           = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
6098       if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
6099         return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
6100                                                       TSK_ImplicitInstantiation,
6101                                             /*Complain=*/!Diagnoser.Suppressed);
6102     } else if (CXXRecordDecl *Rec
6103                  = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
6104       CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
6105       if (!Rec->isBeingDefined() && Pattern) {
6106         MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
6107         assert(MSI && "Missing member specialization information?");
6108         // This record was instantiated from a class within a template.
6109         if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
6110           return InstantiateClass(Loc, Rec, Pattern,
6111                                   getTemplateInstantiationArgs(Rec),
6112                                   TSK_ImplicitInstantiation,
6113                                   /*Complain=*/!Diagnoser.Suppressed);
6114       }
6115     }
6116   }
6117
6118   if (Diagnoser.Suppressed)
6119     return true;
6120
6121   // We have an incomplete type. Produce a diagnostic.
6122   if (Ident___float128 &&
6123       T == Context.getTypeDeclType(Context.getFloat128StubType())) {
6124     Diag(Loc, diag::err_typecheck_decl_incomplete_type___float128);
6125     return true;
6126   }
6127
6128   Diagnoser.diagnose(*this, Loc, T);
6129
6130   // If the type was a forward declaration of a class/struct/union
6131   // type, produce a note.
6132   if (Tag && !Tag->getDecl()->isInvalidDecl())
6133     Diag(Tag->getDecl()->getLocation(),
6134          Tag->isBeingDefined() ? diag::note_type_being_defined
6135                                : diag::note_forward_declaration)
6136       << QualType(Tag, 0);
6137
6138   // If the Objective-C class was a forward declaration, produce a note.
6139   if (IFace && !IFace->getDecl()->isInvalidDecl())
6140     Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
6141
6142   // If we have external information that we can use to suggest a fix,
6143   // produce a note.
6144   if (ExternalSource)
6145     ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
6146
6147   return true;
6148 }
6149
6150 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
6151                                unsigned DiagID) {
6152   TypeDiagnoserDiag Diagnoser(DiagID);
6153   return RequireCompleteType(Loc, T, Diagnoser);
6154 }
6155
6156 /// \brief Get diagnostic %select index for tag kind for
6157 /// literal type diagnostic message.
6158 /// WARNING: Indexes apply to particular diagnostics only!
6159 ///
6160 /// \returns diagnostic %select index.
6161 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
6162   switch (Tag) {
6163   case TTK_Struct: return 0;
6164   case TTK_Interface: return 1;
6165   case TTK_Class:  return 2;
6166   default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
6167   }
6168 }
6169
6170 /// @brief Ensure that the type T is a literal type.
6171 ///
6172 /// This routine checks whether the type @p T is a literal type. If @p T is an
6173 /// incomplete type, an attempt is made to complete it. If @p T is a literal
6174 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
6175 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
6176 /// it the type @p T), along with notes explaining why the type is not a
6177 /// literal type, and returns true.
6178 ///
6179 /// @param Loc  The location in the source that the non-literal type
6180 /// diagnostic should refer to.
6181 ///
6182 /// @param T  The type that this routine is examining for literalness.
6183 ///
6184 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
6185 ///
6186 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
6187 /// @c false otherwise.
6188 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
6189                               TypeDiagnoser &Diagnoser) {
6190   assert(!T->isDependentType() && "type should not be dependent");
6191
6192   QualType ElemType = Context.getBaseElementType(T);
6193   RequireCompleteType(Loc, ElemType, 0);
6194
6195   if (T->isLiteralType(Context))
6196     return false;
6197
6198   if (Diagnoser.Suppressed)
6199     return true;
6200
6201   Diagnoser.diagnose(*this, Loc, T);
6202
6203   if (T->isVariableArrayType())
6204     return true;
6205
6206   const RecordType *RT = ElemType->getAs<RecordType>();
6207   if (!RT)
6208     return true;
6209
6210   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
6211
6212   // A partially-defined class type can't be a literal type, because a literal
6213   // class type must have a trivial destructor (which can't be checked until
6214   // the class definition is complete).
6215   if (!RD->isCompleteDefinition()) {
6216     RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T);
6217     return true;
6218   }
6219
6220   // If the class has virtual base classes, then it's not an aggregate, and
6221   // cannot have any constexpr constructors or a trivial default constructor,
6222   // so is non-literal. This is better to diagnose than the resulting absence
6223   // of constexpr constructors.
6224   if (RD->getNumVBases()) {
6225     Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
6226       << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
6227     for (const auto &I : RD->vbases())
6228       Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here)
6229           << I.getSourceRange();
6230   } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
6231              !RD->hasTrivialDefaultConstructor()) {
6232     Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
6233   } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
6234     for (const auto &I : RD->bases()) {
6235       if (!I.getType()->isLiteralType(Context)) {
6236         Diag(I.getLocStart(),
6237              diag::note_non_literal_base_class)
6238           << RD << I.getType() << I.getSourceRange();
6239         return true;
6240       }
6241     }
6242     for (const auto *I : RD->fields()) {
6243       if (!I->getType()->isLiteralType(Context) ||
6244           I->getType().isVolatileQualified()) {
6245         Diag(I->getLocation(), diag::note_non_literal_field)
6246           << RD << I << I->getType()
6247           << I->getType().isVolatileQualified();
6248         return true;
6249       }
6250     }
6251   } else if (!RD->hasTrivialDestructor()) {
6252     // All fields and bases are of literal types, so have trivial destructors.
6253     // If this class's destructor is non-trivial it must be user-declared.
6254     CXXDestructorDecl *Dtor = RD->getDestructor();
6255     assert(Dtor && "class has literal fields and bases but no dtor?");
6256     if (!Dtor)
6257       return true;
6258
6259     Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
6260          diag::note_non_literal_user_provided_dtor :
6261          diag::note_non_literal_nontrivial_dtor) << RD;
6262     if (!Dtor->isUserProvided())
6263       SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true);
6264   }
6265
6266   return true;
6267 }
6268
6269 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
6270   TypeDiagnoserDiag Diagnoser(DiagID);
6271   return RequireLiteralType(Loc, T, Diagnoser);
6272 }
6273
6274 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
6275 /// and qualified by the nested-name-specifier contained in SS.
6276 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
6277                                  const CXXScopeSpec &SS, QualType T) {
6278   if (T.isNull())
6279     return T;
6280   NestedNameSpecifier *NNS;
6281   if (SS.isValid())
6282     NNS = SS.getScopeRep();
6283   else {
6284     if (Keyword == ETK_None)
6285       return T;
6286     NNS = nullptr;
6287   }
6288   return Context.getElaboratedType(Keyword, NNS, T);
6289 }
6290
6291 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
6292   ExprResult ER = CheckPlaceholderExpr(E);
6293   if (ER.isInvalid()) return QualType();
6294   E = ER.get();
6295
6296   if (!E->isTypeDependent()) {
6297     QualType T = E->getType();
6298     if (const TagType *TT = T->getAs<TagType>())
6299       DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
6300   }
6301   return Context.getTypeOfExprType(E);
6302 }
6303
6304 /// getDecltypeForExpr - Given an expr, will return the decltype for
6305 /// that expression, according to the rules in C++11
6306 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
6307 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
6308   if (E->isTypeDependent())
6309     return S.Context.DependentTy;
6310
6311   // C++11 [dcl.type.simple]p4:
6312   //   The type denoted by decltype(e) is defined as follows:
6313   //
6314   //     - if e is an unparenthesized id-expression or an unparenthesized class
6315   //       member access (5.2.5), decltype(e) is the type of the entity named
6316   //       by e. If there is no such entity, or if e names a set of overloaded
6317   //       functions, the program is ill-formed;
6318   //
6319   // We apply the same rules for Objective-C ivar and property references.
6320   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6321     if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
6322       return VD->getType();
6323   } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6324     if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
6325       return FD->getType();
6326   } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
6327     return IR->getDecl()->getType();
6328   } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
6329     if (PR->isExplicitProperty())
6330       return PR->getExplicitProperty()->getType();
6331   } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) {
6332     return PE->getType();
6333   }
6334   
6335   // C++11 [expr.lambda.prim]p18:
6336   //   Every occurrence of decltype((x)) where x is a possibly
6337   //   parenthesized id-expression that names an entity of automatic
6338   //   storage duration is treated as if x were transformed into an
6339   //   access to a corresponding data member of the closure type that
6340   //   would have been declared if x were an odr-use of the denoted
6341   //   entity.
6342   using namespace sema;
6343   if (S.getCurLambda()) {
6344     if (isa<ParenExpr>(E)) {
6345       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
6346         if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
6347           QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
6348           if (!T.isNull())
6349             return S.Context.getLValueReferenceType(T);
6350         }
6351       }
6352     }
6353   }
6354
6355
6356   // C++11 [dcl.type.simple]p4:
6357   //   [...]
6358   QualType T = E->getType();
6359   switch (E->getValueKind()) {
6360   //     - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6361   //       type of e;
6362   case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
6363   //     - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6364   //       type of e;
6365   case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
6366   //  - otherwise, decltype(e) is the type of e.
6367   case VK_RValue: break;
6368   }
6369
6370   return T;
6371 }
6372
6373 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc,
6374                                  bool AsUnevaluated) {
6375   ExprResult ER = CheckPlaceholderExpr(E);
6376   if (ER.isInvalid()) return QualType();
6377   E = ER.get();
6378
6379   if (AsUnevaluated && ActiveTemplateInstantiations.empty() &&
6380       E->HasSideEffects(Context, false)) {
6381     // The expression operand for decltype is in an unevaluated expression
6382     // context, so side effects could result in unintended consequences.
6383     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
6384   }
6385
6386   return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
6387 }
6388
6389 QualType Sema::BuildUnaryTransformType(QualType BaseType,
6390                                        UnaryTransformType::UTTKind UKind,
6391                                        SourceLocation Loc) {
6392   switch (UKind) {
6393   case UnaryTransformType::EnumUnderlyingType:
6394     if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
6395       Diag(Loc, diag::err_only_enums_have_underlying_types);
6396       return QualType();
6397     } else {
6398       QualType Underlying = BaseType;
6399       if (!BaseType->isDependentType()) {
6400         // The enum could be incomplete if we're parsing its definition or
6401         // recovering from an error.
6402         NamedDecl *FwdDecl = nullptr;
6403         if (BaseType->isIncompleteType(&FwdDecl)) {
6404           Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
6405           Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
6406           return QualType();
6407         }
6408
6409         EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
6410         assert(ED && "EnumType has no EnumDecl");
6411
6412         DiagnoseUseOfDecl(ED, Loc);
6413
6414         Underlying = ED->getIntegerType();
6415         assert(!Underlying.isNull());
6416       }
6417       return Context.getUnaryTransformType(BaseType, Underlying,
6418                                         UnaryTransformType::EnumUnderlyingType);
6419     }
6420   }
6421   llvm_unreachable("unknown unary transform type");
6422 }
6423
6424 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
6425   if (!T->isDependentType()) {
6426     // FIXME: It isn't entirely clear whether incomplete atomic types
6427     // are allowed or not; for simplicity, ban them for the moment.
6428     if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
6429       return QualType();
6430
6431     int DisallowedKind = -1;
6432     if (T->isArrayType())
6433       DisallowedKind = 1;
6434     else if (T->isFunctionType())
6435       DisallowedKind = 2;
6436     else if (T->isReferenceType())
6437       DisallowedKind = 3;
6438     else if (T->isAtomicType())
6439       DisallowedKind = 4;
6440     else if (T.hasQualifiers())
6441       DisallowedKind = 5;
6442     else if (!T.isTriviallyCopyableType(Context))
6443       // Some other non-trivially-copyable type (probably a C++ class)
6444       DisallowedKind = 6;
6445
6446     if (DisallowedKind != -1) {
6447       Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
6448       return QualType();
6449     }
6450
6451     // FIXME: Do we need any handling for ARC here?
6452   }
6453
6454   // Build the pointer type.
6455   return Context.getAtomicType(T);
6456 }