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