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