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