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     inAssumeNonNullRegion = true;
3316     // Determine which file we saw the assume-nonnull region in.
3317     FileID file = getNullabilityCompletenessCheckFileID(
3318                     S, S.PP.getPragmaAssumeNonNullLoc());
3319     if (file.isValid()) {
3320       FileNullability &fileNullability = S.NullabilityMap[file];
3321 
3322       // If we haven't seen any type nullability before, now we have.
3323       if (!fileNullability.SawTypeNullability) {
3324         if (fileNullability.PointerLoc.isValid()) {
3325           S.Diag(fileNullability.PointerLoc, diag::warn_nullability_missing)
3326             << static_cast<unsigned>(fileNullability.PointerKind);
3327         }
3328 
3329         fileNullability.SawTypeNullability = true;
3330       }
3331     }
3332   }
3333 
3334   // Whether to complain about missing nullability specifiers or not.
3335   enum {
3336     /// Never complain.
3337     CAMN_No,
3338     /// Complain on the inner pointers (but not the outermost
3339     /// pointer).
3340     CAMN_InnerPointers,
3341     /// Complain about any pointers that don't have nullability
3342     /// specified or inferred.
3343     CAMN_Yes
3344   } complainAboutMissingNullability = CAMN_No;
3345   unsigned NumPointersRemaining = 0;
3346 
3347   if (IsTypedefName) {
3348     // For typedefs, we do not infer any nullability (the default),
3349     // and we only complain about missing nullability specifiers on
3350     // inner pointers.
3351     complainAboutMissingNullability = CAMN_InnerPointers;
3352 
3353     if (T->canHaveNullability() && !T->getNullability(S.Context)) {
3354       ++NumPointersRemaining;
3355     }
3356 
3357     for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
3358       DeclaratorChunk &chunk = D.getTypeObject(i);
3359       switch (chunk.Kind) {
3360       case DeclaratorChunk::Array:
3361       case DeclaratorChunk::Function:
3362         break;
3363 
3364       case DeclaratorChunk::BlockPointer:
3365       case DeclaratorChunk::MemberPointer:
3366         ++NumPointersRemaining;
3367         break;
3368 
3369       case DeclaratorChunk::Paren:
3370       case DeclaratorChunk::Reference:
3371         continue;
3372 
3373       case DeclaratorChunk::Pointer:
3374         ++NumPointersRemaining;
3375         continue;
3376       }
3377     }
3378   } else {
3379     bool isFunctionOrMethod = false;
3380     switch (auto context = state.getDeclarator().getContext()) {
3381     case Declarator::ObjCParameterContext:
3382     case Declarator::ObjCResultContext:
3383     case Declarator::PrototypeContext:
3384     case Declarator::TrailingReturnContext:
3385       isFunctionOrMethod = true;
3386       // fallthrough
3387 
3388     case Declarator::MemberContext:
3389       if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
3390         complainAboutMissingNullability = CAMN_No;
3391         break;
3392       }
3393 
3394       // Weak properties are inferred to be nullable.
3395       if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) {
3396         inferNullability = NullabilityKind::Nullable;
3397         break;
3398       }
3399 
3400       // fallthrough
3401 
3402     case Declarator::FileContext:
3403     case Declarator::KNRTypeListContext:
3404       complainAboutMissingNullability = CAMN_Yes;
3405 
3406       // Nullability inference depends on the type and declarator.
3407       switch (classifyPointerDeclarator(S, T, D)) {
3408       case PointerDeclaratorKind::NonPointer:
3409       case PointerDeclaratorKind::MultiLevelPointer:
3410         // Cannot infer nullability.
3411         break;
3412 
3413       case PointerDeclaratorKind::SingleLevelPointer:
3414         // Infer _Nonnull if we are in an assumes-nonnull region.
3415         if (inAssumeNonNullRegion) {
3416           inferNullability = NullabilityKind::NonNull;
3417           inferNullabilityCS = (context == Declarator::ObjCParameterContext ||
3418                                 context == Declarator::ObjCResultContext);
3419         }
3420         break;
3421 
3422       case PointerDeclaratorKind::CFErrorRefPointer:
3423       case PointerDeclaratorKind::NSErrorPointerPointer:
3424         // Within a function or method signature, infer _Nullable at both
3425         // levels.
3426         if (isFunctionOrMethod && inAssumeNonNullRegion)
3427           inferNullability = NullabilityKind::Nullable;
3428         break;
3429 
3430       case PointerDeclaratorKind::MaybePointerToCFRef:
3431         if (isFunctionOrMethod) {
3432           // On pointer-to-pointer parameters marked cf_returns_retained or
3433           // cf_returns_not_retained, if the outer pointer is explicit then
3434           // infer the inner pointer as _Nullable.
3435           auto hasCFReturnsAttr = [](const AttributeList *NextAttr) -> bool {
3436             while (NextAttr) {
3437               if (NextAttr->getKind() == AttributeList::AT_CFReturnsRetained ||
3438                   NextAttr->getKind() == AttributeList::AT_CFReturnsNotRetained)
3439                 return true;
3440               NextAttr = NextAttr->getNext();
3441             }
3442             return false;
3443           };
3444           if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
3445             if (hasCFReturnsAttr(D.getAttributes()) ||
3446                 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
3447                 hasCFReturnsAttr(D.getDeclSpec().getAttributes().getList())) {
3448               inferNullability = NullabilityKind::Nullable;
3449               inferNullabilityInnerOnly = true;
3450             }
3451           }
3452         }
3453         break;
3454       }
3455       break;
3456 
3457     case Declarator::ConversionIdContext:
3458       complainAboutMissingNullability = CAMN_Yes;
3459       break;
3460 
3461     case Declarator::AliasDeclContext:
3462     case Declarator::AliasTemplateContext:
3463     case Declarator::BlockContext:
3464     case Declarator::BlockLiteralContext:
3465     case Declarator::ConditionContext:
3466     case Declarator::CXXCatchContext:
3467     case Declarator::CXXNewContext:
3468     case Declarator::ForContext:
3469     case Declarator::LambdaExprContext:
3470     case Declarator::LambdaExprParameterContext:
3471     case Declarator::ObjCCatchContext:
3472     case Declarator::TemplateParamContext:
3473     case Declarator::TemplateTypeArgContext:
3474     case Declarator::TypeNameContext:
3475       // Don't infer in these contexts.
3476       break;
3477     }
3478   }
3479 
3480   // Local function that checks the nullability for a given pointer declarator.
3481   // Returns true if _Nonnull was inferred.
3482   auto inferPointerNullability = [&](SimplePointerKind pointerKind,
3483                                      SourceLocation pointerLoc,
3484                                      AttributeList *&attrs) -> AttributeList * {
3485     // We've seen a pointer.
3486     if (NumPointersRemaining > 0)
3487       --NumPointersRemaining;
3488 
3489     // If a nullability attribute is present, there's nothing to do.
3490     if (hasNullabilityAttr(attrs))
3491       return nullptr;
3492 
3493     // If we're supposed to infer nullability, do so now.
3494     if (inferNullability && !inferNullabilityInnerOnlyComplete) {
3495       AttributeList::Syntax syntax
3496         = inferNullabilityCS ? AttributeList::AS_ContextSensitiveKeyword
3497                              : AttributeList::AS_Keyword;
3498       AttributeList *nullabilityAttr = state.getDeclarator().getAttributePool()
3499                                          .create(
3500                                            S.getNullabilityKeyword(
3501                                              *inferNullability),
3502                                            SourceRange(pointerLoc),
3503                                            nullptr, SourceLocation(),
3504                                            nullptr, 0, syntax);
3505 
3506       spliceAttrIntoList(*nullabilityAttr, attrs);
3507 
3508       if (inferNullabilityCS) {
3509         state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
3510           ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
3511       }
3512 
3513       if (inferNullabilityInnerOnly)
3514         inferNullabilityInnerOnlyComplete = true;
3515       return nullabilityAttr;
3516     }
3517 
3518     // If we're supposed to complain about missing nullability, do so
3519     // now if it's truly missing.
3520     switch (complainAboutMissingNullability) {
3521     case CAMN_No:
3522       break;
3523 
3524     case CAMN_InnerPointers:
3525       if (NumPointersRemaining == 0)
3526         break;
3527       // Fallthrough.
3528 
3529     case CAMN_Yes:
3530       checkNullabilityConsistency(state, pointerKind, pointerLoc);
3531     }
3532     return nullptr;
3533   };
3534 
3535   // If the type itself could have nullability but does not, infer pointer
3536   // nullability and perform consistency checking.
3537   if (T->canHaveNullability() && S.ActiveTemplateInstantiations.empty() &&
3538       !T->getNullability(S.Context)) {
3539     SimplePointerKind pointerKind = SimplePointerKind::Pointer;
3540     if (T->isBlockPointerType())
3541       pointerKind = SimplePointerKind::BlockPointer;
3542     else if (T->isMemberPointerType())
3543       pointerKind = SimplePointerKind::MemberPointer;
3544 
3545     if (auto *attr = inferPointerNullability(
3546                        pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
3547                        D.getMutableDeclSpec().getAttributes().getListRef())) {
3548       T = Context.getAttributedType(
3549             AttributedType::getNullabilityAttrKind(*inferNullability), T, T);
3550       attr->setUsedAsTypeAttr();
3551     }
3552   }
3553 
3554   // Walk the DeclTypeInfo, building the recursive type as we go.
3555   // DeclTypeInfos are ordered from the identifier out, which is
3556   // opposite of what we want :).
3557   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3558     unsigned chunkIndex = e - i - 1;
3559     state.setCurrentChunkIndex(chunkIndex);
3560     DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
3561     IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
3562     switch (DeclType.Kind) {
3563     case DeclaratorChunk::Paren:
3564       T = S.BuildParenType(T);
3565       break;
3566     case DeclaratorChunk::BlockPointer:
3567       // If blocks are disabled, emit an error.
3568       if (!LangOpts.Blocks)
3569         S.Diag(DeclType.Loc, diag::err_blocks_disable);
3570 
3571       // Handle pointer nullability.
3572       inferPointerNullability(SimplePointerKind::BlockPointer,
3573                               DeclType.Loc, DeclType.getAttrListRef());
3574 
3575       T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
3576       if (DeclType.Cls.TypeQuals)
3577         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
3578       break;
3579     case DeclaratorChunk::Pointer:
3580       // Verify that we're not building a pointer to pointer to function with
3581       // exception specification.
3582       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
3583         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
3584         D.setInvalidType(true);
3585         // Build the type anyway.
3586       }
3587 
3588       // Handle pointer nullability
3589       inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
3590                               DeclType.getAttrListRef());
3591 
3592       if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
3593         T = Context.getObjCObjectPointerType(T);
3594         if (DeclType.Ptr.TypeQuals)
3595           T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
3596         break;
3597       }
3598       T = S.BuildPointerType(T, DeclType.Loc, Name);
3599       if (DeclType.Ptr.TypeQuals)
3600         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
3601 
3602       break;
3603     case DeclaratorChunk::Reference: {
3604       // Verify that we're not building a reference to pointer to function with
3605       // exception specification.
3606       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
3607         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
3608         D.setInvalidType(true);
3609         // Build the type anyway.
3610       }
3611       T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
3612 
3613       if (DeclType.Ref.HasRestrict)
3614         T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
3615       break;
3616     }
3617     case DeclaratorChunk::Array: {
3618       // Verify that we're not building an array of pointers to function with
3619       // exception specification.
3620       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
3621         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
3622         D.setInvalidType(true);
3623         // Build the type anyway.
3624       }
3625       DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
3626       Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
3627       ArrayType::ArraySizeModifier ASM;
3628       if (ATI.isStar)
3629         ASM = ArrayType::Star;
3630       else if (ATI.hasStatic)
3631         ASM = ArrayType::Static;
3632       else
3633         ASM = ArrayType::Normal;
3634       if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
3635         // FIXME: This check isn't quite right: it allows star in prototypes
3636         // for function definitions, and disallows some edge cases detailed
3637         // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
3638         S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
3639         ASM = ArrayType::Normal;
3640         D.setInvalidType(true);
3641       }
3642 
3643       // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
3644       // shall appear only in a declaration of a function parameter with an
3645       // array type, ...
3646       if (ASM == ArrayType::Static || ATI.TypeQuals) {
3647         if (!(D.isPrototypeContext() ||
3648               D.getContext() == Declarator::KNRTypeListContext)) {
3649           S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
3650               (ASM == ArrayType::Static ? "'static'" : "type qualifier");
3651           // Remove the 'static' and the type qualifiers.
3652           if (ASM == ArrayType::Static)
3653             ASM = ArrayType::Normal;
3654           ATI.TypeQuals = 0;
3655           D.setInvalidType(true);
3656         }
3657 
3658         // C99 6.7.5.2p1: ... and then only in the outermost array type
3659         // derivation.
3660         unsigned x = chunkIndex;
3661         while (x != 0) {
3662           // Walk outwards along the declarator chunks.
3663           x--;
3664           const DeclaratorChunk &DC = D.getTypeObject(x);
3665           switch (DC.Kind) {
3666           case DeclaratorChunk::Paren:
3667             continue;
3668           case DeclaratorChunk::Array:
3669           case DeclaratorChunk::Pointer:
3670           case DeclaratorChunk::Reference:
3671           case DeclaratorChunk::MemberPointer:
3672             S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
3673               (ASM == ArrayType::Static ? "'static'" : "type qualifier");
3674             if (ASM == ArrayType::Static)
3675               ASM = ArrayType::Normal;
3676             ATI.TypeQuals = 0;
3677             D.setInvalidType(true);
3678             break;
3679           case DeclaratorChunk::Function:
3680           case DeclaratorChunk::BlockPointer:
3681             // These are invalid anyway, so just ignore.
3682             break;
3683           }
3684         }
3685       }
3686       const AutoType *AT = T->getContainedAutoType();
3687       // Allow arrays of auto if we are a generic lambda parameter.
3688       // i.e. [](auto (&array)[5]) { return array[0]; }; OK
3689       if (AT && D.getContext() != Declarator::LambdaExprParameterContext) {
3690         // We've already diagnosed this for decltype(auto).
3691         if (!AT->isDecltypeAuto())
3692           S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
3693             << getPrintableNameForEntity(Name) << T;
3694         T = QualType();
3695         break;
3696       }
3697 
3698       T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
3699                            SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
3700       break;
3701     }
3702     case DeclaratorChunk::Function: {
3703       // If the function declarator has a prototype (i.e. it is not () and
3704       // does not have a K&R-style identifier list), then the arguments are part
3705       // of the type, otherwise the argument list is ().
3706       const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3707       IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
3708 
3709       // Check for auto functions and trailing return type and adjust the
3710       // return type accordingly.
3711       if (!D.isInvalidType()) {
3712         // trailing-return-type is only required if we're declaring a function,
3713         // and not, for instance, a pointer to a function.
3714         if (D.getDeclSpec().containsPlaceholderType() &&
3715             !FTI.hasTrailingReturnType() && chunkIndex == 0 &&
3716             !S.getLangOpts().CPlusPlus14) {
3717           S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
3718                  D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
3719                      ? diag::err_auto_missing_trailing_return
3720                      : diag::err_deduced_return_type);
3721           T = Context.IntTy;
3722           D.setInvalidType(true);
3723         } else if (FTI.hasTrailingReturnType()) {
3724           // T must be exactly 'auto' at this point. See CWG issue 681.
3725           if (isa<ParenType>(T)) {
3726             S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
3727                  diag::err_trailing_return_in_parens)
3728               << T << D.getDeclSpec().getSourceRange();
3729             D.setInvalidType(true);
3730           } else if (D.getContext() != Declarator::LambdaExprContext &&
3731                      (T.hasQualifiers() || !isa<AutoType>(T) ||
3732                       cast<AutoType>(T)->isDecltypeAuto())) {
3733             S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
3734                  diag::err_trailing_return_without_auto)
3735               << T << D.getDeclSpec().getSourceRange();
3736             D.setInvalidType(true);
3737           }
3738           T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
3739           if (T.isNull()) {
3740             // An error occurred parsing the trailing return type.
3741             T = Context.IntTy;
3742             D.setInvalidType(true);
3743           }
3744         }
3745       }
3746 
3747       // C99 6.7.5.3p1: The return type may not be a function or array type.
3748       // For conversion functions, we'll diagnose this particular error later.
3749       if ((T->isArrayType() || T->isFunctionType()) &&
3750           (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
3751         unsigned diagID = diag::err_func_returning_array_function;
3752         // Last processing chunk in block context means this function chunk
3753         // represents the block.
3754         if (chunkIndex == 0 &&
3755             D.getContext() == Declarator::BlockLiteralContext)
3756           diagID = diag::err_block_returning_array_function;
3757         S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
3758         T = Context.IntTy;
3759         D.setInvalidType(true);
3760       }
3761 
3762       // Do not allow returning half FP value.
3763       // FIXME: This really should be in BuildFunctionType.
3764       if (T->isHalfType()) {
3765         if (S.getLangOpts().OpenCL) {
3766           if (!S.getOpenCLOptions().cl_khr_fp16) {
3767             S.Diag(D.getIdentifierLoc(), diag::err_opencl_half_return) << T;
3768             D.setInvalidType(true);
3769           }
3770         } else if (!S.getLangOpts().HalfArgsAndReturns) {
3771           S.Diag(D.getIdentifierLoc(),
3772             diag::err_parameters_retval_cannot_have_fp16_type) << 1;
3773           D.setInvalidType(true);
3774         }
3775       }
3776 
3777       // Methods cannot return interface types. All ObjC objects are
3778       // passed by reference.
3779       if (T->isObjCObjectType()) {
3780         SourceLocation DiagLoc, FixitLoc;
3781         if (TInfo) {
3782           DiagLoc = TInfo->getTypeLoc().getLocStart();
3783           FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd());
3784         } else {
3785           DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
3786           FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd());
3787         }
3788         S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
3789           << 0 << T
3790           << FixItHint::CreateInsertion(FixitLoc, "*");
3791 
3792         T = Context.getObjCObjectPointerType(T);
3793         if (TInfo) {
3794           TypeLocBuilder TLB;
3795           TLB.pushFullCopy(TInfo->getTypeLoc());
3796           ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
3797           TLoc.setStarLoc(FixitLoc);
3798           TInfo = TLB.getTypeSourceInfo(Context, T);
3799         }
3800 
3801         D.setInvalidType(true);
3802       }
3803 
3804       // cv-qualifiers on return types are pointless except when the type is a
3805       // class type in C++.
3806       if ((T.getCVRQualifiers() || T->isAtomicType()) &&
3807           !(S.getLangOpts().CPlusPlus &&
3808             (T->isDependentType() || T->isRecordType()))) {
3809         if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
3810             D.getFunctionDefinitionKind() == FDK_Definition) {
3811           // [6.9.1/3] qualified void return is invalid on a C
3812           // function definition.  Apparently ok on declarations and
3813           // in C++ though (!)
3814           S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
3815         } else
3816           diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
3817       }
3818 
3819       // Objective-C ARC ownership qualifiers are ignored on the function
3820       // return type (by type canonicalization). Complain if this attribute
3821       // was written here.
3822       if (T.getQualifiers().hasObjCLifetime()) {
3823         SourceLocation AttrLoc;
3824         if (chunkIndex + 1 < D.getNumTypeObjects()) {
3825           DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
3826           for (const AttributeList *Attr = ReturnTypeChunk.getAttrs();
3827                Attr; Attr = Attr->getNext()) {
3828             if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
3829               AttrLoc = Attr->getLoc();
3830               break;
3831             }
3832           }
3833         }
3834         if (AttrLoc.isInvalid()) {
3835           for (const AttributeList *Attr
3836                  = D.getDeclSpec().getAttributes().getList();
3837                Attr; Attr = Attr->getNext()) {
3838             if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
3839               AttrLoc = Attr->getLoc();
3840               break;
3841             }
3842           }
3843         }
3844 
3845         if (AttrLoc.isValid()) {
3846           // The ownership attributes are almost always written via
3847           // the predefined
3848           // __strong/__weak/__autoreleasing/__unsafe_unretained.
3849           if (AttrLoc.isMacroID())
3850             AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first;
3851 
3852           S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
3853             << T.getQualifiers().getObjCLifetime();
3854         }
3855       }
3856 
3857       if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
3858         // C++ [dcl.fct]p6:
3859         //   Types shall not be defined in return or parameter types.
3860         TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3861         S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
3862           << Context.getTypeDeclType(Tag);
3863       }
3864 
3865       // Exception specs are not allowed in typedefs. Complain, but add it
3866       // anyway.
3867       if (IsTypedefName && FTI.getExceptionSpecType())
3868         S.Diag(FTI.getExceptionSpecLocBeg(),
3869                diag::err_exception_spec_in_typedef)
3870             << (D.getContext() == Declarator::AliasDeclContext ||
3871                 D.getContext() == Declarator::AliasTemplateContext);
3872 
3873       // If we see "T var();" or "T var(T());" at block scope, it is probably
3874       // an attempt to initialize a variable, not a function declaration.
3875       if (FTI.isAmbiguous)
3876         warnAboutAmbiguousFunction(S, D, DeclType, T);
3877 
3878       FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex));
3879 
3880       if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus) {
3881         // Simple void foo(), where the incoming T is the result type.
3882         T = Context.getFunctionNoProtoType(T, EI);
3883       } else {
3884         // We allow a zero-parameter variadic function in C if the
3885         // function is marked with the "overloadable" attribute. Scan
3886         // for this attribute now.
3887         if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
3888           bool Overloadable = false;
3889           for (const AttributeList *Attrs = D.getAttributes();
3890                Attrs; Attrs = Attrs->getNext()) {
3891             if (Attrs->getKind() == AttributeList::AT_Overloadable) {
3892               Overloadable = true;
3893               break;
3894             }
3895           }
3896 
3897           if (!Overloadable)
3898             S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
3899         }
3900 
3901         if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
3902           // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
3903           // definition.
3904           S.Diag(FTI.Params[0].IdentLoc,
3905                  diag::err_ident_list_in_fn_declaration);
3906           D.setInvalidType(true);
3907           // Recover by creating a K&R-style function type.
3908           T = Context.getFunctionNoProtoType(T, EI);
3909           break;
3910         }
3911 
3912         FunctionProtoType::ExtProtoInfo EPI;
3913         EPI.ExtInfo = EI;
3914         EPI.Variadic = FTI.isVariadic;
3915         EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
3916         EPI.TypeQuals = FTI.TypeQuals;
3917         EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
3918                     : FTI.RefQualifierIsLValueRef? RQ_LValue
3919                     : RQ_RValue;
3920 
3921         // Otherwise, we have a function with a parameter list that is
3922         // potentially variadic.
3923         SmallVector<QualType, 16> ParamTys;
3924         ParamTys.reserve(FTI.NumParams);
3925 
3926         SmallVector<bool, 16> ConsumedParameters;
3927         ConsumedParameters.reserve(FTI.NumParams);
3928         bool HasAnyConsumedParameters = false;
3929 
3930         for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
3931           ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
3932           QualType ParamTy = Param->getType();
3933           assert(!ParamTy.isNull() && "Couldn't parse type?");
3934 
3935           // Look for 'void'.  void is allowed only as a single parameter to a
3936           // function with no other parameters (C99 6.7.5.3p10).  We record
3937           // int(void) as a FunctionProtoType with an empty parameter list.
3938           if (ParamTy->isVoidType()) {
3939             // If this is something like 'float(int, void)', reject it.  'void'
3940             // is an incomplete type (C99 6.2.5p19) and function decls cannot
3941             // have parameters of incomplete type.
3942             if (FTI.NumParams != 1 || FTI.isVariadic) {
3943               S.Diag(DeclType.Loc, diag::err_void_only_param);
3944               ParamTy = Context.IntTy;
3945               Param->setType(ParamTy);
3946             } else if (FTI.Params[i].Ident) {
3947               // Reject, but continue to parse 'int(void abc)'.
3948               S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
3949               ParamTy = Context.IntTy;
3950               Param->setType(ParamTy);
3951             } else {
3952               // Reject, but continue to parse 'float(const void)'.
3953               if (ParamTy.hasQualifiers())
3954                 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
3955 
3956               // Do not add 'void' to the list.
3957               break;
3958             }
3959           } else if (ParamTy->isHalfType()) {
3960             // Disallow half FP parameters.
3961             // FIXME: This really should be in BuildFunctionType.
3962             if (S.getLangOpts().OpenCL) {
3963               if (!S.getOpenCLOptions().cl_khr_fp16) {
3964                 S.Diag(Param->getLocation(),
3965                   diag::err_opencl_half_param) << ParamTy;
3966                 D.setInvalidType();
3967                 Param->setInvalidDecl();
3968               }
3969             } else if (!S.getLangOpts().HalfArgsAndReturns) {
3970               S.Diag(Param->getLocation(),
3971                 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
3972               D.setInvalidType();
3973             }
3974           } else if (!FTI.hasPrototype) {
3975             if (ParamTy->isPromotableIntegerType()) {
3976               ParamTy = Context.getPromotedIntegerType(ParamTy);
3977               Param->setKNRPromoted(true);
3978             } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
3979               if (BTy->getKind() == BuiltinType::Float) {
3980                 ParamTy = Context.DoubleTy;
3981                 Param->setKNRPromoted(true);
3982               }
3983             }
3984           }
3985 
3986           if (LangOpts.ObjCAutoRefCount) {
3987             bool Consumed = Param->hasAttr<NSConsumedAttr>();
3988             ConsumedParameters.push_back(Consumed);
3989             HasAnyConsumedParameters |= Consumed;
3990           }
3991 
3992           ParamTys.push_back(ParamTy);
3993         }
3994 
3995         if (HasAnyConsumedParameters)
3996           EPI.ConsumedParameters = ConsumedParameters.data();
3997 
3998         SmallVector<QualType, 4> Exceptions;
3999         SmallVector<ParsedType, 2> DynamicExceptions;
4000         SmallVector<SourceRange, 2> DynamicExceptionRanges;
4001         Expr *NoexceptExpr = nullptr;
4002 
4003         if (FTI.getExceptionSpecType() == EST_Dynamic) {
4004           // FIXME: It's rather inefficient to have to split into two vectors
4005           // here.
4006           unsigned N = FTI.NumExceptions;
4007           DynamicExceptions.reserve(N);
4008           DynamicExceptionRanges.reserve(N);
4009           for (unsigned I = 0; I != N; ++I) {
4010             DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
4011             DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
4012           }
4013         } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
4014           NoexceptExpr = FTI.NoexceptExpr;
4015         }
4016 
4017         S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
4018                                       FTI.getExceptionSpecType(),
4019                                       DynamicExceptions,
4020                                       DynamicExceptionRanges,
4021                                       NoexceptExpr,
4022                                       Exceptions,
4023                                       EPI.ExceptionSpec);
4024 
4025         T = Context.getFunctionType(T, ParamTys, EPI);
4026       }
4027 
4028       break;
4029     }
4030     case DeclaratorChunk::MemberPointer:
4031       // The scope spec must refer to a class, or be dependent.
4032       CXXScopeSpec &SS = DeclType.Mem.Scope();
4033       QualType ClsType;
4034 
4035       // Handle pointer nullability.
4036       inferPointerNullability(SimplePointerKind::MemberPointer,
4037                               DeclType.Loc, DeclType.getAttrListRef());
4038 
4039       if (SS.isInvalid()) {
4040         // Avoid emitting extra errors if we already errored on the scope.
4041         D.setInvalidType(true);
4042       } else if (S.isDependentScopeSpecifier(SS) ||
4043                  dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
4044         NestedNameSpecifier *NNS = SS.getScopeRep();
4045         NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
4046         switch (NNS->getKind()) {
4047         case NestedNameSpecifier::Identifier:
4048           ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
4049                                                  NNS->getAsIdentifier());
4050           break;
4051 
4052         case NestedNameSpecifier::Namespace:
4053         case NestedNameSpecifier::NamespaceAlias:
4054         case NestedNameSpecifier::Global:
4055         case NestedNameSpecifier::Super:
4056           llvm_unreachable("Nested-name-specifier must name a type");
4057 
4058         case NestedNameSpecifier::TypeSpec:
4059         case NestedNameSpecifier::TypeSpecWithTemplate:
4060           ClsType = QualType(NNS->getAsType(), 0);
4061           // Note: if the NNS has a prefix and ClsType is a nondependent
4062           // TemplateSpecializationType, then the NNS prefix is NOT included
4063           // in ClsType; hence we wrap ClsType into an ElaboratedType.
4064           // NOTE: in particular, no wrap occurs if ClsType already is an
4065           // Elaborated, DependentName, or DependentTemplateSpecialization.
4066           if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
4067             ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
4068           break;
4069         }
4070       } else {
4071         S.Diag(DeclType.Mem.Scope().getBeginLoc(),
4072              diag::err_illegal_decl_mempointer_in_nonclass)
4073           << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
4074           << DeclType.Mem.Scope().getRange();
4075         D.setInvalidType(true);
4076       }
4077 
4078       if (!ClsType.isNull())
4079         T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
4080                                      D.getIdentifier());
4081       if (T.isNull()) {
4082         T = Context.IntTy;
4083         D.setInvalidType(true);
4084       } else if (DeclType.Mem.TypeQuals) {
4085         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
4086       }
4087       break;
4088     }
4089 
4090     if (T.isNull()) {
4091       D.setInvalidType(true);
4092       T = Context.IntTy;
4093     }
4094 
4095     // See if there are any attributes on this declarator chunk.
4096     if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
4097       processTypeAttrs(state, T, TAL_DeclChunk, attrs);
4098   }
4099 
4100   assert(!T.isNull() && "T must not be null after this point");
4101 
4102   if (LangOpts.CPlusPlus && T->isFunctionType()) {
4103     const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
4104     assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
4105 
4106     // C++ 8.3.5p4:
4107     //   A cv-qualifier-seq shall only be part of the function type
4108     //   for a nonstatic member function, the function type to which a pointer
4109     //   to member refers, or the top-level function type of a function typedef
4110     //   declaration.
4111     //
4112     // Core issue 547 also allows cv-qualifiers on function types that are
4113     // top-level template type arguments.
4114     bool FreeFunction;
4115     if (!D.getCXXScopeSpec().isSet()) {
4116       FreeFunction = ((D.getContext() != Declarator::MemberContext &&
4117                        D.getContext() != Declarator::LambdaExprContext) ||
4118                       D.getDeclSpec().isFriendSpecified());
4119     } else {
4120       DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
4121       FreeFunction = (DC && !DC->isRecord());
4122     }
4123 
4124     // C++11 [dcl.fct]p6 (w/DR1417):
4125     // An attempt to specify a function type with a cv-qualifier-seq or a
4126     // ref-qualifier (including by typedef-name) is ill-formed unless it is:
4127     //  - the function type for a non-static member function,
4128     //  - the function type to which a pointer to member refers,
4129     //  - the top-level function type of a function typedef declaration or
4130     //    alias-declaration,
4131     //  - the type-id in the default argument of a type-parameter, or
4132     //  - the type-id of a template-argument for a type-parameter
4133     //
4134     // FIXME: Checking this here is insufficient. We accept-invalid on:
4135     //
4136     //   template<typename T> struct S { void f(T); };
4137     //   S<int() const> s;
4138     //
4139     // ... for instance.
4140     if (IsQualifiedFunction &&
4141         !(!FreeFunction &&
4142           D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
4143         !IsTypedefName &&
4144         D.getContext() != Declarator::TemplateTypeArgContext) {
4145       SourceLocation Loc = D.getLocStart();
4146       SourceRange RemovalRange;
4147       unsigned I;
4148       if (D.isFunctionDeclarator(I)) {
4149         SmallVector<SourceLocation, 4> RemovalLocs;
4150         const DeclaratorChunk &Chunk = D.getTypeObject(I);
4151         assert(Chunk.Kind == DeclaratorChunk::Function);
4152         if (Chunk.Fun.hasRefQualifier())
4153           RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
4154         if (Chunk.Fun.TypeQuals & Qualifiers::Const)
4155           RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
4156         if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
4157           RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
4158         if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
4159           RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
4160         if (!RemovalLocs.empty()) {
4161           std::sort(RemovalLocs.begin(), RemovalLocs.end(),
4162                     BeforeThanCompare<SourceLocation>(S.getSourceManager()));
4163           RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
4164           Loc = RemovalLocs.front();
4165         }
4166       }
4167 
4168       S.Diag(Loc, diag::err_invalid_qualified_function_type)
4169         << FreeFunction << D.isFunctionDeclarator() << T
4170         << getFunctionQualifiersAsString(FnTy)
4171         << FixItHint::CreateRemoval(RemovalRange);
4172 
4173       // Strip the cv-qualifiers and ref-qualifiers from the type.
4174       FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
4175       EPI.TypeQuals = 0;
4176       EPI.RefQualifier = RQ_None;
4177 
4178       T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
4179                                   EPI);
4180       // Rebuild any parens around the identifier in the function type.
4181       for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4182         if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
4183           break;
4184         T = S.BuildParenType(T);
4185       }
4186     }
4187   }
4188 
4189   // Apply any undistributed attributes from the declarator.
4190   if (AttributeList *attrs = D.getAttributes())
4191     processTypeAttrs(state, T, TAL_DeclName, attrs);
4192 
4193   // Diagnose any ignored type attributes.
4194   state.diagnoseIgnoredTypeAttrs(T);
4195 
4196   // C++0x [dcl.constexpr]p9:
4197   //  A constexpr specifier used in an object declaration declares the object
4198   //  as const.
4199   if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
4200     T.addConst();
4201   }
4202 
4203   // If there was an ellipsis in the declarator, the declaration declares a
4204   // parameter pack whose type may be a pack expansion type.
4205   if (D.hasEllipsis()) {
4206     // C++0x [dcl.fct]p13:
4207     //   A declarator-id or abstract-declarator containing an ellipsis shall
4208     //   only be used in a parameter-declaration. Such a parameter-declaration
4209     //   is a parameter pack (14.5.3). [...]
4210     switch (D.getContext()) {
4211     case Declarator::PrototypeContext:
4212     case Declarator::LambdaExprParameterContext:
4213       // C++0x [dcl.fct]p13:
4214       //   [...] When it is part of a parameter-declaration-clause, the
4215       //   parameter pack is a function parameter pack (14.5.3). The type T
4216       //   of the declarator-id of the function parameter pack shall contain
4217       //   a template parameter pack; each template parameter pack in T is
4218       //   expanded by the function parameter pack.
4219       //
4220       // We represent function parameter packs as function parameters whose
4221       // type is a pack expansion.
4222       if (!T->containsUnexpandedParameterPack()) {
4223         S.Diag(D.getEllipsisLoc(),
4224              diag::err_function_parameter_pack_without_parameter_packs)
4225           << T <<  D.getSourceRange();
4226         D.setEllipsisLoc(SourceLocation());
4227       } else {
4228         T = Context.getPackExpansionType(T, None);
4229       }
4230       break;
4231     case Declarator::TemplateParamContext:
4232       // C++0x [temp.param]p15:
4233       //   If a template-parameter is a [...] is a parameter-declaration that
4234       //   declares a parameter pack (8.3.5), then the template-parameter is a
4235       //   template parameter pack (14.5.3).
4236       //
4237       // Note: core issue 778 clarifies that, if there are any unexpanded
4238       // parameter packs in the type of the non-type template parameter, then
4239       // it expands those parameter packs.
4240       if (T->containsUnexpandedParameterPack())
4241         T = Context.getPackExpansionType(T, None);
4242       else
4243         S.Diag(D.getEllipsisLoc(),
4244                LangOpts.CPlusPlus11
4245                  ? diag::warn_cxx98_compat_variadic_templates
4246                  : diag::ext_variadic_templates);
4247       break;
4248 
4249     case Declarator::FileContext:
4250     case Declarator::KNRTypeListContext:
4251     case Declarator::ObjCParameterContext:  // FIXME: special diagnostic here?
4252     case Declarator::ObjCResultContext:     // FIXME: special diagnostic here?
4253     case Declarator::TypeNameContext:
4254     case Declarator::CXXNewContext:
4255     case Declarator::AliasDeclContext:
4256     case Declarator::AliasTemplateContext:
4257     case Declarator::MemberContext:
4258     case Declarator::BlockContext:
4259     case Declarator::ForContext:
4260     case Declarator::ConditionContext:
4261     case Declarator::CXXCatchContext:
4262     case Declarator::ObjCCatchContext:
4263     case Declarator::BlockLiteralContext:
4264     case Declarator::LambdaExprContext:
4265     case Declarator::ConversionIdContext:
4266     case Declarator::TrailingReturnContext:
4267     case Declarator::TemplateTypeArgContext:
4268       // FIXME: We may want to allow parameter packs in block-literal contexts
4269       // in the future.
4270       S.Diag(D.getEllipsisLoc(),
4271              diag::err_ellipsis_in_declarator_not_parameter);
4272       D.setEllipsisLoc(SourceLocation());
4273       break;
4274     }
4275   }
4276 
4277   assert(!T.isNull() && "T must not be null at the end of this function");
4278   if (D.isInvalidType())
4279     return Context.getTrivialTypeSourceInfo(T);
4280 
4281   return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
4282 }
4283 
4284 /// GetTypeForDeclarator - Convert the type for the specified
4285 /// declarator to Type instances.
4286 ///
4287 /// The result of this call will never be null, but the associated
4288 /// type may be a null type if there's an unrecoverable error.
4289 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
4290   // Determine the type of the declarator. Not all forms of declarator
4291   // have a type.
4292 
4293   TypeProcessingState state(*this, D);
4294 
4295   TypeSourceInfo *ReturnTypeInfo = nullptr;
4296   QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
4297 
4298   if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
4299     inferARCWriteback(state, T);
4300 
4301   return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
4302 }
4303 
4304 static void transferARCOwnershipToDeclSpec(Sema &S,
4305                                            QualType &declSpecTy,
4306                                            Qualifiers::ObjCLifetime ownership) {
4307   if (declSpecTy->isObjCRetainableType() &&
4308       declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
4309     Qualifiers qs;
4310     qs.addObjCLifetime(ownership);
4311     declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
4312   }
4313 }
4314 
4315 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
4316                                             Qualifiers::ObjCLifetime ownership,
4317                                             unsigned chunkIndex) {
4318   Sema &S = state.getSema();
4319   Declarator &D = state.getDeclarator();
4320 
4321   // Look for an explicit lifetime attribute.
4322   DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
4323   for (const AttributeList *attr = chunk.getAttrs(); attr;
4324          attr = attr->getNext())
4325     if (attr->getKind() == AttributeList::AT_ObjCOwnership)
4326       return;
4327 
4328   const char *attrStr = nullptr;
4329   switch (ownership) {
4330   case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
4331   case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
4332   case Qualifiers::OCL_Strong: attrStr = "strong"; break;
4333   case Qualifiers::OCL_Weak: attrStr = "weak"; break;
4334   case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
4335   }
4336 
4337   IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
4338   Arg->Ident = &S.Context.Idents.get(attrStr);
4339   Arg->Loc = SourceLocation();
4340 
4341   ArgsUnion Args(Arg);
4342 
4343   // If there wasn't one, add one (with an invalid source location
4344   // so that we don't make an AttributedType for it).
4345   AttributeList *attr = D.getAttributePool()
4346     .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
4347             /*scope*/ nullptr, SourceLocation(),
4348             /*args*/ &Args, 1, AttributeList::AS_GNU);
4349   spliceAttrIntoList(*attr, chunk.getAttrListRef());
4350 
4351   // TODO: mark whether we did this inference?
4352 }
4353 
4354 /// \brief Used for transferring ownership in casts resulting in l-values.
4355 static void transferARCOwnership(TypeProcessingState &state,
4356                                  QualType &declSpecTy,
4357                                  Qualifiers::ObjCLifetime ownership) {
4358   Sema &S = state.getSema();
4359   Declarator &D = state.getDeclarator();
4360 
4361   int inner = -1;
4362   bool hasIndirection = false;
4363   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4364     DeclaratorChunk &chunk = D.getTypeObject(i);
4365     switch (chunk.Kind) {
4366     case DeclaratorChunk::Paren:
4367       // Ignore parens.
4368       break;
4369 
4370     case DeclaratorChunk::Array:
4371     case DeclaratorChunk::Reference:
4372     case DeclaratorChunk::Pointer:
4373       if (inner != -1)
4374         hasIndirection = true;
4375       inner = i;
4376       break;
4377 
4378     case DeclaratorChunk::BlockPointer:
4379       if (inner != -1)
4380         transferARCOwnershipToDeclaratorChunk(state, ownership, i);
4381       return;
4382 
4383     case DeclaratorChunk::Function:
4384     case DeclaratorChunk::MemberPointer:
4385       return;
4386     }
4387   }
4388 
4389   if (inner == -1)
4390     return;
4391 
4392   DeclaratorChunk &chunk = D.getTypeObject(inner);
4393   if (chunk.Kind == DeclaratorChunk::Pointer) {
4394     if (declSpecTy->isObjCRetainableType())
4395       return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
4396     if (declSpecTy->isObjCObjectType() && hasIndirection)
4397       return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
4398   } else {
4399     assert(chunk.Kind == DeclaratorChunk::Array ||
4400            chunk.Kind == DeclaratorChunk::Reference);
4401     return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
4402   }
4403 }
4404 
4405 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
4406   TypeProcessingState state(*this, D);
4407 
4408   TypeSourceInfo *ReturnTypeInfo = nullptr;
4409   QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
4410 
4411   if (getLangOpts().ObjCAutoRefCount) {
4412     Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
4413     if (ownership != Qualifiers::OCL_None)
4414       transferARCOwnership(state, declSpecTy, ownership);
4415   }
4416 
4417   return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
4418 }
4419 
4420 /// Map an AttributedType::Kind to an AttributeList::Kind.
4421 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
4422   switch (kind) {
4423   case AttributedType::attr_address_space:
4424     return AttributeList::AT_AddressSpace;
4425   case AttributedType::attr_regparm:
4426     return AttributeList::AT_Regparm;
4427   case AttributedType::attr_vector_size:
4428     return AttributeList::AT_VectorSize;
4429   case AttributedType::attr_neon_vector_type:
4430     return AttributeList::AT_NeonVectorType;
4431   case AttributedType::attr_neon_polyvector_type:
4432     return AttributeList::AT_NeonPolyVectorType;
4433   case AttributedType::attr_objc_gc:
4434     return AttributeList::AT_ObjCGC;
4435   case AttributedType::attr_objc_ownership:
4436     return AttributeList::AT_ObjCOwnership;
4437   case AttributedType::attr_noreturn:
4438     return AttributeList::AT_NoReturn;
4439   case AttributedType::attr_cdecl:
4440     return AttributeList::AT_CDecl;
4441   case AttributedType::attr_fastcall:
4442     return AttributeList::AT_FastCall;
4443   case AttributedType::attr_stdcall:
4444     return AttributeList::AT_StdCall;
4445   case AttributedType::attr_thiscall:
4446     return AttributeList::AT_ThisCall;
4447   case AttributedType::attr_pascal:
4448     return AttributeList::AT_Pascal;
4449   case AttributedType::attr_vectorcall:
4450     return AttributeList::AT_VectorCall;
4451   case AttributedType::attr_pcs:
4452   case AttributedType::attr_pcs_vfp:
4453     return AttributeList::AT_Pcs;
4454   case AttributedType::attr_inteloclbicc:
4455     return AttributeList::AT_IntelOclBicc;
4456   case AttributedType::attr_ms_abi:
4457     return AttributeList::AT_MSABI;
4458   case AttributedType::attr_sysv_abi:
4459     return AttributeList::AT_SysVABI;
4460   case AttributedType::attr_ptr32:
4461     return AttributeList::AT_Ptr32;
4462   case AttributedType::attr_ptr64:
4463     return AttributeList::AT_Ptr64;
4464   case AttributedType::attr_sptr:
4465     return AttributeList::AT_SPtr;
4466   case AttributedType::attr_uptr:
4467     return AttributeList::AT_UPtr;
4468   case AttributedType::attr_nonnull:
4469     return AttributeList::AT_TypeNonNull;
4470   case AttributedType::attr_nullable:
4471     return AttributeList::AT_TypeNullable;
4472   case AttributedType::attr_null_unspecified:
4473     return AttributeList::AT_TypeNullUnspecified;
4474   case AttributedType::attr_objc_kindof:
4475     return AttributeList::AT_ObjCKindOf;
4476   }
4477   llvm_unreachable("unexpected attribute kind!");
4478 }
4479 
4480 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
4481                                   const AttributeList *attrs,
4482                                   const AttributeList *DeclAttrs = nullptr) {
4483   // DeclAttrs and attrs cannot be both empty.
4484   assert((attrs || DeclAttrs) &&
4485          "no type attributes in the expected location!");
4486 
4487   AttributeList::Kind parsedKind = getAttrListKind(TL.getAttrKind());
4488   // Try to search for an attribute of matching kind in attrs list.
4489   while (attrs && attrs->getKind() != parsedKind)
4490     attrs = attrs->getNext();
4491   if (!attrs) {
4492     // No matching type attribute in attrs list found.
4493     // Try searching through C++11 attributes in the declarator attribute list.
4494     while (DeclAttrs && (!DeclAttrs->isCXX11Attribute() ||
4495                          DeclAttrs->getKind() != parsedKind))
4496       DeclAttrs = DeclAttrs->getNext();
4497     attrs = DeclAttrs;
4498   }
4499 
4500   assert(attrs && "no matching type attribute in expected location!");
4501 
4502   TL.setAttrNameLoc(attrs->getLoc());
4503   if (TL.hasAttrExprOperand()) {
4504     assert(attrs->isArgExpr(0) && "mismatched attribute operand kind");
4505     TL.setAttrExprOperand(attrs->getArgAsExpr(0));
4506   } else if (TL.hasAttrEnumOperand()) {
4507     assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) &&
4508            "unexpected attribute operand kind");
4509     if (attrs->isArgIdent(0))
4510       TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc);
4511     else
4512       TL.setAttrEnumOperandLoc(attrs->getArgAsExpr(0)->getExprLoc());
4513   }
4514 
4515   // FIXME: preserve this information to here.
4516   if (TL.hasAttrOperand())
4517     TL.setAttrOperandParensRange(SourceRange());
4518 }
4519 
4520 namespace {
4521   class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
4522     ASTContext &Context;
4523     const DeclSpec &DS;
4524 
4525   public:
4526     TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
4527       : Context(Context), DS(DS) {}
4528 
4529     void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
4530       fillAttributedTypeLoc(TL, DS.getAttributes().getList());
4531       Visit(TL.getModifiedLoc());
4532     }
4533     void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4534       Visit(TL.getUnqualifiedLoc());
4535     }
4536     void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
4537       TL.setNameLoc(DS.getTypeSpecTypeLoc());
4538     }
4539     void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
4540       TL.setNameLoc(DS.getTypeSpecTypeLoc());
4541       // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
4542       // addition field. What we have is good enough for dispay of location
4543       // of 'fixit' on interface name.
4544       TL.setNameEndLoc(DS.getLocEnd());
4545     }
4546     void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
4547       TypeSourceInfo *RepTInfo = nullptr;
4548       Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
4549       TL.copy(RepTInfo->getTypeLoc());
4550     }
4551     void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
4552       TypeSourceInfo *RepTInfo = nullptr;
4553       Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
4554       TL.copy(RepTInfo->getTypeLoc());
4555     }
4556     void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
4557       TypeSourceInfo *TInfo = nullptr;
4558       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4559 
4560       // If we got no declarator info from previous Sema routines,
4561       // just fill with the typespec loc.
4562       if (!TInfo) {
4563         TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
4564         return;
4565       }
4566 
4567       TypeLoc OldTL = TInfo->getTypeLoc();
4568       if (TInfo->getType()->getAs<ElaboratedType>()) {
4569         ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
4570         TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
4571             .castAs<TemplateSpecializationTypeLoc>();
4572         TL.copy(NamedTL);
4573       } else {
4574         TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
4575         assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
4576       }
4577 
4578     }
4579     void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
4580       assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
4581       TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
4582       TL.setParensRange(DS.getTypeofParensRange());
4583     }
4584     void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
4585       assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
4586       TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
4587       TL.setParensRange(DS.getTypeofParensRange());
4588       assert(DS.getRepAsType());
4589       TypeSourceInfo *TInfo = nullptr;
4590       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4591       TL.setUnderlyingTInfo(TInfo);
4592     }
4593     void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
4594       // FIXME: This holds only because we only have one unary transform.
4595       assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
4596       TL.setKWLoc(DS.getTypeSpecTypeLoc());
4597       TL.setParensRange(DS.getTypeofParensRange());
4598       assert(DS.getRepAsType());
4599       TypeSourceInfo *TInfo = nullptr;
4600       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4601       TL.setUnderlyingTInfo(TInfo);
4602     }
4603     void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
4604       // By default, use the source location of the type specifier.
4605       TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
4606       if (TL.needsExtraLocalData()) {
4607         // Set info for the written builtin specifiers.
4608         TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
4609         // Try to have a meaningful source location.
4610         if (TL.getWrittenSignSpec() != TSS_unspecified)
4611           // Sign spec loc overrides the others (e.g., 'unsigned long').
4612           TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
4613         else if (TL.getWrittenWidthSpec() != TSW_unspecified)
4614           // Width spec loc overrides type spec loc (e.g., 'short int').
4615           TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
4616       }
4617     }
4618     void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
4619       ElaboratedTypeKeyword Keyword
4620         = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
4621       if (DS.getTypeSpecType() == TST_typename) {
4622         TypeSourceInfo *TInfo = nullptr;
4623         Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4624         if (TInfo) {
4625           TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
4626           return;
4627         }
4628       }
4629       TL.setElaboratedKeywordLoc(Keyword != ETK_None
4630                                  ? DS.getTypeSpecTypeLoc()
4631                                  : SourceLocation());
4632       const CXXScopeSpec& SS = DS.getTypeSpecScope();
4633       TL.setQualifierLoc(SS.getWithLocInContext(Context));
4634       Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
4635     }
4636     void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
4637       assert(DS.getTypeSpecType() == TST_typename);
4638       TypeSourceInfo *TInfo = nullptr;
4639       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4640       assert(TInfo);
4641       TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
4642     }
4643     void VisitDependentTemplateSpecializationTypeLoc(
4644                                  DependentTemplateSpecializationTypeLoc TL) {
4645       assert(DS.getTypeSpecType() == TST_typename);
4646       TypeSourceInfo *TInfo = nullptr;
4647       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4648       assert(TInfo);
4649       TL.copy(
4650           TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
4651     }
4652     void VisitTagTypeLoc(TagTypeLoc TL) {
4653       TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
4654     }
4655     void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
4656       // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
4657       // or an _Atomic qualifier.
4658       if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
4659         TL.setKWLoc(DS.getTypeSpecTypeLoc());
4660         TL.setParensRange(DS.getTypeofParensRange());
4661 
4662         TypeSourceInfo *TInfo = nullptr;
4663         Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4664         assert(TInfo);
4665         TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
4666       } else {
4667         TL.setKWLoc(DS.getAtomicSpecLoc());
4668         // No parens, to indicate this was spelled as an _Atomic qualifier.
4669         TL.setParensRange(SourceRange());
4670         Visit(TL.getValueLoc());
4671       }
4672     }
4673 
4674     void VisitTypeLoc(TypeLoc TL) {
4675       // FIXME: add other typespec types and change this to an assert.
4676       TL.initialize(Context, DS.getTypeSpecTypeLoc());
4677     }
4678   };
4679 
4680   class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
4681     ASTContext &Context;
4682     const DeclaratorChunk &Chunk;
4683 
4684   public:
4685     DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
4686       : Context(Context), Chunk(Chunk) {}
4687 
4688     void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4689       llvm_unreachable("qualified type locs not expected here!");
4690     }
4691     void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
4692       llvm_unreachable("decayed type locs not expected here!");
4693     }
4694 
4695     void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
4696       fillAttributedTypeLoc(TL, Chunk.getAttrs());
4697     }
4698     void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
4699       // nothing
4700     }
4701     void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
4702       assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
4703       TL.setCaretLoc(Chunk.Loc);
4704     }
4705     void VisitPointerTypeLoc(PointerTypeLoc TL) {
4706       assert(Chunk.Kind == DeclaratorChunk::Pointer);
4707       TL.setStarLoc(Chunk.Loc);
4708     }
4709     void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
4710       assert(Chunk.Kind == DeclaratorChunk::Pointer);
4711       TL.setStarLoc(Chunk.Loc);
4712     }
4713     void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
4714       assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
4715       const CXXScopeSpec& SS = Chunk.Mem.Scope();
4716       NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
4717 
4718       const Type* ClsTy = TL.getClass();
4719       QualType ClsQT = QualType(ClsTy, 0);
4720       TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
4721       // Now copy source location info into the type loc component.
4722       TypeLoc ClsTL = ClsTInfo->getTypeLoc();
4723       switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
4724       case NestedNameSpecifier::Identifier:
4725         assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
4726         {
4727           DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
4728           DNTLoc.setElaboratedKeywordLoc(SourceLocation());
4729           DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
4730           DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
4731         }
4732         break;
4733 
4734       case NestedNameSpecifier::TypeSpec:
4735       case NestedNameSpecifier::TypeSpecWithTemplate:
4736         if (isa<ElaboratedType>(ClsTy)) {
4737           ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
4738           ETLoc.setElaboratedKeywordLoc(SourceLocation());
4739           ETLoc.setQualifierLoc(NNSLoc.getPrefix());
4740           TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
4741           NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
4742         } else {
4743           ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
4744         }
4745         break;
4746 
4747       case NestedNameSpecifier::Namespace:
4748       case NestedNameSpecifier::NamespaceAlias:
4749       case NestedNameSpecifier::Global:
4750       case NestedNameSpecifier::Super:
4751         llvm_unreachable("Nested-name-specifier must name a type");
4752       }
4753 
4754       // Finally fill in MemberPointerLocInfo fields.
4755       TL.setStarLoc(Chunk.Loc);
4756       TL.setClassTInfo(ClsTInfo);
4757     }
4758     void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
4759       assert(Chunk.Kind == DeclaratorChunk::Reference);
4760       // 'Amp' is misleading: this might have been originally
4761       /// spelled with AmpAmp.
4762       TL.setAmpLoc(Chunk.Loc);
4763     }
4764     void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
4765       assert(Chunk.Kind == DeclaratorChunk::Reference);
4766       assert(!Chunk.Ref.LValueRef);
4767       TL.setAmpAmpLoc(Chunk.Loc);
4768     }
4769     void VisitArrayTypeLoc(ArrayTypeLoc TL) {
4770       assert(Chunk.Kind == DeclaratorChunk::Array);
4771       TL.setLBracketLoc(Chunk.Loc);
4772       TL.setRBracketLoc(Chunk.EndLoc);
4773       TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
4774     }
4775     void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
4776       assert(Chunk.Kind == DeclaratorChunk::Function);
4777       TL.setLocalRangeBegin(Chunk.Loc);
4778       TL.setLocalRangeEnd(Chunk.EndLoc);
4779 
4780       const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
4781       TL.setLParenLoc(FTI.getLParenLoc());
4782       TL.setRParenLoc(FTI.getRParenLoc());
4783       for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
4784         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
4785         TL.setParam(tpi++, Param);
4786       }
4787       // FIXME: exception specs
4788     }
4789     void VisitParenTypeLoc(ParenTypeLoc TL) {
4790       assert(Chunk.Kind == DeclaratorChunk::Paren);
4791       TL.setLParenLoc(Chunk.Loc);
4792       TL.setRParenLoc(Chunk.EndLoc);
4793     }
4794 
4795     void VisitTypeLoc(TypeLoc TL) {
4796       llvm_unreachable("unsupported TypeLoc kind in declarator!");
4797     }
4798   };
4799 }
4800 
4801 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
4802   SourceLocation Loc;
4803   switch (Chunk.Kind) {
4804   case DeclaratorChunk::Function:
4805   case DeclaratorChunk::Array:
4806   case DeclaratorChunk::Paren:
4807     llvm_unreachable("cannot be _Atomic qualified");
4808 
4809   case DeclaratorChunk::Pointer:
4810     Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
4811     break;
4812 
4813   case DeclaratorChunk::BlockPointer:
4814   case DeclaratorChunk::Reference:
4815   case DeclaratorChunk::MemberPointer:
4816     // FIXME: Provide a source location for the _Atomic keyword.
4817     break;
4818   }
4819 
4820   ATL.setKWLoc(Loc);
4821   ATL.setParensRange(SourceRange());
4822 }
4823 
4824 /// \brief Create and instantiate a TypeSourceInfo with type source information.
4825 ///
4826 /// \param T QualType referring to the type as written in source code.
4827 ///
4828 /// \param ReturnTypeInfo For declarators whose return type does not show
4829 /// up in the normal place in the declaration specifiers (such as a C++
4830 /// conversion function), this pointer will refer to a type source information
4831 /// for that return type.
4832 TypeSourceInfo *
4833 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
4834                                      TypeSourceInfo *ReturnTypeInfo) {
4835   TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
4836   UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
4837   const AttributeList *DeclAttrs = D.getAttributes();
4838 
4839   // Handle parameter packs whose type is a pack expansion.
4840   if (isa<PackExpansionType>(T)) {
4841     CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
4842     CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
4843   }
4844 
4845   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4846     // An AtomicTypeLoc might be produced by an atomic qualifier in this
4847     // declarator chunk.
4848     if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
4849       fillAtomicQualLoc(ATL, D.getTypeObject(i));
4850       CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
4851     }
4852 
4853     while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
4854       fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs(), DeclAttrs);
4855       CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
4856     }
4857 
4858     // FIXME: Ordering here?
4859     while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
4860       CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
4861 
4862     DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
4863     CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
4864   }
4865 
4866   // If we have different source information for the return type, use
4867   // that.  This really only applies to C++ conversion functions.
4868   if (ReturnTypeInfo) {
4869     TypeLoc TL = ReturnTypeInfo->getTypeLoc();
4870     assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
4871     memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
4872   } else {
4873     TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
4874   }
4875 
4876   return TInfo;
4877 }
4878 
4879 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
4880 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
4881   // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
4882   // and Sema during declaration parsing. Try deallocating/caching them when
4883   // it's appropriate, instead of allocating them and keeping them around.
4884   LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
4885                                                        TypeAlignment);
4886   new (LocT) LocInfoType(T, TInfo);
4887   assert(LocT->getTypeClass() != T->getTypeClass() &&
4888          "LocInfoType's TypeClass conflicts with an existing Type class");
4889   return ParsedType::make(QualType(LocT, 0));
4890 }
4891 
4892 void LocInfoType::getAsStringInternal(std::string &Str,
4893                                       const PrintingPolicy &Policy) const {
4894   llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
4895          " was used directly instead of getting the QualType through"
4896          " GetTypeFromParser");
4897 }
4898 
4899 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
4900   // C99 6.7.6: Type names have no identifier.  This is already validated by
4901   // the parser.
4902   assert(D.getIdentifier() == nullptr &&
4903          "Type name should have no identifier!");
4904 
4905   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4906   QualType T = TInfo->getType();
4907   if (D.isInvalidType())
4908     return true;
4909 
4910   // Make sure there are no unused decl attributes on the declarator.
4911   // We don't want to do this for ObjC parameters because we're going
4912   // to apply them to the actual parameter declaration.
4913   // Likewise, we don't want to do this for alias declarations, because
4914   // we are actually going to build a declaration from this eventually.
4915   if (D.getContext() != Declarator::ObjCParameterContext &&
4916       D.getContext() != Declarator::AliasDeclContext &&
4917       D.getContext() != Declarator::AliasTemplateContext)
4918     checkUnusedDeclAttributes(D);
4919 
4920   if (getLangOpts().CPlusPlus) {
4921     // Check that there are no default arguments (C++ only).
4922     CheckExtraCXXDefaultArguments(D);
4923   }
4924 
4925   return CreateParsedType(T, TInfo);
4926 }
4927 
4928 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
4929   QualType T = Context.getObjCInstanceType();
4930   TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
4931   return CreateParsedType(T, TInfo);
4932 }
4933 
4934 
4935 //===----------------------------------------------------------------------===//
4936 // Type Attribute Processing
4937 //===----------------------------------------------------------------------===//
4938 
4939 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
4940 /// specified type.  The attribute contains 1 argument, the id of the address
4941 /// space for the type.
4942 static void HandleAddressSpaceTypeAttribute(QualType &Type,
4943                                             const AttributeList &Attr, Sema &S){
4944 
4945   // If this type is already address space qualified, reject it.
4946   // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
4947   // qualifiers for two or more different address spaces."
4948   if (Type.getAddressSpace()) {
4949     S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
4950     Attr.setInvalid();
4951     return;
4952   }
4953 
4954   // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
4955   // qualified by an address-space qualifier."
4956   if (Type->isFunctionType()) {
4957     S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
4958     Attr.setInvalid();
4959     return;
4960   }
4961 
4962   unsigned ASIdx;
4963   if (Attr.getKind() == AttributeList::AT_AddressSpace) {
4964     // Check the attribute arguments.
4965     if (Attr.getNumArgs() != 1) {
4966       S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4967         << Attr.getName() << 1;
4968       Attr.setInvalid();
4969       return;
4970     }
4971     Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4972     llvm::APSInt addrSpace(32);
4973     if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
4974         !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
4975       S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
4976         << Attr.getName() << AANT_ArgumentIntegerConstant
4977         << ASArgExpr->getSourceRange();
4978       Attr.setInvalid();
4979       return;
4980     }
4981 
4982     // Bounds checking.
4983     if (addrSpace.isSigned()) {
4984       if (addrSpace.isNegative()) {
4985         S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
4986           << ASArgExpr->getSourceRange();
4987         Attr.setInvalid();
4988         return;
4989       }
4990       addrSpace.setIsSigned(false);
4991     }
4992     llvm::APSInt max(addrSpace.getBitWidth());
4993     max = Qualifiers::MaxAddressSpace;
4994     if (addrSpace > max) {
4995       S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
4996         << int(Qualifiers::MaxAddressSpace) << ASArgExpr->getSourceRange();
4997       Attr.setInvalid();
4998       return;
4999     }
5000     ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
5001   } else {
5002     // The keyword-based type attributes imply which address space to use.
5003     switch (Attr.getKind()) {
5004     case AttributeList::AT_OpenCLGlobalAddressSpace:
5005       ASIdx = LangAS::opencl_global; break;
5006     case AttributeList::AT_OpenCLLocalAddressSpace:
5007       ASIdx = LangAS::opencl_local; break;
5008     case AttributeList::AT_OpenCLConstantAddressSpace:
5009       ASIdx = LangAS::opencl_constant; break;
5010     case AttributeList::AT_OpenCLGenericAddressSpace:
5011       ASIdx = LangAS::opencl_generic; break;
5012     default:
5013       assert(Attr.getKind() == AttributeList::AT_OpenCLPrivateAddressSpace);
5014       ASIdx = 0; break;
5015     }
5016   }
5017 
5018   Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
5019 }
5020 
5021 /// Does this type have a "direct" ownership qualifier?  That is,
5022 /// is it written like "__strong id", as opposed to something like
5023 /// "typeof(foo)", where that happens to be strong?
5024 static bool hasDirectOwnershipQualifier(QualType type) {
5025   // Fast path: no qualifier at all.
5026   assert(type.getQualifiers().hasObjCLifetime());
5027 
5028   while (true) {
5029     // __strong id
5030     if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
5031       if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
5032         return true;
5033 
5034       type = attr->getModifiedType();
5035 
5036     // X *__strong (...)
5037     } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
5038       type = paren->getInnerType();
5039 
5040     // That's it for things we want to complain about.  In particular,
5041     // we do not want to look through typedefs, typeof(expr),
5042     // typeof(type), or any other way that the type is somehow
5043     // abstracted.
5044     } else {
5045 
5046       return false;
5047     }
5048   }
5049 }
5050 
5051 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
5052 /// attribute on the specified type.
5053 ///
5054 /// Returns 'true' if the attribute was handled.
5055 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
5056                                        AttributeList &attr,
5057                                        QualType &type) {
5058   bool NonObjCPointer = false;
5059 
5060   if (!type->isDependentType() && !type->isUndeducedType()) {
5061     if (const PointerType *ptr = type->getAs<PointerType>()) {
5062       QualType pointee = ptr->getPointeeType();
5063       if (pointee->isObjCRetainableType() || pointee->isPointerType())
5064         return false;
5065       // It is important not to lose the source info that there was an attribute
5066       // applied to non-objc pointer. We will create an attributed type but
5067       // its type will be the same as the original type.
5068       NonObjCPointer = true;
5069     } else if (!type->isObjCRetainableType()) {
5070       return false;
5071     }
5072 
5073     // Don't accept an ownership attribute in the declspec if it would
5074     // just be the return type of a block pointer.
5075     if (state.isProcessingDeclSpec()) {
5076       Declarator &D = state.getDeclarator();
5077       if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
5078                                   /*onlyBlockPointers=*/true))
5079         return false;
5080     }
5081   }
5082 
5083   Sema &S = state.getSema();
5084   SourceLocation AttrLoc = attr.getLoc();
5085   if (AttrLoc.isMacroID())
5086     AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
5087 
5088   if (!attr.isArgIdent(0)) {
5089     S.Diag(AttrLoc, diag::err_attribute_argument_type)
5090       << attr.getName() << AANT_ArgumentString;
5091     attr.setInvalid();
5092     return true;
5093   }
5094 
5095   // Consume lifetime attributes without further comment outside of
5096   // ARC mode.
5097   if (!S.getLangOpts().ObjCAutoRefCount)
5098     return true;
5099 
5100   IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5101   Qualifiers::ObjCLifetime lifetime;
5102   if (II->isStr("none"))
5103     lifetime = Qualifiers::OCL_ExplicitNone;
5104   else if (II->isStr("strong"))
5105     lifetime = Qualifiers::OCL_Strong;
5106   else if (II->isStr("weak"))
5107     lifetime = Qualifiers::OCL_Weak;
5108   else if (II->isStr("autoreleasing"))
5109     lifetime = Qualifiers::OCL_Autoreleasing;
5110   else {
5111     S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
5112       << attr.getName() << II;
5113     attr.setInvalid();
5114     return true;
5115   }
5116 
5117   SplitQualType underlyingType = type.split();
5118 
5119   // Check for redundant/conflicting ownership qualifiers.
5120   if (Qualifiers::ObjCLifetime previousLifetime
5121         = type.getQualifiers().getObjCLifetime()) {
5122     // If it's written directly, that's an error.
5123     if (hasDirectOwnershipQualifier(type)) {
5124       S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
5125         << type;
5126       return true;
5127     }
5128 
5129     // Otherwise, if the qualifiers actually conflict, pull sugar off
5130     // until we reach a type that is directly qualified.
5131     if (previousLifetime != lifetime) {
5132       // This should always terminate: the canonical type is
5133       // qualified, so some bit of sugar must be hiding it.
5134       while (!underlyingType.Quals.hasObjCLifetime()) {
5135         underlyingType = underlyingType.getSingleStepDesugaredType();
5136       }
5137       underlyingType.Quals.removeObjCLifetime();
5138     }
5139   }
5140 
5141   underlyingType.Quals.addObjCLifetime(lifetime);
5142 
5143   if (NonObjCPointer) {
5144     StringRef name = attr.getName()->getName();
5145     switch (lifetime) {
5146     case Qualifiers::OCL_None:
5147     case Qualifiers::OCL_ExplicitNone:
5148       break;
5149     case Qualifiers::OCL_Strong: name = "__strong"; break;
5150     case Qualifiers::OCL_Weak: name = "__weak"; break;
5151     case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
5152     }
5153     S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
5154       << TDS_ObjCObjOrBlock << type;
5155   }
5156 
5157   QualType origType = type;
5158   if (!NonObjCPointer)
5159     type = S.Context.getQualifiedType(underlyingType);
5160 
5161   // If we have a valid source location for the attribute, use an
5162   // AttributedType instead.
5163   if (AttrLoc.isValid())
5164     type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
5165                                        origType, type);
5166 
5167   // Forbid __weak if the runtime doesn't support it.
5168   if (lifetime == Qualifiers::OCL_Weak &&
5169       !S.getLangOpts().ObjCARCWeak && !NonObjCPointer) {
5170 
5171     // Actually, delay this until we know what we're parsing.
5172     if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
5173       S.DelayedDiagnostics.add(
5174           sema::DelayedDiagnostic::makeForbiddenType(
5175               S.getSourceManager().getExpansionLoc(AttrLoc),
5176               diag::err_arc_weak_no_runtime, type, /*ignored*/ 0));
5177     } else {
5178       S.Diag(AttrLoc, diag::err_arc_weak_no_runtime);
5179     }
5180 
5181     attr.setInvalid();
5182     return true;
5183   }
5184 
5185   // Forbid __weak for class objects marked as
5186   // objc_arc_weak_reference_unavailable
5187   if (lifetime == Qualifiers::OCL_Weak) {
5188     if (const ObjCObjectPointerType *ObjT =
5189           type->getAs<ObjCObjectPointerType>()) {
5190       if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
5191         if (Class->isArcWeakrefUnavailable()) {
5192             S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
5193             S.Diag(ObjT->getInterfaceDecl()->getLocation(),
5194                    diag::note_class_declared);
5195         }
5196       }
5197     }
5198   }
5199 
5200   return true;
5201 }
5202 
5203 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
5204 /// attribute on the specified type.  Returns true to indicate that
5205 /// the attribute was handled, false to indicate that the type does
5206 /// not permit the attribute.
5207 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
5208                                  AttributeList &attr,
5209                                  QualType &type) {
5210   Sema &S = state.getSema();
5211 
5212   // Delay if this isn't some kind of pointer.
5213   if (!type->isPointerType() &&
5214       !type->isObjCObjectPointerType() &&
5215       !type->isBlockPointerType())
5216     return false;
5217 
5218   if (type.getObjCGCAttr() != Qualifiers::GCNone) {
5219     S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
5220     attr.setInvalid();
5221     return true;
5222   }
5223 
5224   // Check the attribute arguments.
5225   if (!attr.isArgIdent(0)) {
5226     S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
5227       << attr.getName() << AANT_ArgumentString;
5228     attr.setInvalid();
5229     return true;
5230   }
5231   Qualifiers::GC GCAttr;
5232   if (attr.getNumArgs() > 1) {
5233     S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5234       << attr.getName() << 1;
5235     attr.setInvalid();
5236     return true;
5237   }
5238 
5239   IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5240   if (II->isStr("weak"))
5241     GCAttr = Qualifiers::Weak;
5242   else if (II->isStr("strong"))
5243     GCAttr = Qualifiers::Strong;
5244   else {
5245     S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
5246       << attr.getName() << II;
5247     attr.setInvalid();
5248     return true;
5249   }
5250 
5251   QualType origType = type;
5252   type = S.Context.getObjCGCQualType(origType, GCAttr);
5253 
5254   // Make an attributed type to preserve the source information.
5255   if (attr.getLoc().isValid())
5256     type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
5257                                        origType, type);
5258 
5259   return true;
5260 }
5261 
5262 namespace {
5263   /// A helper class to unwrap a type down to a function for the
5264   /// purposes of applying attributes there.
5265   ///
5266   /// Use:
5267   ///   FunctionTypeUnwrapper unwrapped(SemaRef, T);
5268   ///   if (unwrapped.isFunctionType()) {
5269   ///     const FunctionType *fn = unwrapped.get();
5270   ///     // change fn somehow
5271   ///     T = unwrapped.wrap(fn);
5272   ///   }
5273   struct FunctionTypeUnwrapper {
5274     enum WrapKind {
5275       Desugar,
5276       Parens,
5277       Pointer,
5278       BlockPointer,
5279       Reference,
5280       MemberPointer
5281     };
5282 
5283     QualType Original;
5284     const FunctionType *Fn;
5285     SmallVector<unsigned char /*WrapKind*/, 8> Stack;
5286 
5287     FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
5288       while (true) {
5289         const Type *Ty = T.getTypePtr();
5290         if (isa<FunctionType>(Ty)) {
5291           Fn = cast<FunctionType>(Ty);
5292           return;
5293         } else if (isa<ParenType>(Ty)) {
5294           T = cast<ParenType>(Ty)->getInnerType();
5295           Stack.push_back(Parens);
5296         } else if (isa<PointerType>(Ty)) {
5297           T = cast<PointerType>(Ty)->getPointeeType();
5298           Stack.push_back(Pointer);
5299         } else if (isa<BlockPointerType>(Ty)) {
5300           T = cast<BlockPointerType>(Ty)->getPointeeType();
5301           Stack.push_back(BlockPointer);
5302         } else if (isa<MemberPointerType>(Ty)) {
5303           T = cast<MemberPointerType>(Ty)->getPointeeType();
5304           Stack.push_back(MemberPointer);
5305         } else if (isa<ReferenceType>(Ty)) {
5306           T = cast<ReferenceType>(Ty)->getPointeeType();
5307           Stack.push_back(Reference);
5308         } else {
5309           const Type *DTy = Ty->getUnqualifiedDesugaredType();
5310           if (Ty == DTy) {
5311             Fn = nullptr;
5312             return;
5313           }
5314 
5315           T = QualType(DTy, 0);
5316           Stack.push_back(Desugar);
5317         }
5318       }
5319     }
5320 
5321     bool isFunctionType() const { return (Fn != nullptr); }
5322     const FunctionType *get() const { return Fn; }
5323 
5324     QualType wrap(Sema &S, const FunctionType *New) {
5325       // If T wasn't modified from the unwrapped type, do nothing.
5326       if (New == get()) return Original;
5327 
5328       Fn = New;
5329       return wrap(S.Context, Original, 0);
5330     }
5331 
5332   private:
5333     QualType wrap(ASTContext &C, QualType Old, unsigned I) {
5334       if (I == Stack.size())
5335         return C.getQualifiedType(Fn, Old.getQualifiers());
5336 
5337       // Build up the inner type, applying the qualifiers from the old
5338       // type to the new type.
5339       SplitQualType SplitOld = Old.split();
5340 
5341       // As a special case, tail-recurse if there are no qualifiers.
5342       if (SplitOld.Quals.empty())
5343         return wrap(C, SplitOld.Ty, I);
5344       return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
5345     }
5346 
5347     QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
5348       if (I == Stack.size()) return QualType(Fn, 0);
5349 
5350       switch (static_cast<WrapKind>(Stack[I++])) {
5351       case Desugar:
5352         // This is the point at which we potentially lose source
5353         // information.
5354         return wrap(C, Old->getUnqualifiedDesugaredType(), I);
5355 
5356       case Parens: {
5357         QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
5358         return C.getParenType(New);
5359       }
5360 
5361       case Pointer: {
5362         QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
5363         return C.getPointerType(New);
5364       }
5365 
5366       case BlockPointer: {
5367         QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
5368         return C.getBlockPointerType(New);
5369       }
5370 
5371       case MemberPointer: {
5372         const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
5373         QualType New = wrap(C, OldMPT->getPointeeType(), I);
5374         return C.getMemberPointerType(New, OldMPT->getClass());
5375       }
5376 
5377       case Reference: {
5378         const ReferenceType *OldRef = cast<ReferenceType>(Old);
5379         QualType New = wrap(C, OldRef->getPointeeType(), I);
5380         if (isa<LValueReferenceType>(OldRef))
5381           return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
5382         else
5383           return C.getRValueReferenceType(New);
5384       }
5385       }
5386 
5387       llvm_unreachable("unknown wrapping kind");
5388     }
5389   };
5390 }
5391 
5392 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
5393                                              AttributeList &Attr,
5394                                              QualType &Type) {
5395   Sema &S = State.getSema();
5396 
5397   AttributeList::Kind Kind = Attr.getKind();
5398   QualType Desugared = Type;
5399   const AttributedType *AT = dyn_cast<AttributedType>(Type);
5400   while (AT) {
5401     AttributedType::Kind CurAttrKind = AT->getAttrKind();
5402 
5403     // You cannot specify duplicate type attributes, so if the attribute has
5404     // already been applied, flag it.
5405     if (getAttrListKind(CurAttrKind) == Kind) {
5406       S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact)
5407         << Attr.getName();
5408       return true;
5409     }
5410 
5411     // You cannot have both __sptr and __uptr on the same type, nor can you
5412     // have __ptr32 and __ptr64.
5413     if ((CurAttrKind == AttributedType::attr_ptr32 &&
5414          Kind == AttributeList::AT_Ptr64) ||
5415         (CurAttrKind == AttributedType::attr_ptr64 &&
5416          Kind == AttributeList::AT_Ptr32)) {
5417       S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
5418         << "'__ptr32'" << "'__ptr64'";
5419       return true;
5420     } else if ((CurAttrKind == AttributedType::attr_sptr &&
5421                 Kind == AttributeList::AT_UPtr) ||
5422                (CurAttrKind == AttributedType::attr_uptr &&
5423                 Kind == AttributeList::AT_SPtr)) {
5424       S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
5425         << "'__sptr'" << "'__uptr'";
5426       return true;
5427     }
5428 
5429     Desugared = AT->getEquivalentType();
5430     AT = dyn_cast<AttributedType>(Desugared);
5431   }
5432 
5433   // Pointer type qualifiers can only operate on pointer types, but not
5434   // pointer-to-member types.
5435   if (!isa<PointerType>(Desugared)) {
5436     S.Diag(Attr.getLoc(), Type->isMemberPointerType() ?
5437                           diag::err_attribute_no_member_pointers :
5438                           diag::err_attribute_pointers_only) << Attr.getName();
5439     return true;
5440   }
5441 
5442   AttributedType::Kind TAK;
5443   switch (Kind) {
5444   default: llvm_unreachable("Unknown attribute kind");
5445   case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break;
5446   case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break;
5447   case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break;
5448   case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break;
5449   }
5450 
5451   Type = S.Context.getAttributedType(TAK, Type, Type);
5452   return false;
5453 }
5454 
5455 bool Sema::checkNullabilityTypeSpecifier(QualType &type,
5456                                          NullabilityKind nullability,
5457                                          SourceLocation nullabilityLoc,
5458                                          bool isContextSensitive) {
5459   // We saw a nullability type specifier. If this is the first one for
5460   // this file, note that.
5461   FileID file = getNullabilityCompletenessCheckFileID(*this, nullabilityLoc);
5462   if (!file.isInvalid()) {
5463     FileNullability &fileNullability = NullabilityMap[file];
5464     if (!fileNullability.SawTypeNullability) {
5465       // If we have already seen a pointer declarator without a nullability
5466       // annotation, complain about it.
5467       if (fileNullability.PointerLoc.isValid()) {
5468         Diag(fileNullability.PointerLoc, diag::warn_nullability_missing)
5469           << static_cast<unsigned>(fileNullability.PointerKind);
5470       }
5471 
5472       fileNullability.SawTypeNullability = true;
5473     }
5474   }
5475 
5476   // Check for existing nullability attributes on the type.
5477   QualType desugared = type;
5478   while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
5479     // Check whether there is already a null
5480     if (auto existingNullability = attributed->getImmediateNullability()) {
5481       // Duplicated nullability.
5482       if (nullability == *existingNullability) {
5483         Diag(nullabilityLoc, diag::warn_nullability_duplicate)
5484           << DiagNullabilityKind(nullability, isContextSensitive)
5485           << FixItHint::CreateRemoval(nullabilityLoc);
5486 
5487         break;
5488       }
5489 
5490       // Conflicting nullability.
5491       Diag(nullabilityLoc, diag::err_nullability_conflicting)
5492         << DiagNullabilityKind(nullability, isContextSensitive)
5493         << DiagNullabilityKind(*existingNullability, false);
5494       return true;
5495     }
5496 
5497     desugared = attributed->getModifiedType();
5498   }
5499 
5500   // If there is already a different nullability specifier, complain.
5501   // This (unlike the code above) looks through typedefs that might
5502   // have nullability specifiers on them, which means we cannot
5503   // provide a useful Fix-It.
5504   if (auto existingNullability = desugared->getNullability(Context)) {
5505     if (nullability != *existingNullability) {
5506       Diag(nullabilityLoc, diag::err_nullability_conflicting)
5507         << DiagNullabilityKind(nullability, isContextSensitive)
5508         << DiagNullabilityKind(*existingNullability, false);
5509 
5510       // Try to find the typedef with the existing nullability specifier.
5511       if (auto typedefType = desugared->getAs<TypedefType>()) {
5512         TypedefNameDecl *typedefDecl = typedefType->getDecl();
5513         QualType underlyingType = typedefDecl->getUnderlyingType();
5514         if (auto typedefNullability
5515               = AttributedType::stripOuterNullability(underlyingType)) {
5516           if (*typedefNullability == *existingNullability) {
5517             Diag(typedefDecl->getLocation(), diag::note_nullability_here)
5518               << DiagNullabilityKind(*existingNullability, false);
5519           }
5520         }
5521       }
5522 
5523       return true;
5524     }
5525   }
5526 
5527   // If this definitely isn't a pointer type, reject the specifier.
5528   if (!desugared->canHaveNullability()) {
5529     Diag(nullabilityLoc, diag::err_nullability_nonpointer)
5530       << DiagNullabilityKind(nullability, isContextSensitive) << type;
5531     return true;
5532   }
5533 
5534   // For the context-sensitive keywords/Objective-C property
5535   // attributes, require that the type be a single-level pointer.
5536   if (isContextSensitive) {
5537     // Make sure that the pointee isn't itself a pointer type.
5538     QualType pointeeType = desugared->getPointeeType();
5539     if (pointeeType->isAnyPointerType() ||
5540         pointeeType->isObjCObjectPointerType() ||
5541         pointeeType->isMemberPointerType()) {
5542       Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
5543         << DiagNullabilityKind(nullability, true)
5544         << type;
5545       Diag(nullabilityLoc, diag::note_nullability_type_specifier)
5546         << DiagNullabilityKind(nullability, false)
5547         << type
5548         << FixItHint::CreateReplacement(nullabilityLoc,
5549                                         getNullabilitySpelling(nullability));
5550       return true;
5551     }
5552   }
5553 
5554   // Form the attributed type.
5555   type = Context.getAttributedType(
5556            AttributedType::getNullabilityAttrKind(nullability), type, type);
5557   return false;
5558 }
5559 
5560 bool Sema::checkObjCKindOfType(QualType &type, SourceLocation loc) {
5561   // Find out if it's an Objective-C object or object pointer type;
5562   const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
5563   const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
5564                                           : type->getAs<ObjCObjectType>();
5565 
5566   // If not, we can't apply __kindof.
5567   if (!objType) {
5568     // FIXME: Handle dependent types that aren't yet object types.
5569     Diag(loc, diag::err_objc_kindof_nonobject)
5570       << type;
5571     return true;
5572   }
5573 
5574   // Rebuild the "equivalent" type, which pushes __kindof down into
5575   // the object type.
5576   QualType equivType = Context.getObjCObjectType(objType->getBaseType(),
5577                                                  objType->getTypeArgsAsWritten(),
5578                                                  objType->getProtocols(),
5579                                                  /*isKindOf=*/true);
5580 
5581   // If we started with an object pointer type, rebuild it.
5582   if (ptrType) {
5583     equivType = Context.getObjCObjectPointerType(equivType);
5584     if (auto nullability = type->getNullability(Context)) {
5585       auto attrKind = AttributedType::getNullabilityAttrKind(*nullability);
5586       equivType = Context.getAttributedType(attrKind, equivType, equivType);
5587     }
5588   }
5589 
5590   // Build the attributed type to record where __kindof occurred.
5591   type = Context.getAttributedType(AttributedType::attr_objc_kindof,
5592                                    type,
5593                                    equivType);
5594 
5595   return false;
5596 }
5597 
5598 /// Map a nullability attribute kind to a nullability kind.
5599 static NullabilityKind mapNullabilityAttrKind(AttributeList::Kind kind) {
5600   switch (kind) {
5601   case AttributeList::AT_TypeNonNull:
5602     return NullabilityKind::NonNull;
5603 
5604   case AttributeList::AT_TypeNullable:
5605     return NullabilityKind::Nullable;
5606 
5607   case AttributeList::AT_TypeNullUnspecified:
5608     return NullabilityKind::Unspecified;
5609 
5610   default:
5611     llvm_unreachable("not a nullability attribute kind");
5612   }
5613 }
5614 
5615 /// Distribute a nullability type attribute that cannot be applied to
5616 /// the type specifier to a pointer, block pointer, or member pointer
5617 /// declarator, complaining if necessary.
5618 ///
5619 /// \returns true if the nullability annotation was distributed, false
5620 /// otherwise.
5621 static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
5622                                           QualType type,
5623                                           AttributeList &attr) {
5624   Declarator &declarator = state.getDeclarator();
5625 
5626   /// Attempt to move the attribute to the specified chunk.
5627   auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
5628     // If there is already a nullability attribute there, don't add
5629     // one.
5630     if (hasNullabilityAttr(chunk.getAttrListRef()))
5631       return false;
5632 
5633     // Complain about the nullability qualifier being in the wrong
5634     // place.
5635     enum {
5636       PK_Pointer,
5637       PK_BlockPointer,
5638       PK_MemberPointer,
5639       PK_FunctionPointer,
5640       PK_MemberFunctionPointer,
5641     } pointerKind
5642       = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
5643                                                              : PK_Pointer)
5644         : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
5645         : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
5646 
5647     auto diag = state.getSema().Diag(attr.getLoc(),
5648                                      diag::warn_nullability_declspec)
5649       << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
5650                              attr.isContextSensitiveKeywordAttribute())
5651       << type
5652       << static_cast<unsigned>(pointerKind);
5653 
5654     // FIXME: MemberPointer chunks don't carry the location of the *.
5655     if (chunk.Kind != DeclaratorChunk::MemberPointer) {
5656       diag << FixItHint::CreateRemoval(attr.getLoc())
5657            << FixItHint::CreateInsertion(
5658                 state.getSema().getPreprocessor()
5659                   .getLocForEndOfToken(chunk.Loc),
5660                 " " + attr.getName()->getName().str() + " ");
5661     }
5662 
5663     moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
5664                            chunk.getAttrListRef());
5665     return true;
5666   };
5667 
5668   // Move it to the outermost pointer, member pointer, or block
5669   // pointer declarator.
5670   for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
5671     DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
5672     switch (chunk.Kind) {
5673     case DeclaratorChunk::Pointer:
5674     case DeclaratorChunk::BlockPointer:
5675     case DeclaratorChunk::MemberPointer:
5676       return moveToChunk(chunk, false);
5677 
5678     case DeclaratorChunk::Paren:
5679     case DeclaratorChunk::Array:
5680       continue;
5681 
5682     case DeclaratorChunk::Function:
5683       // Try to move past the return type to a function/block/member
5684       // function pointer.
5685       if (DeclaratorChunk *dest = maybeMovePastReturnType(
5686                                     declarator, i,
5687                                     /*onlyBlockPointers=*/false)) {
5688         return moveToChunk(*dest, true);
5689       }
5690 
5691       return false;
5692 
5693     // Don't walk through these.
5694     case DeclaratorChunk::Reference:
5695       return false;
5696     }
5697   }
5698 
5699   return false;
5700 }
5701 
5702 static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) {
5703   assert(!Attr.isInvalid());
5704   switch (Attr.getKind()) {
5705   default:
5706     llvm_unreachable("not a calling convention attribute");
5707   case AttributeList::AT_CDecl:
5708     return AttributedType::attr_cdecl;
5709   case AttributeList::AT_FastCall:
5710     return AttributedType::attr_fastcall;
5711   case AttributeList::AT_StdCall:
5712     return AttributedType::attr_stdcall;
5713   case AttributeList::AT_ThisCall:
5714     return AttributedType::attr_thiscall;
5715   case AttributeList::AT_Pascal:
5716     return AttributedType::attr_pascal;
5717   case AttributeList::AT_VectorCall:
5718     return AttributedType::attr_vectorcall;
5719   case AttributeList::AT_Pcs: {
5720     // The attribute may have had a fixit applied where we treated an
5721     // identifier as a string literal.  The contents of the string are valid,
5722     // but the form may not be.
5723     StringRef Str;
5724     if (Attr.isArgExpr(0))
5725       Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
5726     else
5727       Str = Attr.getArgAsIdent(0)->Ident->getName();
5728     return llvm::StringSwitch<AttributedType::Kind>(Str)
5729         .Case("aapcs", AttributedType::attr_pcs)
5730         .Case("aapcs-vfp", AttributedType::attr_pcs_vfp);
5731   }
5732   case AttributeList::AT_IntelOclBicc:
5733     return AttributedType::attr_inteloclbicc;
5734   case AttributeList::AT_MSABI:
5735     return AttributedType::attr_ms_abi;
5736   case AttributeList::AT_SysVABI:
5737     return AttributedType::attr_sysv_abi;
5738   }
5739   llvm_unreachable("unexpected attribute kind!");
5740 }
5741 
5742 /// Process an individual function attribute.  Returns true to
5743 /// indicate that the attribute was handled, false if it wasn't.
5744 static bool handleFunctionTypeAttr(TypeProcessingState &state,
5745                                    AttributeList &attr,
5746                                    QualType &type) {
5747   Sema &S = state.getSema();
5748 
5749   FunctionTypeUnwrapper unwrapped(S, type);
5750 
5751   if (attr.getKind() == AttributeList::AT_NoReturn) {
5752     if (S.CheckNoReturnAttr(attr))
5753       return true;
5754 
5755     // Delay if this is not a function type.
5756     if (!unwrapped.isFunctionType())
5757       return false;
5758 
5759     // Otherwise we can process right away.
5760     FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
5761     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5762     return true;
5763   }
5764 
5765   // ns_returns_retained is not always a type attribute, but if we got
5766   // here, we're treating it as one right now.
5767   if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
5768     assert(S.getLangOpts().ObjCAutoRefCount &&
5769            "ns_returns_retained treated as type attribute in non-ARC");
5770     if (attr.getNumArgs()) return true;
5771 
5772     // Delay if this is not a function type.
5773     if (!unwrapped.isFunctionType())
5774       return false;
5775 
5776     FunctionType::ExtInfo EI
5777       = unwrapped.get()->getExtInfo().withProducesResult(true);
5778     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5779     return true;
5780   }
5781 
5782   if (attr.getKind() == AttributeList::AT_Regparm) {
5783     unsigned value;
5784     if (S.CheckRegparmAttr(attr, value))
5785       return true;
5786 
5787     // Delay if this is not a function type.
5788     if (!unwrapped.isFunctionType())
5789       return false;
5790 
5791     // Diagnose regparm with fastcall.
5792     const FunctionType *fn = unwrapped.get();
5793     CallingConv CC = fn->getCallConv();
5794     if (CC == CC_X86FastCall) {
5795       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
5796         << FunctionType::getNameForCallConv(CC)
5797         << "regparm";
5798       attr.setInvalid();
5799       return true;
5800     }
5801 
5802     FunctionType::ExtInfo EI =
5803       unwrapped.get()->getExtInfo().withRegParm(value);
5804     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5805     return true;
5806   }
5807 
5808   // Delay if the type didn't work out to a function.
5809   if (!unwrapped.isFunctionType()) return false;
5810 
5811   // Otherwise, a calling convention.
5812   CallingConv CC;
5813   if (S.CheckCallingConvAttr(attr, CC))
5814     return true;
5815 
5816   const FunctionType *fn = unwrapped.get();
5817   CallingConv CCOld = fn->getCallConv();
5818   AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr);
5819 
5820   if (CCOld != CC) {
5821     // Error out on when there's already an attribute on the type
5822     // and the CCs don't match.
5823     const AttributedType *AT = S.getCallingConvAttributedType(type);
5824     if (AT && AT->getAttrKind() != CCAttrKind) {
5825       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
5826         << FunctionType::getNameForCallConv(CC)
5827         << FunctionType::getNameForCallConv(CCOld);
5828       attr.setInvalid();
5829       return true;
5830     }
5831   }
5832 
5833   // Diagnose use of callee-cleanup calling convention on variadic functions.
5834   if (!supportsVariadicCall(CC)) {
5835     const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
5836     if (FnP && FnP->isVariadic()) {
5837       unsigned DiagID = diag::err_cconv_varargs;
5838       // stdcall and fastcall are ignored with a warning for GCC and MS
5839       // compatibility.
5840       if (CC == CC_X86StdCall || CC == CC_X86FastCall)
5841         DiagID = diag::warn_cconv_varargs;
5842 
5843       S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC);
5844       attr.setInvalid();
5845       return true;
5846     }
5847   }
5848 
5849   // Also diagnose fastcall with regparm.
5850   if (CC == CC_X86FastCall && fn->getHasRegParm()) {
5851     S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
5852         << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
5853     attr.setInvalid();
5854     return true;
5855   }
5856 
5857   // Modify the CC from the wrapped function type, wrap it all back, and then
5858   // wrap the whole thing in an AttributedType as written.  The modified type
5859   // might have a different CC if we ignored the attribute.
5860   FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
5861   QualType Equivalent =
5862       unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5863   type = S.Context.getAttributedType(CCAttrKind, type, Equivalent);
5864   return true;
5865 }
5866 
5867 bool Sema::hasExplicitCallingConv(QualType &T) {
5868   QualType R = T.IgnoreParens();
5869   while (const AttributedType *AT = dyn_cast<AttributedType>(R)) {
5870     if (AT->isCallingConv())
5871       return true;
5872     R = AT->getModifiedType().IgnoreParens();
5873   }
5874   return false;
5875 }
5876 
5877 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
5878                                   SourceLocation Loc) {
5879   FunctionTypeUnwrapper Unwrapped(*this, T);
5880   const FunctionType *FT = Unwrapped.get();
5881   bool IsVariadic = (isa<FunctionProtoType>(FT) &&
5882                      cast<FunctionProtoType>(FT)->isVariadic());
5883   CallingConv CurCC = FT->getCallConv();
5884   CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
5885 
5886   if (CurCC == ToCC)
5887     return;
5888 
5889   // MS compiler ignores explicit calling convention attributes on structors. We
5890   // should do the same.
5891   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
5892     // Issue a warning on ignored calling convention -- except of __stdcall.
5893     // Again, this is what MS compiler does.
5894     if (CurCC != CC_X86StdCall)
5895       Diag(Loc, diag::warn_cconv_structors)
5896           << FunctionType::getNameForCallConv(CurCC);
5897   // Default adjustment.
5898   } else {
5899     // Only adjust types with the default convention.  For example, on Windows
5900     // we should adjust a __cdecl type to __thiscall for instance methods, and a
5901     // __thiscall type to __cdecl for static methods.
5902     CallingConv DefaultCC =
5903         Context.getDefaultCallingConvention(IsVariadic, IsStatic);
5904 
5905     if (CurCC != DefaultCC || DefaultCC == ToCC)
5906       return;
5907 
5908     if (hasExplicitCallingConv(T))
5909       return;
5910   }
5911 
5912   FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
5913   QualType Wrapped = Unwrapped.wrap(*this, FT);
5914   T = Context.getAdjustedType(T, Wrapped);
5915 }
5916 
5917 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
5918 /// and float scalars, although arrays, pointers, and function return values are
5919 /// allowed in conjunction with this construct. Aggregates with this attribute
5920 /// are invalid, even if they are of the same size as a corresponding scalar.
5921 /// The raw attribute should contain precisely 1 argument, the vector size for
5922 /// the variable, measured in bytes. If curType and rawAttr are well formed,
5923 /// this routine will return a new vector type.
5924 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
5925                                  Sema &S) {
5926   // Check the attribute arguments.
5927   if (Attr.getNumArgs() != 1) {
5928     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5929       << Attr.getName() << 1;
5930     Attr.setInvalid();
5931     return;
5932   }
5933   Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5934   llvm::APSInt vecSize(32);
5935   if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
5936       !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
5937     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
5938       << Attr.getName() << AANT_ArgumentIntegerConstant
5939       << sizeExpr->getSourceRange();
5940     Attr.setInvalid();
5941     return;
5942   }
5943   // The base type must be integer (not Boolean or enumeration) or float, and
5944   // can't already be a vector.
5945   if (!CurType->isBuiltinType() || CurType->isBooleanType() ||
5946       (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
5947     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
5948     Attr.setInvalid();
5949     return;
5950   }
5951   unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
5952   // vecSize is specified in bytes - convert to bits.
5953   unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
5954 
5955   // the vector size needs to be an integral multiple of the type size.
5956   if (vectorSize % typeSize) {
5957     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
5958       << sizeExpr->getSourceRange();
5959     Attr.setInvalid();
5960     return;
5961   }
5962   if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) {
5963     S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large)
5964       << sizeExpr->getSourceRange();
5965     Attr.setInvalid();
5966     return;
5967   }
5968   if (vectorSize == 0) {
5969     S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
5970       << sizeExpr->getSourceRange();
5971     Attr.setInvalid();
5972     return;
5973   }
5974 
5975   // Success! Instantiate the vector type, the number of elements is > 0, and
5976   // not required to be a power of 2, unlike GCC.
5977   CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
5978                                     VectorType::GenericVector);
5979 }
5980 
5981 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
5982 /// a type.
5983 static void HandleExtVectorTypeAttr(QualType &CurType,
5984                                     const AttributeList &Attr,
5985                                     Sema &S) {
5986   // check the attribute arguments.
5987   if (Attr.getNumArgs() != 1) {
5988     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5989       << Attr.getName() << 1;
5990     return;
5991   }
5992 
5993   Expr *sizeExpr;
5994 
5995   // Special case where the argument is a template id.
5996   if (Attr.isArgIdent(0)) {
5997     CXXScopeSpec SS;
5998     SourceLocation TemplateKWLoc;
5999     UnqualifiedId id;
6000     id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
6001 
6002     ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
6003                                           id, false, false);
6004     if (Size.isInvalid())
6005       return;
6006 
6007     sizeExpr = Size.get();
6008   } else {
6009     sizeExpr = Attr.getArgAsExpr(0);
6010   }
6011 
6012   // Create the vector type.
6013   QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
6014   if (!T.isNull())
6015     CurType = T;
6016 }
6017 
6018 static bool isPermittedNeonBaseType(QualType &Ty,
6019                                     VectorType::VectorKind VecKind, Sema &S) {
6020   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
6021   if (!BTy)
6022     return false;
6023 
6024   llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
6025 
6026   // Signed poly is mathematically wrong, but has been baked into some ABIs by
6027   // now.
6028   bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
6029                         Triple.getArch() == llvm::Triple::aarch64_be;
6030   if (VecKind == VectorType::NeonPolyVector) {
6031     if (IsPolyUnsigned) {
6032       // AArch64 polynomial vectors are unsigned and support poly64.
6033       return BTy->getKind() == BuiltinType::UChar ||
6034              BTy->getKind() == BuiltinType::UShort ||
6035              BTy->getKind() == BuiltinType::ULong ||
6036              BTy->getKind() == BuiltinType::ULongLong;
6037     } else {
6038       // AArch32 polynomial vector are signed.
6039       return BTy->getKind() == BuiltinType::SChar ||
6040              BTy->getKind() == BuiltinType::Short;
6041     }
6042   }
6043 
6044   // Non-polynomial vector types: the usual suspects are allowed, as well as
6045   // float64_t on AArch64.
6046   bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 ||
6047                  Triple.getArch() == llvm::Triple::aarch64_be;
6048 
6049   if (Is64Bit && BTy->getKind() == BuiltinType::Double)
6050     return true;
6051 
6052   return BTy->getKind() == BuiltinType::SChar ||
6053          BTy->getKind() == BuiltinType::UChar ||
6054          BTy->getKind() == BuiltinType::Short ||
6055          BTy->getKind() == BuiltinType::UShort ||
6056          BTy->getKind() == BuiltinType::Int ||
6057          BTy->getKind() == BuiltinType::UInt ||
6058          BTy->getKind() == BuiltinType::Long ||
6059          BTy->getKind() == BuiltinType::ULong ||
6060          BTy->getKind() == BuiltinType::LongLong ||
6061          BTy->getKind() == BuiltinType::ULongLong ||
6062          BTy->getKind() == BuiltinType::Float ||
6063          BTy->getKind() == BuiltinType::Half;
6064 }
6065 
6066 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
6067 /// "neon_polyvector_type" attributes are used to create vector types that
6068 /// are mangled according to ARM's ABI.  Otherwise, these types are identical
6069 /// to those created with the "vector_size" attribute.  Unlike "vector_size"
6070 /// the argument to these Neon attributes is the number of vector elements,
6071 /// not the vector size in bytes.  The vector width and element type must
6072 /// match one of the standard Neon vector types.
6073 static void HandleNeonVectorTypeAttr(QualType& CurType,
6074                                      const AttributeList &Attr, Sema &S,
6075                                      VectorType::VectorKind VecKind) {
6076   // Target must have NEON
6077   if (!S.Context.getTargetInfo().hasFeature("neon")) {
6078     S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName();
6079     Attr.setInvalid();
6080     return;
6081   }
6082   // Check the attribute arguments.
6083   if (Attr.getNumArgs() != 1) {
6084     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6085       << Attr.getName() << 1;
6086     Attr.setInvalid();
6087     return;
6088   }
6089   // The number of elements must be an ICE.
6090   Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6091   llvm::APSInt numEltsInt(32);
6092   if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
6093       !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
6094     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6095       << Attr.getName() << AANT_ArgumentIntegerConstant
6096       << numEltsExpr->getSourceRange();
6097     Attr.setInvalid();
6098     return;
6099   }
6100   // Only certain element types are supported for Neon vectors.
6101   if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
6102     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
6103     Attr.setInvalid();
6104     return;
6105   }
6106 
6107   // The total size of the vector must be 64 or 128 bits.
6108   unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
6109   unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
6110   unsigned vecSize = typeSize * numElts;
6111   if (vecSize != 64 && vecSize != 128) {
6112     S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
6113     Attr.setInvalid();
6114     return;
6115   }
6116 
6117   CurType = S.Context.getVectorType(CurType, numElts, VecKind);
6118 }
6119 
6120 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
6121                              TypeAttrLocation TAL, AttributeList *attrs) {
6122   // Scan through and apply attributes to this type where it makes sense.  Some
6123   // attributes (such as __address_space__, __vector_size__, etc) apply to the
6124   // type, but others can be present in the type specifiers even though they
6125   // apply to the decl.  Here we apply type attributes and ignore the rest.
6126 
6127   AttributeList *next;
6128   do {
6129     AttributeList &attr = *attrs;
6130     next = attr.getNext();
6131 
6132     // Skip attributes that were marked to be invalid.
6133     if (attr.isInvalid())
6134       continue;
6135 
6136     if (attr.isCXX11Attribute()) {
6137       // [[gnu::...]] attributes are treated as declaration attributes, so may
6138       // not appertain to a DeclaratorChunk, even if we handle them as type
6139       // attributes.
6140       if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
6141         if (TAL == TAL_DeclChunk) {
6142           state.getSema().Diag(attr.getLoc(),
6143                                diag::warn_cxx11_gnu_attribute_on_type)
6144               << attr.getName();
6145           continue;
6146         }
6147       } else if (TAL != TAL_DeclChunk) {
6148         // Otherwise, only consider type processing for a C++11 attribute if
6149         // it's actually been applied to a type.
6150         continue;
6151       }
6152     }
6153 
6154     // If this is an attribute we can handle, do so now,
6155     // otherwise, add it to the FnAttrs list for rechaining.
6156     switch (attr.getKind()) {
6157     default:
6158       // A C++11 attribute on a declarator chunk must appertain to a type.
6159       if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
6160         state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
6161           << attr.getName();
6162         attr.setUsedAsTypeAttr();
6163       }
6164       break;
6165 
6166     case AttributeList::UnknownAttribute:
6167       if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
6168         state.getSema().Diag(attr.getLoc(),
6169                              diag::warn_unknown_attribute_ignored)
6170           << attr.getName();
6171       break;
6172 
6173     case AttributeList::IgnoredAttribute:
6174       break;
6175 
6176     case AttributeList::AT_MayAlias:
6177       // FIXME: This attribute needs to actually be handled, but if we ignore
6178       // it it breaks large amounts of Linux software.
6179       attr.setUsedAsTypeAttr();
6180       break;
6181     case AttributeList::AT_OpenCLPrivateAddressSpace:
6182     case AttributeList::AT_OpenCLGlobalAddressSpace:
6183     case AttributeList::AT_OpenCLLocalAddressSpace:
6184     case AttributeList::AT_OpenCLConstantAddressSpace:
6185     case AttributeList::AT_OpenCLGenericAddressSpace:
6186     case AttributeList::AT_AddressSpace:
6187       HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
6188       attr.setUsedAsTypeAttr();
6189       break;
6190     OBJC_POINTER_TYPE_ATTRS_CASELIST:
6191       if (!handleObjCPointerTypeAttr(state, attr, type))
6192         distributeObjCPointerTypeAttr(state, attr, type);
6193       attr.setUsedAsTypeAttr();
6194       break;
6195     case AttributeList::AT_VectorSize:
6196       HandleVectorSizeAttr(type, attr, state.getSema());
6197       attr.setUsedAsTypeAttr();
6198       break;
6199     case AttributeList::AT_ExtVectorType:
6200       HandleExtVectorTypeAttr(type, attr, state.getSema());
6201       attr.setUsedAsTypeAttr();
6202       break;
6203     case AttributeList::AT_NeonVectorType:
6204       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
6205                                VectorType::NeonVector);
6206       attr.setUsedAsTypeAttr();
6207       break;
6208     case AttributeList::AT_NeonPolyVectorType:
6209       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
6210                                VectorType::NeonPolyVector);
6211       attr.setUsedAsTypeAttr();
6212       break;
6213     case AttributeList::AT_OpenCLImageAccess:
6214       // FIXME: there should be some type checking happening here, I would
6215       // imagine, but the original handler's checking was entirely superfluous.
6216       attr.setUsedAsTypeAttr();
6217       break;
6218 
6219     MS_TYPE_ATTRS_CASELIST:
6220       if (!handleMSPointerTypeQualifierAttr(state, attr, type))
6221         attr.setUsedAsTypeAttr();
6222       break;
6223 
6224 
6225     NULLABILITY_TYPE_ATTRS_CASELIST:
6226       // Either add nullability here or try to distribute it.  We
6227       // don't want to distribute the nullability specifier past any
6228       // dependent type, because that complicates the user model.
6229       if (type->canHaveNullability() || type->isDependentType() ||
6230           !distributeNullabilityTypeAttr(state, type, attr)) {
6231         if (state.getSema().checkNullabilityTypeSpecifier(
6232               type,
6233               mapNullabilityAttrKind(attr.getKind()),
6234               attr.getLoc(),
6235               attr.isContextSensitiveKeywordAttribute())) {
6236           attr.setInvalid();
6237         }
6238 
6239         attr.setUsedAsTypeAttr();
6240       }
6241       break;
6242 
6243     case AttributeList::AT_ObjCKindOf:
6244       // '__kindof' must be part of the decl-specifiers.
6245       switch (TAL) {
6246       case TAL_DeclSpec:
6247         break;
6248 
6249       case TAL_DeclChunk:
6250       case TAL_DeclName:
6251         state.getSema().Diag(attr.getLoc(),
6252                              diag::err_objc_kindof_wrong_position)
6253           << FixItHint::CreateRemoval(attr.getLoc())
6254           << FixItHint::CreateInsertion(
6255                state.getDeclarator().getDeclSpec().getLocStart(), "__kindof ");
6256         break;
6257       }
6258 
6259       // Apply it regardless.
6260       if (state.getSema().checkObjCKindOfType(type, attr.getLoc()))
6261         attr.setInvalid();
6262       attr.setUsedAsTypeAttr();
6263       break;
6264 
6265     case AttributeList::AT_NSReturnsRetained:
6266       if (!state.getSema().getLangOpts().ObjCAutoRefCount)
6267         break;
6268       // fallthrough into the function attrs
6269 
6270     FUNCTION_TYPE_ATTRS_CASELIST:
6271       attr.setUsedAsTypeAttr();
6272 
6273       // Never process function type attributes as part of the
6274       // declaration-specifiers.
6275       if (TAL == TAL_DeclSpec)
6276         distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
6277 
6278       // Otherwise, handle the possible delays.
6279       else if (!handleFunctionTypeAttr(state, attr, type))
6280         distributeFunctionTypeAttr(state, attr, type);
6281       break;
6282     }
6283   } while ((attrs = next));
6284 }
6285 
6286 /// \brief Ensure that the type of the given expression is complete.
6287 ///
6288 /// This routine checks whether the expression \p E has a complete type. If the
6289 /// expression refers to an instantiable construct, that instantiation is
6290 /// performed as needed to complete its type. Furthermore
6291 /// Sema::RequireCompleteType is called for the expression's type (or in the
6292 /// case of a reference type, the referred-to type).
6293 ///
6294 /// \param E The expression whose type is required to be complete.
6295 /// \param Diagnoser The object that will emit a diagnostic if the type is
6296 /// incomplete.
6297 ///
6298 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
6299 /// otherwise.
6300 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser){
6301   QualType T = E->getType();
6302 
6303   // Fast path the case where the type is already complete.
6304   if (!T->isIncompleteType())
6305     // FIXME: The definition might not be visible.
6306     return false;
6307 
6308   // Incomplete array types may be completed by the initializer attached to
6309   // their definitions. For static data members of class templates and for
6310   // variable templates, we need to instantiate the definition to get this
6311   // initializer and complete the type.
6312   if (T->isIncompleteArrayType()) {
6313     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
6314       if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
6315         if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
6316           SourceLocation PointOfInstantiation = E->getExprLoc();
6317 
6318           if (MemberSpecializationInfo *MSInfo =
6319                   Var->getMemberSpecializationInfo()) {
6320             // If we don't already have a point of instantiation, this is it.
6321             if (MSInfo->getPointOfInstantiation().isInvalid()) {
6322               MSInfo->setPointOfInstantiation(PointOfInstantiation);
6323 
6324               // This is a modification of an existing AST node. Notify
6325               // listeners.
6326               if (ASTMutationListener *L = getASTMutationListener())
6327                 L->StaticDataMemberInstantiated(Var);
6328             }
6329           } else {
6330             VarTemplateSpecializationDecl *VarSpec =
6331                 cast<VarTemplateSpecializationDecl>(Var);
6332             if (VarSpec->getPointOfInstantiation().isInvalid())
6333               VarSpec->setPointOfInstantiation(PointOfInstantiation);
6334           }
6335 
6336           InstantiateVariableDefinition(PointOfInstantiation, Var);
6337 
6338           // Update the type to the newly instantiated definition's type both
6339           // here and within the expression.
6340           if (VarDecl *Def = Var->getDefinition()) {
6341             DRE->setDecl(Def);
6342             T = Def->getType();
6343             DRE->setType(T);
6344             E->setType(T);
6345           }
6346 
6347           // We still go on to try to complete the type independently, as it
6348           // may also require instantiations or diagnostics if it remains
6349           // incomplete.
6350         }
6351       }
6352     }
6353   }
6354 
6355   // FIXME: Are there other cases which require instantiating something other
6356   // than the type to complete the type of an expression?
6357 
6358   // Look through reference types and complete the referred type.
6359   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6360     T = Ref->getPointeeType();
6361 
6362   return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
6363 }
6364 
6365 namespace {
6366   struct TypeDiagnoserDiag : Sema::TypeDiagnoser {
6367     unsigned DiagID;
6368 
6369     TypeDiagnoserDiag(unsigned DiagID)
6370       : Sema::TypeDiagnoser(DiagID == 0), DiagID(DiagID) {}
6371 
6372     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6373       if (Suppressed) return;
6374       S.Diag(Loc, DiagID) << T;
6375     }
6376   };
6377 }
6378 
6379 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
6380   TypeDiagnoserDiag Diagnoser(DiagID);
6381   return RequireCompleteExprType(E, Diagnoser);
6382 }
6383 
6384 /// @brief Ensure that the type T is a complete type.
6385 ///
6386 /// This routine checks whether the type @p T is complete in any
6387 /// context where a complete type is required. If @p T is a complete
6388 /// type, returns false. If @p T is a class template specialization,
6389 /// this routine then attempts to perform class template
6390 /// instantiation. If instantiation fails, or if @p T is incomplete
6391 /// and cannot be completed, issues the diagnostic @p diag (giving it
6392 /// the type @p T) and returns true.
6393 ///
6394 /// @param Loc  The location in the source that the incomplete type
6395 /// diagnostic should refer to.
6396 ///
6397 /// @param T  The type that this routine is examining for completeness.
6398 ///
6399 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
6400 /// @c false otherwise.
6401 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
6402                                TypeDiagnoser &Diagnoser) {
6403   if (RequireCompleteTypeImpl(Loc, T, Diagnoser))
6404     return true;
6405   if (const TagType *Tag = T->getAs<TagType>()) {
6406     if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
6407       Tag->getDecl()->setCompleteDefinitionRequired();
6408       Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
6409     }
6410   }
6411   return false;
6412 }
6413 
6414 /// \brief Determine whether there is any declaration of \p D that was ever a
6415 ///        definition (perhaps before module merging) and is currently visible.
6416 /// \param D The definition of the entity.
6417 /// \param Suggested Filled in with the declaration that should be made visible
6418 ///        in order to provide a definition of this entity.
6419 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
6420 ///        not defined. This only matters for enums with a fixed underlying
6421 ///        type, since in all other cases, a type is complete if and only if it
6422 ///        is defined.
6423 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
6424                                 bool OnlyNeedComplete) {
6425   // Easy case: if we don't have modules, all declarations are visible.
6426   if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
6427     return true;
6428 
6429   // If this definition was instantiated from a template, map back to the
6430   // pattern from which it was instantiated.
6431   if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
6432     // We're in the middle of defining it; this definition should be treated
6433     // as visible.
6434     return true;
6435   } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6436     if (auto *Pattern = RD->getTemplateInstantiationPattern())
6437       RD = Pattern;
6438     D = RD->getDefinition();
6439   } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
6440     while (auto *NewED = ED->getInstantiatedFromMemberEnum())
6441       ED = NewED;
6442     if (OnlyNeedComplete && ED->isFixed()) {
6443       // If the enum has a fixed underlying type, and we're only looking for a
6444       // complete type (not a definition), any visible declaration of it will
6445       // do.
6446       *Suggested = nullptr;
6447       for (auto *Redecl : ED->redecls()) {
6448         if (isVisible(Redecl))
6449           return true;
6450         if (Redecl->isThisDeclarationADefinition() ||
6451             (Redecl->isCanonicalDecl() && !*Suggested))
6452           *Suggested = Redecl;
6453       }
6454       return false;
6455     }
6456     D = ED->getDefinition();
6457   }
6458   assert(D && "missing definition for pattern of instantiated definition");
6459 
6460   *Suggested = D;
6461   if (isVisible(D))
6462     return true;
6463 
6464   // The external source may have additional definitions of this type that are
6465   // visible, so complete the redeclaration chain now and ask again.
6466   if (auto *Source = Context.getExternalSource()) {
6467     Source->CompleteRedeclChain(D);
6468     return isVisible(D);
6469   }
6470 
6471   return false;
6472 }
6473 
6474 /// Locks in the inheritance model for the given class and all of its bases.
6475 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
6476   RD = RD->getMostRecentDecl();
6477   if (!RD->hasAttr<MSInheritanceAttr>()) {
6478     MSInheritanceAttr::Spelling IM;
6479 
6480     switch (S.MSPointerToMemberRepresentationMethod) {
6481     case LangOptions::PPTMK_BestCase:
6482       IM = RD->calculateInheritanceModel();
6483       break;
6484     case LangOptions::PPTMK_FullGeneralitySingleInheritance:
6485       IM = MSInheritanceAttr::Keyword_single_inheritance;
6486       break;
6487     case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
6488       IM = MSInheritanceAttr::Keyword_multiple_inheritance;
6489       break;
6490     case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
6491       IM = MSInheritanceAttr::Keyword_unspecified_inheritance;
6492       break;
6493     }
6494 
6495     RD->addAttr(MSInheritanceAttr::CreateImplicit(
6496         S.getASTContext(), IM,
6497         /*BestCase=*/S.MSPointerToMemberRepresentationMethod ==
6498             LangOptions::PPTMK_BestCase,
6499         S.ImplicitMSInheritanceAttrLoc.isValid()
6500             ? S.ImplicitMSInheritanceAttrLoc
6501             : RD->getSourceRange()));
6502   }
6503 }
6504 
6505 /// \brief The implementation of RequireCompleteType
6506 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
6507                                    TypeDiagnoser &Diagnoser) {
6508   // FIXME: Add this assertion to make sure we always get instantiation points.
6509   //  assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
6510   // FIXME: Add this assertion to help us flush out problems with
6511   // checking for dependent types and type-dependent expressions.
6512   //
6513   //  assert(!T->isDependentType() &&
6514   //         "Can't ask whether a dependent type is complete");
6515 
6516   // We lock in the inheritance model once somebody has asked us to ensure
6517   // that a pointer-to-member type is complete.
6518   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6519     if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
6520       if (!MPTy->getClass()->isDependentType()) {
6521         RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), 0);
6522         assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
6523       }
6524     }
6525   }
6526 
6527   // If we have a complete type, we're done.
6528   NamedDecl *Def = nullptr;
6529   if (!T->isIncompleteType(&Def)) {
6530     // If we know about the definition but it is not visible, complain.
6531     NamedDecl *SuggestedDef = nullptr;
6532     if (!Diagnoser.Suppressed && Def &&
6533         !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true))
6534       diagnoseMissingImport(Loc, SuggestedDef, /*NeedDefinition*/true);
6535 
6536     return false;
6537   }
6538 
6539   const TagType *Tag = T->getAs<TagType>();
6540   const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>();
6541 
6542   // If there's an unimported definition of this type in a module (for
6543   // instance, because we forward declared it, then imported the definition),
6544   // import that definition now.
6545   //
6546   // FIXME: What about other cases where an import extends a redeclaration
6547   // chain for a declaration that can be accessed through a mechanism other
6548   // than name lookup (eg, referenced in a template, or a variable whose type
6549   // could be completed by the module)?
6550   if (Tag || IFace) {
6551     NamedDecl *D =
6552         Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl();
6553 
6554     // Avoid diagnosing invalid decls as incomplete.
6555     if (D->isInvalidDecl())
6556       return true;
6557 
6558     // Give the external AST source a chance to complete the type.
6559     if (auto *Source = Context.getExternalSource()) {
6560       if (Tag)
6561         Source->CompleteType(Tag->getDecl());
6562       else
6563         Source->CompleteType(IFace->getDecl());
6564 
6565       // If the external source completed the type, go through the motions
6566       // again to ensure we're allowed to use the completed type.
6567       if (!T->isIncompleteType())
6568         return RequireCompleteTypeImpl(Loc, T, Diagnoser);
6569     }
6570   }
6571 
6572   // If we have a class template specialization or a class member of a
6573   // class template specialization, or an array with known size of such,
6574   // try to instantiate it.
6575   QualType MaybeTemplate = T;
6576   while (const ConstantArrayType *Array
6577            = Context.getAsConstantArrayType(MaybeTemplate))
6578     MaybeTemplate = Array->getElementType();
6579   if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
6580     if (ClassTemplateSpecializationDecl *ClassTemplateSpec
6581           = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
6582       if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
6583         return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
6584                                                       TSK_ImplicitInstantiation,
6585                                             /*Complain=*/!Diagnoser.Suppressed);
6586     } else if (CXXRecordDecl *Rec
6587                  = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
6588       CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
6589       if (!Rec->isBeingDefined() && Pattern) {
6590         MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
6591         assert(MSI && "Missing member specialization information?");
6592         // This record was instantiated from a class within a template.
6593         if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
6594           return InstantiateClass(Loc, Rec, Pattern,
6595                                   getTemplateInstantiationArgs(Rec),
6596                                   TSK_ImplicitInstantiation,
6597                                   /*Complain=*/!Diagnoser.Suppressed);
6598       }
6599     }
6600   }
6601 
6602   if (Diagnoser.Suppressed)
6603     return true;
6604 
6605   // We have an incomplete type. Produce a diagnostic.
6606   if (Ident___float128 &&
6607       T == Context.getTypeDeclType(Context.getFloat128StubType())) {
6608     Diag(Loc, diag::err_typecheck_decl_incomplete_type___float128);
6609     return true;
6610   }
6611 
6612   Diagnoser.diagnose(*this, Loc, T);
6613 
6614   // If the type was a forward declaration of a class/struct/union
6615   // type, produce a note.
6616   if (Tag && !Tag->getDecl()->isInvalidDecl())
6617     Diag(Tag->getDecl()->getLocation(),
6618          Tag->isBeingDefined() ? diag::note_type_being_defined
6619                                : diag::note_forward_declaration)
6620       << QualType(Tag, 0);
6621 
6622   // If the Objective-C class was a forward declaration, produce a note.
6623   if (IFace && !IFace->getDecl()->isInvalidDecl())
6624     Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
6625 
6626   // If we have external information that we can use to suggest a fix,
6627   // produce a note.
6628   if (ExternalSource)
6629     ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
6630 
6631   return true;
6632 }
6633 
6634 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
6635                                unsigned DiagID) {
6636   TypeDiagnoserDiag Diagnoser(DiagID);
6637   return RequireCompleteType(Loc, T, Diagnoser);
6638 }
6639 
6640 /// \brief Get diagnostic %select index for tag kind for
6641 /// literal type diagnostic message.
6642 /// WARNING: Indexes apply to particular diagnostics only!
6643 ///
6644 /// \returns diagnostic %select index.
6645 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
6646   switch (Tag) {
6647   case TTK_Struct: return 0;
6648   case TTK_Interface: return 1;
6649   case TTK_Class:  return 2;
6650   default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
6651   }
6652 }
6653 
6654 /// @brief Ensure that the type T is a literal type.
6655 ///
6656 /// This routine checks whether the type @p T is a literal type. If @p T is an
6657 /// incomplete type, an attempt is made to complete it. If @p T is a literal
6658 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
6659 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
6660 /// it the type @p T), along with notes explaining why the type is not a
6661 /// literal type, and returns true.
6662 ///
6663 /// @param Loc  The location in the source that the non-literal type
6664 /// diagnostic should refer to.
6665 ///
6666 /// @param T  The type that this routine is examining for literalness.
6667 ///
6668 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
6669 ///
6670 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
6671 /// @c false otherwise.
6672 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
6673                               TypeDiagnoser &Diagnoser) {
6674   assert(!T->isDependentType() && "type should not be dependent");
6675 
6676   QualType ElemType = Context.getBaseElementType(T);
6677   RequireCompleteType(Loc, ElemType, 0);
6678 
6679   if (T->isLiteralType(Context))
6680     return false;
6681 
6682   if (Diagnoser.Suppressed)
6683     return true;
6684 
6685   Diagnoser.diagnose(*this, Loc, T);
6686 
6687   if (T->isVariableArrayType())
6688     return true;
6689 
6690   const RecordType *RT = ElemType->getAs<RecordType>();
6691   if (!RT)
6692     return true;
6693 
6694   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
6695 
6696   // A partially-defined class type can't be a literal type, because a literal
6697   // class type must have a trivial destructor (which can't be checked until
6698   // the class definition is complete).
6699   if (!RD->isCompleteDefinition()) {
6700     RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T);
6701     return true;
6702   }
6703 
6704   // If the class has virtual base classes, then it's not an aggregate, and
6705   // cannot have any constexpr constructors or a trivial default constructor,
6706   // so is non-literal. This is better to diagnose than the resulting absence
6707   // of constexpr constructors.
6708   if (RD->getNumVBases()) {
6709     Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
6710       << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
6711     for (const auto &I : RD->vbases())
6712       Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here)
6713           << I.getSourceRange();
6714   } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
6715              !RD->hasTrivialDefaultConstructor()) {
6716     Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
6717   } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
6718     for (const auto &I : RD->bases()) {
6719       if (!I.getType()->isLiteralType(Context)) {
6720         Diag(I.getLocStart(),
6721              diag::note_non_literal_base_class)
6722           << RD << I.getType() << I.getSourceRange();
6723         return true;
6724       }
6725     }
6726     for (const auto *I : RD->fields()) {
6727       if (!I->getType()->isLiteralType(Context) ||
6728           I->getType().isVolatileQualified()) {
6729         Diag(I->getLocation(), diag::note_non_literal_field)
6730           << RD << I << I->getType()
6731           << I->getType().isVolatileQualified();
6732         return true;
6733       }
6734     }
6735   } else if (!RD->hasTrivialDestructor()) {
6736     // All fields and bases are of literal types, so have trivial destructors.
6737     // If this class's destructor is non-trivial it must be user-declared.
6738     CXXDestructorDecl *Dtor = RD->getDestructor();
6739     assert(Dtor && "class has literal fields and bases but no dtor?");
6740     if (!Dtor)
6741       return true;
6742 
6743     Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
6744          diag::note_non_literal_user_provided_dtor :
6745          diag::note_non_literal_nontrivial_dtor) << RD;
6746     if (!Dtor->isUserProvided())
6747       SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true);
6748   }
6749 
6750   return true;
6751 }
6752 
6753 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
6754   TypeDiagnoserDiag Diagnoser(DiagID);
6755   return RequireLiteralType(Loc, T, Diagnoser);
6756 }
6757 
6758 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
6759 /// and qualified by the nested-name-specifier contained in SS.
6760 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
6761                                  const CXXScopeSpec &SS, QualType T) {
6762   if (T.isNull())
6763     return T;
6764   NestedNameSpecifier *NNS;
6765   if (SS.isValid())
6766     NNS = SS.getScopeRep();
6767   else {
6768     if (Keyword == ETK_None)
6769       return T;
6770     NNS = nullptr;
6771   }
6772   return Context.getElaboratedType(Keyword, NNS, T);
6773 }
6774 
6775 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
6776   ExprResult ER = CheckPlaceholderExpr(E);
6777   if (ER.isInvalid()) return QualType();
6778   E = ER.get();
6779 
6780   if (!E->isTypeDependent()) {
6781     QualType T = E->getType();
6782     if (const TagType *TT = T->getAs<TagType>())
6783       DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
6784   }
6785   return Context.getTypeOfExprType(E);
6786 }
6787 
6788 /// getDecltypeForExpr - Given an expr, will return the decltype for
6789 /// that expression, according to the rules in C++11
6790 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
6791 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
6792   if (E->isTypeDependent())
6793     return S.Context.DependentTy;
6794 
6795   // C++11 [dcl.type.simple]p4:
6796   //   The type denoted by decltype(e) is defined as follows:
6797   //
6798   //     - if e is an unparenthesized id-expression or an unparenthesized class
6799   //       member access (5.2.5), decltype(e) is the type of the entity named
6800   //       by e. If there is no such entity, or if e names a set of overloaded
6801   //       functions, the program is ill-formed;
6802   //
6803   // We apply the same rules for Objective-C ivar and property references.
6804   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6805     if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
6806       return VD->getType();
6807   } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6808     if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
6809       return FD->getType();
6810   } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
6811     return IR->getDecl()->getType();
6812   } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
6813     if (PR->isExplicitProperty())
6814       return PR->getExplicitProperty()->getType();
6815   } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) {
6816     return PE->getType();
6817   }
6818 
6819   // C++11 [expr.lambda.prim]p18:
6820   //   Every occurrence of decltype((x)) where x is a possibly
6821   //   parenthesized id-expression that names an entity of automatic
6822   //   storage duration is treated as if x were transformed into an
6823   //   access to a corresponding data member of the closure type that
6824   //   would have been declared if x were an odr-use of the denoted
6825   //   entity.
6826   using namespace sema;
6827   if (S.getCurLambda()) {
6828     if (isa<ParenExpr>(E)) {
6829       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
6830         if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
6831           QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
6832           if (!T.isNull())
6833             return S.Context.getLValueReferenceType(T);
6834         }
6835       }
6836     }
6837   }
6838 
6839 
6840   // C++11 [dcl.type.simple]p4:
6841   //   [...]
6842   QualType T = E->getType();
6843   switch (E->getValueKind()) {
6844   //     - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6845   //       type of e;
6846   case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
6847   //     - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6848   //       type of e;
6849   case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
6850   //  - otherwise, decltype(e) is the type of e.
6851   case VK_RValue: break;
6852   }
6853 
6854   return T;
6855 }
6856 
6857 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc,
6858                                  bool AsUnevaluated) {
6859   ExprResult ER = CheckPlaceholderExpr(E);
6860   if (ER.isInvalid()) return QualType();
6861   E = ER.get();
6862 
6863   if (AsUnevaluated && ActiveTemplateInstantiations.empty() &&
6864       E->HasSideEffects(Context, false)) {
6865     // The expression operand for decltype is in an unevaluated expression
6866     // context, so side effects could result in unintended consequences.
6867     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
6868   }
6869 
6870   return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
6871 }
6872 
6873 QualType Sema::BuildUnaryTransformType(QualType BaseType,
6874                                        UnaryTransformType::UTTKind UKind,
6875                                        SourceLocation Loc) {
6876   switch (UKind) {
6877   case UnaryTransformType::EnumUnderlyingType:
6878     if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
6879       Diag(Loc, diag::err_only_enums_have_underlying_types);
6880       return QualType();
6881     } else {
6882       QualType Underlying = BaseType;
6883       if (!BaseType->isDependentType()) {
6884         // The enum could be incomplete if we're parsing its definition or
6885         // recovering from an error.
6886         NamedDecl *FwdDecl = nullptr;
6887         if (BaseType->isIncompleteType(&FwdDecl)) {
6888           Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
6889           Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
6890           return QualType();
6891         }
6892 
6893         EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
6894         assert(ED && "EnumType has no EnumDecl");
6895 
6896         DiagnoseUseOfDecl(ED, Loc);
6897 
6898         Underlying = ED->getIntegerType();
6899         assert(!Underlying.isNull());
6900       }
6901       return Context.getUnaryTransformType(BaseType, Underlying,
6902                                         UnaryTransformType::EnumUnderlyingType);
6903     }
6904   }
6905   llvm_unreachable("unknown unary transform type");
6906 }
6907 
6908 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
6909   if (!T->isDependentType()) {
6910     // FIXME: It isn't entirely clear whether incomplete atomic types
6911     // are allowed or not; for simplicity, ban them for the moment.
6912     if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
6913       return QualType();
6914 
6915     int DisallowedKind = -1;
6916     if (T->isArrayType())
6917       DisallowedKind = 1;
6918     else if (T->isFunctionType())
6919       DisallowedKind = 2;
6920     else if (T->isReferenceType())
6921       DisallowedKind = 3;
6922     else if (T->isAtomicType())
6923       DisallowedKind = 4;
6924     else if (T.hasQualifiers())
6925       DisallowedKind = 5;
6926     else if (!T.isTriviallyCopyableType(Context))
6927       // Some other non-trivially-copyable type (probably a C++ class)
6928       DisallowedKind = 6;
6929 
6930     if (DisallowedKind != -1) {
6931       Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
6932       return QualType();
6933     }
6934 
6935     // FIXME: Do we need any handling for ARC here?
6936   }
6937 
6938   // Build the pointer type.
6939   return Context.getAtomicType(T);
6940 }
6941