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().ObjC1) {
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   IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5096   Qualifiers::ObjCLifetime lifetime;
5097   if (II->isStr("none"))
5098     lifetime = Qualifiers::OCL_ExplicitNone;
5099   else if (II->isStr("strong"))
5100     lifetime = Qualifiers::OCL_Strong;
5101   else if (II->isStr("weak"))
5102     lifetime = Qualifiers::OCL_Weak;
5103   else if (II->isStr("autoreleasing"))
5104     lifetime = Qualifiers::OCL_Autoreleasing;
5105   else {
5106     S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
5107       << attr.getName() << II;
5108     attr.setInvalid();
5109     return true;
5110   }
5111 
5112   // Just ignore lifetime attributes other than __weak and __unsafe_unretained
5113   // outside of ARC mode.
5114   if (!S.getLangOpts().ObjCAutoRefCount &&
5115       lifetime != Qualifiers::OCL_Weak &&
5116       lifetime != Qualifiers::OCL_ExplicitNone) {
5117     return true;
5118   }
5119 
5120   SplitQualType underlyingType = type.split();
5121 
5122   // Check for redundant/conflicting ownership qualifiers.
5123   if (Qualifiers::ObjCLifetime previousLifetime
5124         = type.getQualifiers().getObjCLifetime()) {
5125     // If it's written directly, that's an error.
5126     if (hasDirectOwnershipQualifier(type)) {
5127       S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
5128         << type;
5129       return true;
5130     }
5131 
5132     // Otherwise, if the qualifiers actually conflict, pull sugar off
5133     // until we reach a type that is directly qualified.
5134     if (previousLifetime != lifetime) {
5135       // This should always terminate: the canonical type is
5136       // qualified, so some bit of sugar must be hiding it.
5137       while (!underlyingType.Quals.hasObjCLifetime()) {
5138         underlyingType = underlyingType.getSingleStepDesugaredType();
5139       }
5140       underlyingType.Quals.removeObjCLifetime();
5141     }
5142   }
5143 
5144   underlyingType.Quals.addObjCLifetime(lifetime);
5145 
5146   if (NonObjCPointer) {
5147     StringRef name = attr.getName()->getName();
5148     switch (lifetime) {
5149     case Qualifiers::OCL_None:
5150     case Qualifiers::OCL_ExplicitNone:
5151       break;
5152     case Qualifiers::OCL_Strong: name = "__strong"; break;
5153     case Qualifiers::OCL_Weak: name = "__weak"; break;
5154     case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
5155     }
5156     S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
5157       << TDS_ObjCObjOrBlock << type;
5158   }
5159 
5160   QualType origType = type;
5161   if (!NonObjCPointer)
5162     type = S.Context.getQualifiedType(underlyingType);
5163 
5164   // If we have a valid source location for the attribute, use an
5165   // AttributedType instead.
5166   if (AttrLoc.isValid())
5167     type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
5168                                        origType, type);
5169 
5170   // Sometimes, __weak isn't allowed.
5171   if (lifetime == Qualifiers::OCL_Weak &&
5172       !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
5173 
5174     // Use a specialized diagnostic if the runtime just doesn't support them.
5175     unsigned diagnostic =
5176       (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
5177                                        : diag::err_arc_weak_no_runtime);
5178 
5179     // In any case, delay the diagnostic until we know what we're parsing.
5180     if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
5181       S.DelayedDiagnostics.add(
5182           sema::DelayedDiagnostic::makeForbiddenType(
5183               S.getSourceManager().getExpansionLoc(AttrLoc),
5184               diagnostic, type, /*ignored*/ 0));
5185     } else {
5186       S.Diag(AttrLoc, diagnostic);
5187     }
5188 
5189     attr.setInvalid();
5190     return true;
5191   }
5192 
5193   // If we accepted __weak, we might still need to warn about it.
5194   if (lifetime == Qualifiers::OCL_Weak &&
5195       !S.getLangOpts().ObjCAutoRefCount &&
5196       S.getLangOpts().ObjCWeak) {
5197     S.Diag(AttrLoc, diag::warn_objc_weak_compat);
5198   }
5199 
5200   // Forbid __weak for class objects marked as
5201   // objc_arc_weak_reference_unavailable
5202   if (lifetime == Qualifiers::OCL_Weak) {
5203     if (const ObjCObjectPointerType *ObjT =
5204           type->getAs<ObjCObjectPointerType>()) {
5205       if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
5206         if (Class->isArcWeakrefUnavailable()) {
5207           S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
5208           S.Diag(ObjT->getInterfaceDecl()->getLocation(),
5209                   diag::note_class_declared);
5210         }
5211       }
5212     }
5213   }
5214 
5215   return true;
5216 }
5217 
5218 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
5219 /// attribute on the specified type.  Returns true to indicate that
5220 /// the attribute was handled, false to indicate that the type does
5221 /// not permit the attribute.
5222 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
5223                                  AttributeList &attr,
5224                                  QualType &type) {
5225   Sema &S = state.getSema();
5226 
5227   // Delay if this isn't some kind of pointer.
5228   if (!type->isPointerType() &&
5229       !type->isObjCObjectPointerType() &&
5230       !type->isBlockPointerType())
5231     return false;
5232 
5233   if (type.getObjCGCAttr() != Qualifiers::GCNone) {
5234     S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
5235     attr.setInvalid();
5236     return true;
5237   }
5238 
5239   // Check the attribute arguments.
5240   if (!attr.isArgIdent(0)) {
5241     S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
5242       << attr.getName() << AANT_ArgumentString;
5243     attr.setInvalid();
5244     return true;
5245   }
5246   Qualifiers::GC GCAttr;
5247   if (attr.getNumArgs() > 1) {
5248     S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5249       << attr.getName() << 1;
5250     attr.setInvalid();
5251     return true;
5252   }
5253 
5254   IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5255   if (II->isStr("weak"))
5256     GCAttr = Qualifiers::Weak;
5257   else if (II->isStr("strong"))
5258     GCAttr = Qualifiers::Strong;
5259   else {
5260     S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
5261       << attr.getName() << II;
5262     attr.setInvalid();
5263     return true;
5264   }
5265 
5266   QualType origType = type;
5267   type = S.Context.getObjCGCQualType(origType, GCAttr);
5268 
5269   // Make an attributed type to preserve the source information.
5270   if (attr.getLoc().isValid())
5271     type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
5272                                        origType, type);
5273 
5274   return true;
5275 }
5276 
5277 namespace {
5278   /// A helper class to unwrap a type down to a function for the
5279   /// purposes of applying attributes there.
5280   ///
5281   /// Use:
5282   ///   FunctionTypeUnwrapper unwrapped(SemaRef, T);
5283   ///   if (unwrapped.isFunctionType()) {
5284   ///     const FunctionType *fn = unwrapped.get();
5285   ///     // change fn somehow
5286   ///     T = unwrapped.wrap(fn);
5287   ///   }
5288   struct FunctionTypeUnwrapper {
5289     enum WrapKind {
5290       Desugar,
5291       Parens,
5292       Pointer,
5293       BlockPointer,
5294       Reference,
5295       MemberPointer
5296     };
5297 
5298     QualType Original;
5299     const FunctionType *Fn;
5300     SmallVector<unsigned char /*WrapKind*/, 8> Stack;
5301 
5302     FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
5303       while (true) {
5304         const Type *Ty = T.getTypePtr();
5305         if (isa<FunctionType>(Ty)) {
5306           Fn = cast<FunctionType>(Ty);
5307           return;
5308         } else if (isa<ParenType>(Ty)) {
5309           T = cast<ParenType>(Ty)->getInnerType();
5310           Stack.push_back(Parens);
5311         } else if (isa<PointerType>(Ty)) {
5312           T = cast<PointerType>(Ty)->getPointeeType();
5313           Stack.push_back(Pointer);
5314         } else if (isa<BlockPointerType>(Ty)) {
5315           T = cast<BlockPointerType>(Ty)->getPointeeType();
5316           Stack.push_back(BlockPointer);
5317         } else if (isa<MemberPointerType>(Ty)) {
5318           T = cast<MemberPointerType>(Ty)->getPointeeType();
5319           Stack.push_back(MemberPointer);
5320         } else if (isa<ReferenceType>(Ty)) {
5321           T = cast<ReferenceType>(Ty)->getPointeeType();
5322           Stack.push_back(Reference);
5323         } else {
5324           const Type *DTy = Ty->getUnqualifiedDesugaredType();
5325           if (Ty == DTy) {
5326             Fn = nullptr;
5327             return;
5328           }
5329 
5330           T = QualType(DTy, 0);
5331           Stack.push_back(Desugar);
5332         }
5333       }
5334     }
5335 
5336     bool isFunctionType() const { return (Fn != nullptr); }
5337     const FunctionType *get() const { return Fn; }
5338 
5339     QualType wrap(Sema &S, const FunctionType *New) {
5340       // If T wasn't modified from the unwrapped type, do nothing.
5341       if (New == get()) return Original;
5342 
5343       Fn = New;
5344       return wrap(S.Context, Original, 0);
5345     }
5346 
5347   private:
5348     QualType wrap(ASTContext &C, QualType Old, unsigned I) {
5349       if (I == Stack.size())
5350         return C.getQualifiedType(Fn, Old.getQualifiers());
5351 
5352       // Build up the inner type, applying the qualifiers from the old
5353       // type to the new type.
5354       SplitQualType SplitOld = Old.split();
5355 
5356       // As a special case, tail-recurse if there are no qualifiers.
5357       if (SplitOld.Quals.empty())
5358         return wrap(C, SplitOld.Ty, I);
5359       return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
5360     }
5361 
5362     QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
5363       if (I == Stack.size()) return QualType(Fn, 0);
5364 
5365       switch (static_cast<WrapKind>(Stack[I++])) {
5366       case Desugar:
5367         // This is the point at which we potentially lose source
5368         // information.
5369         return wrap(C, Old->getUnqualifiedDesugaredType(), I);
5370 
5371       case Parens: {
5372         QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
5373         return C.getParenType(New);
5374       }
5375 
5376       case Pointer: {
5377         QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
5378         return C.getPointerType(New);
5379       }
5380 
5381       case BlockPointer: {
5382         QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
5383         return C.getBlockPointerType(New);
5384       }
5385 
5386       case MemberPointer: {
5387         const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
5388         QualType New = wrap(C, OldMPT->getPointeeType(), I);
5389         return C.getMemberPointerType(New, OldMPT->getClass());
5390       }
5391 
5392       case Reference: {
5393         const ReferenceType *OldRef = cast<ReferenceType>(Old);
5394         QualType New = wrap(C, OldRef->getPointeeType(), I);
5395         if (isa<LValueReferenceType>(OldRef))
5396           return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
5397         else
5398           return C.getRValueReferenceType(New);
5399       }
5400       }
5401 
5402       llvm_unreachable("unknown wrapping kind");
5403     }
5404   };
5405 }
5406 
5407 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
5408                                              AttributeList &Attr,
5409                                              QualType &Type) {
5410   Sema &S = State.getSema();
5411 
5412   AttributeList::Kind Kind = Attr.getKind();
5413   QualType Desugared = Type;
5414   const AttributedType *AT = dyn_cast<AttributedType>(Type);
5415   while (AT) {
5416     AttributedType::Kind CurAttrKind = AT->getAttrKind();
5417 
5418     // You cannot specify duplicate type attributes, so if the attribute has
5419     // already been applied, flag it.
5420     if (getAttrListKind(CurAttrKind) == Kind) {
5421       S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact)
5422         << Attr.getName();
5423       return true;
5424     }
5425 
5426     // You cannot have both __sptr and __uptr on the same type, nor can you
5427     // have __ptr32 and __ptr64.
5428     if ((CurAttrKind == AttributedType::attr_ptr32 &&
5429          Kind == AttributeList::AT_Ptr64) ||
5430         (CurAttrKind == AttributedType::attr_ptr64 &&
5431          Kind == AttributeList::AT_Ptr32)) {
5432       S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
5433         << "'__ptr32'" << "'__ptr64'";
5434       return true;
5435     } else if ((CurAttrKind == AttributedType::attr_sptr &&
5436                 Kind == AttributeList::AT_UPtr) ||
5437                (CurAttrKind == AttributedType::attr_uptr &&
5438                 Kind == AttributeList::AT_SPtr)) {
5439       S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
5440         << "'__sptr'" << "'__uptr'";
5441       return true;
5442     }
5443 
5444     Desugared = AT->getEquivalentType();
5445     AT = dyn_cast<AttributedType>(Desugared);
5446   }
5447 
5448   // Pointer type qualifiers can only operate on pointer types, but not
5449   // pointer-to-member types.
5450   if (!isa<PointerType>(Desugared)) {
5451     S.Diag(Attr.getLoc(), Type->isMemberPointerType() ?
5452                           diag::err_attribute_no_member_pointers :
5453                           diag::err_attribute_pointers_only) << Attr.getName();
5454     return true;
5455   }
5456 
5457   AttributedType::Kind TAK;
5458   switch (Kind) {
5459   default: llvm_unreachable("Unknown attribute kind");
5460   case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break;
5461   case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break;
5462   case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break;
5463   case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break;
5464   }
5465 
5466   Type = S.Context.getAttributedType(TAK, Type, Type);
5467   return false;
5468 }
5469 
5470 bool Sema::checkNullabilityTypeSpecifier(QualType &type,
5471                                          NullabilityKind nullability,
5472                                          SourceLocation nullabilityLoc,
5473                                          bool isContextSensitive) {
5474   // We saw a nullability type specifier. If this is the first one for
5475   // this file, note that.
5476   FileID file = getNullabilityCompletenessCheckFileID(*this, nullabilityLoc);
5477   if (!file.isInvalid()) {
5478     FileNullability &fileNullability = NullabilityMap[file];
5479     if (!fileNullability.SawTypeNullability) {
5480       // If we have already seen a pointer declarator without a nullability
5481       // annotation, complain about it.
5482       if (fileNullability.PointerLoc.isValid()) {
5483         Diag(fileNullability.PointerLoc, diag::warn_nullability_missing)
5484           << static_cast<unsigned>(fileNullability.PointerKind);
5485       }
5486 
5487       fileNullability.SawTypeNullability = true;
5488     }
5489   }
5490 
5491   // Check for existing nullability attributes on the type.
5492   QualType desugared = type;
5493   while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
5494     // Check whether there is already a null
5495     if (auto existingNullability = attributed->getImmediateNullability()) {
5496       // Duplicated nullability.
5497       if (nullability == *existingNullability) {
5498         Diag(nullabilityLoc, diag::warn_nullability_duplicate)
5499           << DiagNullabilityKind(nullability, isContextSensitive)
5500           << FixItHint::CreateRemoval(nullabilityLoc);
5501 
5502         break;
5503       }
5504 
5505       // Conflicting nullability.
5506       Diag(nullabilityLoc, diag::err_nullability_conflicting)
5507         << DiagNullabilityKind(nullability, isContextSensitive)
5508         << DiagNullabilityKind(*existingNullability, false);
5509       return true;
5510     }
5511 
5512     desugared = attributed->getModifiedType();
5513   }
5514 
5515   // If there is already a different nullability specifier, complain.
5516   // This (unlike the code above) looks through typedefs that might
5517   // have nullability specifiers on them, which means we cannot
5518   // provide a useful Fix-It.
5519   if (auto existingNullability = desugared->getNullability(Context)) {
5520     if (nullability != *existingNullability) {
5521       Diag(nullabilityLoc, diag::err_nullability_conflicting)
5522         << DiagNullabilityKind(nullability, isContextSensitive)
5523         << DiagNullabilityKind(*existingNullability, false);
5524 
5525       // Try to find the typedef with the existing nullability specifier.
5526       if (auto typedefType = desugared->getAs<TypedefType>()) {
5527         TypedefNameDecl *typedefDecl = typedefType->getDecl();
5528         QualType underlyingType = typedefDecl->getUnderlyingType();
5529         if (auto typedefNullability
5530               = AttributedType::stripOuterNullability(underlyingType)) {
5531           if (*typedefNullability == *existingNullability) {
5532             Diag(typedefDecl->getLocation(), diag::note_nullability_here)
5533               << DiagNullabilityKind(*existingNullability, false);
5534           }
5535         }
5536       }
5537 
5538       return true;
5539     }
5540   }
5541 
5542   // If this definitely isn't a pointer type, reject the specifier.
5543   if (!desugared->canHaveNullability()) {
5544     Diag(nullabilityLoc, diag::err_nullability_nonpointer)
5545       << DiagNullabilityKind(nullability, isContextSensitive) << type;
5546     return true;
5547   }
5548 
5549   // For the context-sensitive keywords/Objective-C property
5550   // attributes, require that the type be a single-level pointer.
5551   if (isContextSensitive) {
5552     // Make sure that the pointee isn't itself a pointer type.
5553     QualType pointeeType = desugared->getPointeeType();
5554     if (pointeeType->isAnyPointerType() ||
5555         pointeeType->isObjCObjectPointerType() ||
5556         pointeeType->isMemberPointerType()) {
5557       Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
5558         << DiagNullabilityKind(nullability, true)
5559         << type;
5560       Diag(nullabilityLoc, diag::note_nullability_type_specifier)
5561         << DiagNullabilityKind(nullability, false)
5562         << type
5563         << FixItHint::CreateReplacement(nullabilityLoc,
5564                                         getNullabilitySpelling(nullability));
5565       return true;
5566     }
5567   }
5568 
5569   // Form the attributed type.
5570   type = Context.getAttributedType(
5571            AttributedType::getNullabilityAttrKind(nullability), type, type);
5572   return false;
5573 }
5574 
5575 bool Sema::checkObjCKindOfType(QualType &type, SourceLocation loc) {
5576   // Find out if it's an Objective-C object or object pointer type;
5577   const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
5578   const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
5579                                           : type->getAs<ObjCObjectType>();
5580 
5581   // If not, we can't apply __kindof.
5582   if (!objType) {
5583     // FIXME: Handle dependent types that aren't yet object types.
5584     Diag(loc, diag::err_objc_kindof_nonobject)
5585       << type;
5586     return true;
5587   }
5588 
5589   // Rebuild the "equivalent" type, which pushes __kindof down into
5590   // the object type.
5591   QualType equivType = Context.getObjCObjectType(objType->getBaseType(),
5592                                                  objType->getTypeArgsAsWritten(),
5593                                                  objType->getProtocols(),
5594                                                  /*isKindOf=*/true);
5595 
5596   // If we started with an object pointer type, rebuild it.
5597   if (ptrType) {
5598     equivType = Context.getObjCObjectPointerType(equivType);
5599     if (auto nullability = type->getNullability(Context)) {
5600       auto attrKind = AttributedType::getNullabilityAttrKind(*nullability);
5601       equivType = Context.getAttributedType(attrKind, equivType, equivType);
5602     }
5603   }
5604 
5605   // Build the attributed type to record where __kindof occurred.
5606   type = Context.getAttributedType(AttributedType::attr_objc_kindof,
5607                                    type,
5608                                    equivType);
5609 
5610   return false;
5611 }
5612 
5613 /// Map a nullability attribute kind to a nullability kind.
5614 static NullabilityKind mapNullabilityAttrKind(AttributeList::Kind kind) {
5615   switch (kind) {
5616   case AttributeList::AT_TypeNonNull:
5617     return NullabilityKind::NonNull;
5618 
5619   case AttributeList::AT_TypeNullable:
5620     return NullabilityKind::Nullable;
5621 
5622   case AttributeList::AT_TypeNullUnspecified:
5623     return NullabilityKind::Unspecified;
5624 
5625   default:
5626     llvm_unreachable("not a nullability attribute kind");
5627   }
5628 }
5629 
5630 /// Distribute a nullability type attribute that cannot be applied to
5631 /// the type specifier to a pointer, block pointer, or member pointer
5632 /// declarator, complaining if necessary.
5633 ///
5634 /// \returns true if the nullability annotation was distributed, false
5635 /// otherwise.
5636 static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
5637                                           QualType type,
5638                                           AttributeList &attr) {
5639   Declarator &declarator = state.getDeclarator();
5640 
5641   /// Attempt to move the attribute to the specified chunk.
5642   auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
5643     // If there is already a nullability attribute there, don't add
5644     // one.
5645     if (hasNullabilityAttr(chunk.getAttrListRef()))
5646       return false;
5647 
5648     // Complain about the nullability qualifier being in the wrong
5649     // place.
5650     enum {
5651       PK_Pointer,
5652       PK_BlockPointer,
5653       PK_MemberPointer,
5654       PK_FunctionPointer,
5655       PK_MemberFunctionPointer,
5656     } pointerKind
5657       = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
5658                                                              : PK_Pointer)
5659         : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
5660         : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
5661 
5662     auto diag = state.getSema().Diag(attr.getLoc(),
5663                                      diag::warn_nullability_declspec)
5664       << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
5665                              attr.isContextSensitiveKeywordAttribute())
5666       << type
5667       << static_cast<unsigned>(pointerKind);
5668 
5669     // FIXME: MemberPointer chunks don't carry the location of the *.
5670     if (chunk.Kind != DeclaratorChunk::MemberPointer) {
5671       diag << FixItHint::CreateRemoval(attr.getLoc())
5672            << FixItHint::CreateInsertion(
5673                 state.getSema().getPreprocessor()
5674                   .getLocForEndOfToken(chunk.Loc),
5675                 " " + attr.getName()->getName().str() + " ");
5676     }
5677 
5678     moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
5679                            chunk.getAttrListRef());
5680     return true;
5681   };
5682 
5683   // Move it to the outermost pointer, member pointer, or block
5684   // pointer declarator.
5685   for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
5686     DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
5687     switch (chunk.Kind) {
5688     case DeclaratorChunk::Pointer:
5689     case DeclaratorChunk::BlockPointer:
5690     case DeclaratorChunk::MemberPointer:
5691       return moveToChunk(chunk, false);
5692 
5693     case DeclaratorChunk::Paren:
5694     case DeclaratorChunk::Array:
5695       continue;
5696 
5697     case DeclaratorChunk::Function:
5698       // Try to move past the return type to a function/block/member
5699       // function pointer.
5700       if (DeclaratorChunk *dest = maybeMovePastReturnType(
5701                                     declarator, i,
5702                                     /*onlyBlockPointers=*/false)) {
5703         return moveToChunk(*dest, true);
5704       }
5705 
5706       return false;
5707 
5708     // Don't walk through these.
5709     case DeclaratorChunk::Reference:
5710       return false;
5711     }
5712   }
5713 
5714   return false;
5715 }
5716 
5717 static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) {
5718   assert(!Attr.isInvalid());
5719   switch (Attr.getKind()) {
5720   default:
5721     llvm_unreachable("not a calling convention attribute");
5722   case AttributeList::AT_CDecl:
5723     return AttributedType::attr_cdecl;
5724   case AttributeList::AT_FastCall:
5725     return AttributedType::attr_fastcall;
5726   case AttributeList::AT_StdCall:
5727     return AttributedType::attr_stdcall;
5728   case AttributeList::AT_ThisCall:
5729     return AttributedType::attr_thiscall;
5730   case AttributeList::AT_Pascal:
5731     return AttributedType::attr_pascal;
5732   case AttributeList::AT_VectorCall:
5733     return AttributedType::attr_vectorcall;
5734   case AttributeList::AT_Pcs: {
5735     // The attribute may have had a fixit applied where we treated an
5736     // identifier as a string literal.  The contents of the string are valid,
5737     // but the form may not be.
5738     StringRef Str;
5739     if (Attr.isArgExpr(0))
5740       Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
5741     else
5742       Str = Attr.getArgAsIdent(0)->Ident->getName();
5743     return llvm::StringSwitch<AttributedType::Kind>(Str)
5744         .Case("aapcs", AttributedType::attr_pcs)
5745         .Case("aapcs-vfp", AttributedType::attr_pcs_vfp);
5746   }
5747   case AttributeList::AT_IntelOclBicc:
5748     return AttributedType::attr_inteloclbicc;
5749   case AttributeList::AT_MSABI:
5750     return AttributedType::attr_ms_abi;
5751   case AttributeList::AT_SysVABI:
5752     return AttributedType::attr_sysv_abi;
5753   }
5754   llvm_unreachable("unexpected attribute kind!");
5755 }
5756 
5757 /// Process an individual function attribute.  Returns true to
5758 /// indicate that the attribute was handled, false if it wasn't.
5759 static bool handleFunctionTypeAttr(TypeProcessingState &state,
5760                                    AttributeList &attr,
5761                                    QualType &type) {
5762   Sema &S = state.getSema();
5763 
5764   FunctionTypeUnwrapper unwrapped(S, type);
5765 
5766   if (attr.getKind() == AttributeList::AT_NoReturn) {
5767     if (S.CheckNoReturnAttr(attr))
5768       return true;
5769 
5770     // Delay if this is not a function type.
5771     if (!unwrapped.isFunctionType())
5772       return false;
5773 
5774     // Otherwise we can process right away.
5775     FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
5776     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5777     return true;
5778   }
5779 
5780   // ns_returns_retained is not always a type attribute, but if we got
5781   // here, we're treating it as one right now.
5782   if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
5783     assert(S.getLangOpts().ObjCAutoRefCount &&
5784            "ns_returns_retained treated as type attribute in non-ARC");
5785     if (attr.getNumArgs()) return true;
5786 
5787     // Delay if this is not a function type.
5788     if (!unwrapped.isFunctionType())
5789       return false;
5790 
5791     FunctionType::ExtInfo EI
5792       = unwrapped.get()->getExtInfo().withProducesResult(true);
5793     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5794     return true;
5795   }
5796 
5797   if (attr.getKind() == AttributeList::AT_Regparm) {
5798     unsigned value;
5799     if (S.CheckRegparmAttr(attr, value))
5800       return true;
5801 
5802     // Delay if this is not a function type.
5803     if (!unwrapped.isFunctionType())
5804       return false;
5805 
5806     // Diagnose regparm with fastcall.
5807     const FunctionType *fn = unwrapped.get();
5808     CallingConv CC = fn->getCallConv();
5809     if (CC == CC_X86FastCall) {
5810       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
5811         << FunctionType::getNameForCallConv(CC)
5812         << "regparm";
5813       attr.setInvalid();
5814       return true;
5815     }
5816 
5817     FunctionType::ExtInfo EI =
5818       unwrapped.get()->getExtInfo().withRegParm(value);
5819     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5820     return true;
5821   }
5822 
5823   // Delay if the type didn't work out to a function.
5824   if (!unwrapped.isFunctionType()) return false;
5825 
5826   // Otherwise, a calling convention.
5827   CallingConv CC;
5828   if (S.CheckCallingConvAttr(attr, CC))
5829     return true;
5830 
5831   const FunctionType *fn = unwrapped.get();
5832   CallingConv CCOld = fn->getCallConv();
5833   AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr);
5834 
5835   if (CCOld != CC) {
5836     // Error out on when there's already an attribute on the type
5837     // and the CCs don't match.
5838     const AttributedType *AT = S.getCallingConvAttributedType(type);
5839     if (AT && AT->getAttrKind() != CCAttrKind) {
5840       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
5841         << FunctionType::getNameForCallConv(CC)
5842         << FunctionType::getNameForCallConv(CCOld);
5843       attr.setInvalid();
5844       return true;
5845     }
5846   }
5847 
5848   // Diagnose use of callee-cleanup calling convention on variadic functions.
5849   if (!supportsVariadicCall(CC)) {
5850     const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
5851     if (FnP && FnP->isVariadic()) {
5852       unsigned DiagID = diag::err_cconv_varargs;
5853       // stdcall and fastcall are ignored with a warning for GCC and MS
5854       // compatibility.
5855       if (CC == CC_X86StdCall || CC == CC_X86FastCall)
5856         DiagID = diag::warn_cconv_varargs;
5857 
5858       S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC);
5859       attr.setInvalid();
5860       return true;
5861     }
5862   }
5863 
5864   // Also diagnose fastcall with regparm.
5865   if (CC == CC_X86FastCall && fn->getHasRegParm()) {
5866     S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
5867         << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
5868     attr.setInvalid();
5869     return true;
5870   }
5871 
5872   // Modify the CC from the wrapped function type, wrap it all back, and then
5873   // wrap the whole thing in an AttributedType as written.  The modified type
5874   // might have a different CC if we ignored the attribute.
5875   FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
5876   QualType Equivalent =
5877       unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5878   type = S.Context.getAttributedType(CCAttrKind, type, Equivalent);
5879   return true;
5880 }
5881 
5882 bool Sema::hasExplicitCallingConv(QualType &T) {
5883   QualType R = T.IgnoreParens();
5884   while (const AttributedType *AT = dyn_cast<AttributedType>(R)) {
5885     if (AT->isCallingConv())
5886       return true;
5887     R = AT->getModifiedType().IgnoreParens();
5888   }
5889   return false;
5890 }
5891 
5892 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
5893                                   SourceLocation Loc) {
5894   FunctionTypeUnwrapper Unwrapped(*this, T);
5895   const FunctionType *FT = Unwrapped.get();
5896   bool IsVariadic = (isa<FunctionProtoType>(FT) &&
5897                      cast<FunctionProtoType>(FT)->isVariadic());
5898   CallingConv CurCC = FT->getCallConv();
5899   CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
5900 
5901   if (CurCC == ToCC)
5902     return;
5903 
5904   // MS compiler ignores explicit calling convention attributes on structors. We
5905   // should do the same.
5906   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
5907     // Issue a warning on ignored calling convention -- except of __stdcall.
5908     // Again, this is what MS compiler does.
5909     if (CurCC != CC_X86StdCall)
5910       Diag(Loc, diag::warn_cconv_structors)
5911           << FunctionType::getNameForCallConv(CurCC);
5912   // Default adjustment.
5913   } else {
5914     // Only adjust types with the default convention.  For example, on Windows
5915     // we should adjust a __cdecl type to __thiscall for instance methods, and a
5916     // __thiscall type to __cdecl for static methods.
5917     CallingConv DefaultCC =
5918         Context.getDefaultCallingConvention(IsVariadic, IsStatic);
5919 
5920     if (CurCC != DefaultCC || DefaultCC == ToCC)
5921       return;
5922 
5923     if (hasExplicitCallingConv(T))
5924       return;
5925   }
5926 
5927   FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
5928   QualType Wrapped = Unwrapped.wrap(*this, FT);
5929   T = Context.getAdjustedType(T, Wrapped);
5930 }
5931 
5932 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
5933 /// and float scalars, although arrays, pointers, and function return values are
5934 /// allowed in conjunction with this construct. Aggregates with this attribute
5935 /// are invalid, even if they are of the same size as a corresponding scalar.
5936 /// The raw attribute should contain precisely 1 argument, the vector size for
5937 /// the variable, measured in bytes. If curType and rawAttr are well formed,
5938 /// this routine will return a new vector type.
5939 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
5940                                  Sema &S) {
5941   // Check the attribute arguments.
5942   if (Attr.getNumArgs() != 1) {
5943     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5944       << Attr.getName() << 1;
5945     Attr.setInvalid();
5946     return;
5947   }
5948   Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5949   llvm::APSInt vecSize(32);
5950   if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
5951       !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
5952     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
5953       << Attr.getName() << AANT_ArgumentIntegerConstant
5954       << sizeExpr->getSourceRange();
5955     Attr.setInvalid();
5956     return;
5957   }
5958   // The base type must be integer (not Boolean or enumeration) or float, and
5959   // can't already be a vector.
5960   if (!CurType->isBuiltinType() || CurType->isBooleanType() ||
5961       (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
5962     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
5963     Attr.setInvalid();
5964     return;
5965   }
5966   unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
5967   // vecSize is specified in bytes - convert to bits.
5968   unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
5969 
5970   // the vector size needs to be an integral multiple of the type size.
5971   if (vectorSize % typeSize) {
5972     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
5973       << sizeExpr->getSourceRange();
5974     Attr.setInvalid();
5975     return;
5976   }
5977   if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) {
5978     S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large)
5979       << sizeExpr->getSourceRange();
5980     Attr.setInvalid();
5981     return;
5982   }
5983   if (vectorSize == 0) {
5984     S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
5985       << sizeExpr->getSourceRange();
5986     Attr.setInvalid();
5987     return;
5988   }
5989 
5990   // Success! Instantiate the vector type, the number of elements is > 0, and
5991   // not required to be a power of 2, unlike GCC.
5992   CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
5993                                     VectorType::GenericVector);
5994 }
5995 
5996 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
5997 /// a type.
5998 static void HandleExtVectorTypeAttr(QualType &CurType,
5999                                     const AttributeList &Attr,
6000                                     Sema &S) {
6001   // check the attribute arguments.
6002   if (Attr.getNumArgs() != 1) {
6003     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6004       << Attr.getName() << 1;
6005     return;
6006   }
6007 
6008   Expr *sizeExpr;
6009 
6010   // Special case where the argument is a template id.
6011   if (Attr.isArgIdent(0)) {
6012     CXXScopeSpec SS;
6013     SourceLocation TemplateKWLoc;
6014     UnqualifiedId id;
6015     id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
6016 
6017     ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
6018                                           id, false, false);
6019     if (Size.isInvalid())
6020       return;
6021 
6022     sizeExpr = Size.get();
6023   } else {
6024     sizeExpr = Attr.getArgAsExpr(0);
6025   }
6026 
6027   // Create the vector type.
6028   QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
6029   if (!T.isNull())
6030     CurType = T;
6031 }
6032 
6033 static bool isPermittedNeonBaseType(QualType &Ty,
6034                                     VectorType::VectorKind VecKind, Sema &S) {
6035   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
6036   if (!BTy)
6037     return false;
6038 
6039   llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
6040 
6041   // Signed poly is mathematically wrong, but has been baked into some ABIs by
6042   // now.
6043   bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
6044                         Triple.getArch() == llvm::Triple::aarch64_be;
6045   if (VecKind == VectorType::NeonPolyVector) {
6046     if (IsPolyUnsigned) {
6047       // AArch64 polynomial vectors are unsigned and support poly64.
6048       return BTy->getKind() == BuiltinType::UChar ||
6049              BTy->getKind() == BuiltinType::UShort ||
6050              BTy->getKind() == BuiltinType::ULong ||
6051              BTy->getKind() == BuiltinType::ULongLong;
6052     } else {
6053       // AArch32 polynomial vector are signed.
6054       return BTy->getKind() == BuiltinType::SChar ||
6055              BTy->getKind() == BuiltinType::Short;
6056     }
6057   }
6058 
6059   // Non-polynomial vector types: the usual suspects are allowed, as well as
6060   // float64_t on AArch64.
6061   bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 ||
6062                  Triple.getArch() == llvm::Triple::aarch64_be;
6063 
6064   if (Is64Bit && BTy->getKind() == BuiltinType::Double)
6065     return true;
6066 
6067   return BTy->getKind() == BuiltinType::SChar ||
6068          BTy->getKind() == BuiltinType::UChar ||
6069          BTy->getKind() == BuiltinType::Short ||
6070          BTy->getKind() == BuiltinType::UShort ||
6071          BTy->getKind() == BuiltinType::Int ||
6072          BTy->getKind() == BuiltinType::UInt ||
6073          BTy->getKind() == BuiltinType::Long ||
6074          BTy->getKind() == BuiltinType::ULong ||
6075          BTy->getKind() == BuiltinType::LongLong ||
6076          BTy->getKind() == BuiltinType::ULongLong ||
6077          BTy->getKind() == BuiltinType::Float ||
6078          BTy->getKind() == BuiltinType::Half;
6079 }
6080 
6081 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
6082 /// "neon_polyvector_type" attributes are used to create vector types that
6083 /// are mangled according to ARM's ABI.  Otherwise, these types are identical
6084 /// to those created with the "vector_size" attribute.  Unlike "vector_size"
6085 /// the argument to these Neon attributes is the number of vector elements,
6086 /// not the vector size in bytes.  The vector width and element type must
6087 /// match one of the standard Neon vector types.
6088 static void HandleNeonVectorTypeAttr(QualType& CurType,
6089                                      const AttributeList &Attr, Sema &S,
6090                                      VectorType::VectorKind VecKind) {
6091   // Target must have NEON
6092   if (!S.Context.getTargetInfo().hasFeature("neon")) {
6093     S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName();
6094     Attr.setInvalid();
6095     return;
6096   }
6097   // Check the attribute arguments.
6098   if (Attr.getNumArgs() != 1) {
6099     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6100       << Attr.getName() << 1;
6101     Attr.setInvalid();
6102     return;
6103   }
6104   // The number of elements must be an ICE.
6105   Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6106   llvm::APSInt numEltsInt(32);
6107   if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
6108       !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
6109     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6110       << Attr.getName() << AANT_ArgumentIntegerConstant
6111       << numEltsExpr->getSourceRange();
6112     Attr.setInvalid();
6113     return;
6114   }
6115   // Only certain element types are supported for Neon vectors.
6116   if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
6117     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
6118     Attr.setInvalid();
6119     return;
6120   }
6121 
6122   // The total size of the vector must be 64 or 128 bits.
6123   unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
6124   unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
6125   unsigned vecSize = typeSize * numElts;
6126   if (vecSize != 64 && vecSize != 128) {
6127     S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
6128     Attr.setInvalid();
6129     return;
6130   }
6131 
6132   CurType = S.Context.getVectorType(CurType, numElts, VecKind);
6133 }
6134 
6135 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
6136                              TypeAttrLocation TAL, AttributeList *attrs) {
6137   // Scan through and apply attributes to this type where it makes sense.  Some
6138   // attributes (such as __address_space__, __vector_size__, etc) apply to the
6139   // type, but others can be present in the type specifiers even though they
6140   // apply to the decl.  Here we apply type attributes and ignore the rest.
6141 
6142   AttributeList *next;
6143   do {
6144     AttributeList &attr = *attrs;
6145     next = attr.getNext();
6146 
6147     // Skip attributes that were marked to be invalid.
6148     if (attr.isInvalid())
6149       continue;
6150 
6151     if (attr.isCXX11Attribute()) {
6152       // [[gnu::...]] attributes are treated as declaration attributes, so may
6153       // not appertain to a DeclaratorChunk, even if we handle them as type
6154       // attributes.
6155       if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
6156         if (TAL == TAL_DeclChunk) {
6157           state.getSema().Diag(attr.getLoc(),
6158                                diag::warn_cxx11_gnu_attribute_on_type)
6159               << attr.getName();
6160           continue;
6161         }
6162       } else if (TAL != TAL_DeclChunk) {
6163         // Otherwise, only consider type processing for a C++11 attribute if
6164         // it's actually been applied to a type.
6165         continue;
6166       }
6167     }
6168 
6169     // If this is an attribute we can handle, do so now,
6170     // otherwise, add it to the FnAttrs list for rechaining.
6171     switch (attr.getKind()) {
6172     default:
6173       // A C++11 attribute on a declarator chunk must appertain to a type.
6174       if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
6175         state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
6176           << attr.getName();
6177         attr.setUsedAsTypeAttr();
6178       }
6179       break;
6180 
6181     case AttributeList::UnknownAttribute:
6182       if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
6183         state.getSema().Diag(attr.getLoc(),
6184                              diag::warn_unknown_attribute_ignored)
6185           << attr.getName();
6186       break;
6187 
6188     case AttributeList::IgnoredAttribute:
6189       break;
6190 
6191     case AttributeList::AT_MayAlias:
6192       // FIXME: This attribute needs to actually be handled, but if we ignore
6193       // it it breaks large amounts of Linux software.
6194       attr.setUsedAsTypeAttr();
6195       break;
6196     case AttributeList::AT_OpenCLPrivateAddressSpace:
6197     case AttributeList::AT_OpenCLGlobalAddressSpace:
6198     case AttributeList::AT_OpenCLLocalAddressSpace:
6199     case AttributeList::AT_OpenCLConstantAddressSpace:
6200     case AttributeList::AT_OpenCLGenericAddressSpace:
6201     case AttributeList::AT_AddressSpace:
6202       HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
6203       attr.setUsedAsTypeAttr();
6204       break;
6205     OBJC_POINTER_TYPE_ATTRS_CASELIST:
6206       if (!handleObjCPointerTypeAttr(state, attr, type))
6207         distributeObjCPointerTypeAttr(state, attr, type);
6208       attr.setUsedAsTypeAttr();
6209       break;
6210     case AttributeList::AT_VectorSize:
6211       HandleVectorSizeAttr(type, attr, state.getSema());
6212       attr.setUsedAsTypeAttr();
6213       break;
6214     case AttributeList::AT_ExtVectorType:
6215       HandleExtVectorTypeAttr(type, attr, state.getSema());
6216       attr.setUsedAsTypeAttr();
6217       break;
6218     case AttributeList::AT_NeonVectorType:
6219       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
6220                                VectorType::NeonVector);
6221       attr.setUsedAsTypeAttr();
6222       break;
6223     case AttributeList::AT_NeonPolyVectorType:
6224       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
6225                                VectorType::NeonPolyVector);
6226       attr.setUsedAsTypeAttr();
6227       break;
6228     case AttributeList::AT_OpenCLImageAccess:
6229       // FIXME: there should be some type checking happening here, I would
6230       // imagine, but the original handler's checking was entirely superfluous.
6231       attr.setUsedAsTypeAttr();
6232       break;
6233 
6234     MS_TYPE_ATTRS_CASELIST:
6235       if (!handleMSPointerTypeQualifierAttr(state, attr, type))
6236         attr.setUsedAsTypeAttr();
6237       break;
6238 
6239 
6240     NULLABILITY_TYPE_ATTRS_CASELIST:
6241       // Either add nullability here or try to distribute it.  We
6242       // don't want to distribute the nullability specifier past any
6243       // dependent type, because that complicates the user model.
6244       if (type->canHaveNullability() || type->isDependentType() ||
6245           !distributeNullabilityTypeAttr(state, type, attr)) {
6246         if (state.getSema().checkNullabilityTypeSpecifier(
6247               type,
6248               mapNullabilityAttrKind(attr.getKind()),
6249               attr.getLoc(),
6250               attr.isContextSensitiveKeywordAttribute())) {
6251           attr.setInvalid();
6252         }
6253 
6254         attr.setUsedAsTypeAttr();
6255       }
6256       break;
6257 
6258     case AttributeList::AT_ObjCKindOf:
6259       // '__kindof' must be part of the decl-specifiers.
6260       switch (TAL) {
6261       case TAL_DeclSpec:
6262         break;
6263 
6264       case TAL_DeclChunk:
6265       case TAL_DeclName:
6266         state.getSema().Diag(attr.getLoc(),
6267                              diag::err_objc_kindof_wrong_position)
6268           << FixItHint::CreateRemoval(attr.getLoc())
6269           << FixItHint::CreateInsertion(
6270                state.getDeclarator().getDeclSpec().getLocStart(), "__kindof ");
6271         break;
6272       }
6273 
6274       // Apply it regardless.
6275       if (state.getSema().checkObjCKindOfType(type, attr.getLoc()))
6276         attr.setInvalid();
6277       attr.setUsedAsTypeAttr();
6278       break;
6279 
6280     case AttributeList::AT_NSReturnsRetained:
6281       if (!state.getSema().getLangOpts().ObjCAutoRefCount)
6282         break;
6283       // fallthrough into the function attrs
6284 
6285     FUNCTION_TYPE_ATTRS_CASELIST:
6286       attr.setUsedAsTypeAttr();
6287 
6288       // Never process function type attributes as part of the
6289       // declaration-specifiers.
6290       if (TAL == TAL_DeclSpec)
6291         distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
6292 
6293       // Otherwise, handle the possible delays.
6294       else if (!handleFunctionTypeAttr(state, attr, type))
6295         distributeFunctionTypeAttr(state, attr, type);
6296       break;
6297     }
6298   } while ((attrs = next));
6299 }
6300 
6301 /// \brief Ensure that the type of the given expression is complete.
6302 ///
6303 /// This routine checks whether the expression \p E has a complete type. If the
6304 /// expression refers to an instantiable construct, that instantiation is
6305 /// performed as needed to complete its type. Furthermore
6306 /// Sema::RequireCompleteType is called for the expression's type (or in the
6307 /// case of a reference type, the referred-to type).
6308 ///
6309 /// \param E The expression whose type is required to be complete.
6310 /// \param Diagnoser The object that will emit a diagnostic if the type is
6311 /// incomplete.
6312 ///
6313 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
6314 /// otherwise.
6315 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser){
6316   QualType T = E->getType();
6317 
6318   // Fast path the case where the type is already complete.
6319   if (!T->isIncompleteType())
6320     // FIXME: The definition might not be visible.
6321     return false;
6322 
6323   // Incomplete array types may be completed by the initializer attached to
6324   // their definitions. For static data members of class templates and for
6325   // variable templates, we need to instantiate the definition to get this
6326   // initializer and complete the type.
6327   if (T->isIncompleteArrayType()) {
6328     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
6329       if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
6330         if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
6331           SourceLocation PointOfInstantiation = E->getExprLoc();
6332 
6333           if (MemberSpecializationInfo *MSInfo =
6334                   Var->getMemberSpecializationInfo()) {
6335             // If we don't already have a point of instantiation, this is it.
6336             if (MSInfo->getPointOfInstantiation().isInvalid()) {
6337               MSInfo->setPointOfInstantiation(PointOfInstantiation);
6338 
6339               // This is a modification of an existing AST node. Notify
6340               // listeners.
6341               if (ASTMutationListener *L = getASTMutationListener())
6342                 L->StaticDataMemberInstantiated(Var);
6343             }
6344           } else {
6345             VarTemplateSpecializationDecl *VarSpec =
6346                 cast<VarTemplateSpecializationDecl>(Var);
6347             if (VarSpec->getPointOfInstantiation().isInvalid())
6348               VarSpec->setPointOfInstantiation(PointOfInstantiation);
6349           }
6350 
6351           InstantiateVariableDefinition(PointOfInstantiation, Var);
6352 
6353           // Update the type to the newly instantiated definition's type both
6354           // here and within the expression.
6355           if (VarDecl *Def = Var->getDefinition()) {
6356             DRE->setDecl(Def);
6357             T = Def->getType();
6358             DRE->setType(T);
6359             E->setType(T);
6360           }
6361 
6362           // We still go on to try to complete the type independently, as it
6363           // may also require instantiations or diagnostics if it remains
6364           // incomplete.
6365         }
6366       }
6367     }
6368   }
6369 
6370   // FIXME: Are there other cases which require instantiating something other
6371   // than the type to complete the type of an expression?
6372 
6373   // Look through reference types and complete the referred type.
6374   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6375     T = Ref->getPointeeType();
6376 
6377   return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
6378 }
6379 
6380 namespace {
6381   struct TypeDiagnoserDiag : Sema::TypeDiagnoser {
6382     unsigned DiagID;
6383 
6384     TypeDiagnoserDiag(unsigned DiagID)
6385       : Sema::TypeDiagnoser(DiagID == 0), DiagID(DiagID) {}
6386 
6387     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6388       if (Suppressed) return;
6389       S.Diag(Loc, DiagID) << T;
6390     }
6391   };
6392 }
6393 
6394 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
6395   TypeDiagnoserDiag Diagnoser(DiagID);
6396   return RequireCompleteExprType(E, Diagnoser);
6397 }
6398 
6399 /// @brief Ensure that the type T is a complete type.
6400 ///
6401 /// This routine checks whether the type @p T is complete in any
6402 /// context where a complete type is required. If @p T is a complete
6403 /// type, returns false. If @p T is a class template specialization,
6404 /// this routine then attempts to perform class template
6405 /// instantiation. If instantiation fails, or if @p T is incomplete
6406 /// and cannot be completed, issues the diagnostic @p diag (giving it
6407 /// the type @p T) and returns true.
6408 ///
6409 /// @param Loc  The location in the source that the incomplete type
6410 /// diagnostic should refer to.
6411 ///
6412 /// @param T  The type that this routine is examining for completeness.
6413 ///
6414 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
6415 /// @c false otherwise.
6416 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
6417                                TypeDiagnoser &Diagnoser) {
6418   if (RequireCompleteTypeImpl(Loc, T, Diagnoser))
6419     return true;
6420   if (const TagType *Tag = T->getAs<TagType>()) {
6421     if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
6422       Tag->getDecl()->setCompleteDefinitionRequired();
6423       Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
6424     }
6425   }
6426   return false;
6427 }
6428 
6429 /// \brief Determine whether there is any declaration of \p D that was ever a
6430 ///        definition (perhaps before module merging) and is currently visible.
6431 /// \param D The definition of the entity.
6432 /// \param Suggested Filled in with the declaration that should be made visible
6433 ///        in order to provide a definition of this entity.
6434 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
6435 ///        not defined. This only matters for enums with a fixed underlying
6436 ///        type, since in all other cases, a type is complete if and only if it
6437 ///        is defined.
6438 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
6439                                 bool OnlyNeedComplete) {
6440   // Easy case: if we don't have modules, all declarations are visible.
6441   if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
6442     return true;
6443 
6444   // If this definition was instantiated from a template, map back to the
6445   // pattern from which it was instantiated.
6446   if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
6447     // We're in the middle of defining it; this definition should be treated
6448     // as visible.
6449     return true;
6450   } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6451     if (auto *Pattern = RD->getTemplateInstantiationPattern())
6452       RD = Pattern;
6453     D = RD->getDefinition();
6454   } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
6455     while (auto *NewED = ED->getInstantiatedFromMemberEnum())
6456       ED = NewED;
6457     if (OnlyNeedComplete && ED->isFixed()) {
6458       // If the enum has a fixed underlying type, and we're only looking for a
6459       // complete type (not a definition), any visible declaration of it will
6460       // do.
6461       *Suggested = nullptr;
6462       for (auto *Redecl : ED->redecls()) {
6463         if (isVisible(Redecl))
6464           return true;
6465         if (Redecl->isThisDeclarationADefinition() ||
6466             (Redecl->isCanonicalDecl() && !*Suggested))
6467           *Suggested = Redecl;
6468       }
6469       return false;
6470     }
6471     D = ED->getDefinition();
6472   }
6473   assert(D && "missing definition for pattern of instantiated definition");
6474 
6475   *Suggested = D;
6476   if (isVisible(D))
6477     return true;
6478 
6479   // The external source may have additional definitions of this type that are
6480   // visible, so complete the redeclaration chain now and ask again.
6481   if (auto *Source = Context.getExternalSource()) {
6482     Source->CompleteRedeclChain(D);
6483     return isVisible(D);
6484   }
6485 
6486   return false;
6487 }
6488 
6489 /// Locks in the inheritance model for the given class and all of its bases.
6490 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
6491   RD = RD->getMostRecentDecl();
6492   if (!RD->hasAttr<MSInheritanceAttr>()) {
6493     MSInheritanceAttr::Spelling IM;
6494 
6495     switch (S.MSPointerToMemberRepresentationMethod) {
6496     case LangOptions::PPTMK_BestCase:
6497       IM = RD->calculateInheritanceModel();
6498       break;
6499     case LangOptions::PPTMK_FullGeneralitySingleInheritance:
6500       IM = MSInheritanceAttr::Keyword_single_inheritance;
6501       break;
6502     case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
6503       IM = MSInheritanceAttr::Keyword_multiple_inheritance;
6504       break;
6505     case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
6506       IM = MSInheritanceAttr::Keyword_unspecified_inheritance;
6507       break;
6508     }
6509 
6510     RD->addAttr(MSInheritanceAttr::CreateImplicit(
6511         S.getASTContext(), IM,
6512         /*BestCase=*/S.MSPointerToMemberRepresentationMethod ==
6513             LangOptions::PPTMK_BestCase,
6514         S.ImplicitMSInheritanceAttrLoc.isValid()
6515             ? S.ImplicitMSInheritanceAttrLoc
6516             : RD->getSourceRange()));
6517   }
6518 }
6519 
6520 /// \brief The implementation of RequireCompleteType
6521 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
6522                                    TypeDiagnoser &Diagnoser) {
6523   // FIXME: Add this assertion to make sure we always get instantiation points.
6524   //  assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
6525   // FIXME: Add this assertion to help us flush out problems with
6526   // checking for dependent types and type-dependent expressions.
6527   //
6528   //  assert(!T->isDependentType() &&
6529   //         "Can't ask whether a dependent type is complete");
6530 
6531   // We lock in the inheritance model once somebody has asked us to ensure
6532   // that a pointer-to-member type is complete.
6533   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6534     if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
6535       if (!MPTy->getClass()->isDependentType()) {
6536         RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), 0);
6537         assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
6538       }
6539     }
6540   }
6541 
6542   // If we have a complete type, we're done.
6543   NamedDecl *Def = nullptr;
6544   if (!T->isIncompleteType(&Def)) {
6545     // If we know about the definition but it is not visible, complain.
6546     NamedDecl *SuggestedDef = nullptr;
6547     if (!Diagnoser.Suppressed && Def &&
6548         !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true))
6549       diagnoseMissingImport(Loc, SuggestedDef, /*NeedDefinition*/true);
6550 
6551     return false;
6552   }
6553 
6554   const TagType *Tag = T->getAs<TagType>();
6555   const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>();
6556 
6557   // If there's an unimported definition of this type in a module (for
6558   // instance, because we forward declared it, then imported the definition),
6559   // import that definition now.
6560   //
6561   // FIXME: What about other cases where an import extends a redeclaration
6562   // chain for a declaration that can be accessed through a mechanism other
6563   // than name lookup (eg, referenced in a template, or a variable whose type
6564   // could be completed by the module)?
6565   if (Tag || IFace) {
6566     NamedDecl *D =
6567         Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl();
6568 
6569     // Avoid diagnosing invalid decls as incomplete.
6570     if (D->isInvalidDecl())
6571       return true;
6572 
6573     // Give the external AST source a chance to complete the type.
6574     if (auto *Source = Context.getExternalSource()) {
6575       if (Tag)
6576         Source->CompleteType(Tag->getDecl());
6577       else
6578         Source->CompleteType(IFace->getDecl());
6579 
6580       // If the external source completed the type, go through the motions
6581       // again to ensure we're allowed to use the completed type.
6582       if (!T->isIncompleteType())
6583         return RequireCompleteTypeImpl(Loc, T, Diagnoser);
6584     }
6585   }
6586 
6587   // If we have a class template specialization or a class member of a
6588   // class template specialization, or an array with known size of such,
6589   // try to instantiate it.
6590   QualType MaybeTemplate = T;
6591   while (const ConstantArrayType *Array
6592            = Context.getAsConstantArrayType(MaybeTemplate))
6593     MaybeTemplate = Array->getElementType();
6594   if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
6595     if (ClassTemplateSpecializationDecl *ClassTemplateSpec
6596           = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
6597       if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
6598         return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
6599                                                       TSK_ImplicitInstantiation,
6600                                             /*Complain=*/!Diagnoser.Suppressed);
6601     } else if (CXXRecordDecl *Rec
6602                  = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
6603       CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
6604       if (!Rec->isBeingDefined() && Pattern) {
6605         MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
6606         assert(MSI && "Missing member specialization information?");
6607         // This record was instantiated from a class within a template.
6608         if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
6609           return InstantiateClass(Loc, Rec, Pattern,
6610                                   getTemplateInstantiationArgs(Rec),
6611                                   TSK_ImplicitInstantiation,
6612                                   /*Complain=*/!Diagnoser.Suppressed);
6613       }
6614     }
6615   }
6616 
6617   if (Diagnoser.Suppressed)
6618     return true;
6619 
6620   // We have an incomplete type. Produce a diagnostic.
6621   if (Ident___float128 &&
6622       T == Context.getTypeDeclType(Context.getFloat128StubType())) {
6623     Diag(Loc, diag::err_typecheck_decl_incomplete_type___float128);
6624     return true;
6625   }
6626 
6627   Diagnoser.diagnose(*this, Loc, T);
6628 
6629   // If the type was a forward declaration of a class/struct/union
6630   // type, produce a note.
6631   if (Tag && !Tag->getDecl()->isInvalidDecl())
6632     Diag(Tag->getDecl()->getLocation(),
6633          Tag->isBeingDefined() ? diag::note_type_being_defined
6634                                : diag::note_forward_declaration)
6635       << QualType(Tag, 0);
6636 
6637   // If the Objective-C class was a forward declaration, produce a note.
6638   if (IFace && !IFace->getDecl()->isInvalidDecl())
6639     Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
6640 
6641   // If we have external information that we can use to suggest a fix,
6642   // produce a note.
6643   if (ExternalSource)
6644     ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
6645 
6646   return true;
6647 }
6648 
6649 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
6650                                unsigned DiagID) {
6651   TypeDiagnoserDiag Diagnoser(DiagID);
6652   return RequireCompleteType(Loc, T, Diagnoser);
6653 }
6654 
6655 /// \brief Get diagnostic %select index for tag kind for
6656 /// literal type diagnostic message.
6657 /// WARNING: Indexes apply to particular diagnostics only!
6658 ///
6659 /// \returns diagnostic %select index.
6660 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
6661   switch (Tag) {
6662   case TTK_Struct: return 0;
6663   case TTK_Interface: return 1;
6664   case TTK_Class:  return 2;
6665   default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
6666   }
6667 }
6668 
6669 /// @brief Ensure that the type T is a literal type.
6670 ///
6671 /// This routine checks whether the type @p T is a literal type. If @p T is an
6672 /// incomplete type, an attempt is made to complete it. If @p T is a literal
6673 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
6674 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
6675 /// it the type @p T), along with notes explaining why the type is not a
6676 /// literal type, and returns true.
6677 ///
6678 /// @param Loc  The location in the source that the non-literal type
6679 /// diagnostic should refer to.
6680 ///
6681 /// @param T  The type that this routine is examining for literalness.
6682 ///
6683 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
6684 ///
6685 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
6686 /// @c false otherwise.
6687 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
6688                               TypeDiagnoser &Diagnoser) {
6689   assert(!T->isDependentType() && "type should not be dependent");
6690 
6691   QualType ElemType = Context.getBaseElementType(T);
6692   RequireCompleteType(Loc, ElemType, 0);
6693 
6694   if (T->isLiteralType(Context))
6695     return false;
6696 
6697   if (Diagnoser.Suppressed)
6698     return true;
6699 
6700   Diagnoser.diagnose(*this, Loc, T);
6701 
6702   if (T->isVariableArrayType())
6703     return true;
6704 
6705   const RecordType *RT = ElemType->getAs<RecordType>();
6706   if (!RT)
6707     return true;
6708 
6709   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
6710 
6711   // A partially-defined class type can't be a literal type, because a literal
6712   // class type must have a trivial destructor (which can't be checked until
6713   // the class definition is complete).
6714   if (!RD->isCompleteDefinition()) {
6715     RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T);
6716     return true;
6717   }
6718 
6719   // If the class has virtual base classes, then it's not an aggregate, and
6720   // cannot have any constexpr constructors or a trivial default constructor,
6721   // so is non-literal. This is better to diagnose than the resulting absence
6722   // of constexpr constructors.
6723   if (RD->getNumVBases()) {
6724     Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
6725       << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
6726     for (const auto &I : RD->vbases())
6727       Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here)
6728           << I.getSourceRange();
6729   } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
6730              !RD->hasTrivialDefaultConstructor()) {
6731     Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
6732   } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
6733     for (const auto &I : RD->bases()) {
6734       if (!I.getType()->isLiteralType(Context)) {
6735         Diag(I.getLocStart(),
6736              diag::note_non_literal_base_class)
6737           << RD << I.getType() << I.getSourceRange();
6738         return true;
6739       }
6740     }
6741     for (const auto *I : RD->fields()) {
6742       if (!I->getType()->isLiteralType(Context) ||
6743           I->getType().isVolatileQualified()) {
6744         Diag(I->getLocation(), diag::note_non_literal_field)
6745           << RD << I << I->getType()
6746           << I->getType().isVolatileQualified();
6747         return true;
6748       }
6749     }
6750   } else if (!RD->hasTrivialDestructor()) {
6751     // All fields and bases are of literal types, so have trivial destructors.
6752     // If this class's destructor is non-trivial it must be user-declared.
6753     CXXDestructorDecl *Dtor = RD->getDestructor();
6754     assert(Dtor && "class has literal fields and bases but no dtor?");
6755     if (!Dtor)
6756       return true;
6757 
6758     Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
6759          diag::note_non_literal_user_provided_dtor :
6760          diag::note_non_literal_nontrivial_dtor) << RD;
6761     if (!Dtor->isUserProvided())
6762       SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true);
6763   }
6764 
6765   return true;
6766 }
6767 
6768 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
6769   TypeDiagnoserDiag Diagnoser(DiagID);
6770   return RequireLiteralType(Loc, T, Diagnoser);
6771 }
6772 
6773 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
6774 /// and qualified by the nested-name-specifier contained in SS.
6775 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
6776                                  const CXXScopeSpec &SS, QualType T) {
6777   if (T.isNull())
6778     return T;
6779   NestedNameSpecifier *NNS;
6780   if (SS.isValid())
6781     NNS = SS.getScopeRep();
6782   else {
6783     if (Keyword == ETK_None)
6784       return T;
6785     NNS = nullptr;
6786   }
6787   return Context.getElaboratedType(Keyword, NNS, T);
6788 }
6789 
6790 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
6791   ExprResult ER = CheckPlaceholderExpr(E);
6792   if (ER.isInvalid()) return QualType();
6793   E = ER.get();
6794 
6795   if (!E->isTypeDependent()) {
6796     QualType T = E->getType();
6797     if (const TagType *TT = T->getAs<TagType>())
6798       DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
6799   }
6800   return Context.getTypeOfExprType(E);
6801 }
6802 
6803 /// getDecltypeForExpr - Given an expr, will return the decltype for
6804 /// that expression, according to the rules in C++11
6805 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
6806 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
6807   if (E->isTypeDependent())
6808     return S.Context.DependentTy;
6809 
6810   // C++11 [dcl.type.simple]p4:
6811   //   The type denoted by decltype(e) is defined as follows:
6812   //
6813   //     - if e is an unparenthesized id-expression or an unparenthesized class
6814   //       member access (5.2.5), decltype(e) is the type of the entity named
6815   //       by e. If there is no such entity, or if e names a set of overloaded
6816   //       functions, the program is ill-formed;
6817   //
6818   // We apply the same rules for Objective-C ivar and property references.
6819   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6820     if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
6821       return VD->getType();
6822   } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6823     if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
6824       return FD->getType();
6825   } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
6826     return IR->getDecl()->getType();
6827   } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
6828     if (PR->isExplicitProperty())
6829       return PR->getExplicitProperty()->getType();
6830   } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) {
6831     return PE->getType();
6832   }
6833 
6834   // C++11 [expr.lambda.prim]p18:
6835   //   Every occurrence of decltype((x)) where x is a possibly
6836   //   parenthesized id-expression that names an entity of automatic
6837   //   storage duration is treated as if x were transformed into an
6838   //   access to a corresponding data member of the closure type that
6839   //   would have been declared if x were an odr-use of the denoted
6840   //   entity.
6841   using namespace sema;
6842   if (S.getCurLambda()) {
6843     if (isa<ParenExpr>(E)) {
6844       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
6845         if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
6846           QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
6847           if (!T.isNull())
6848             return S.Context.getLValueReferenceType(T);
6849         }
6850       }
6851     }
6852   }
6853 
6854 
6855   // C++11 [dcl.type.simple]p4:
6856   //   [...]
6857   QualType T = E->getType();
6858   switch (E->getValueKind()) {
6859   //     - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6860   //       type of e;
6861   case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
6862   //     - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6863   //       type of e;
6864   case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
6865   //  - otherwise, decltype(e) is the type of e.
6866   case VK_RValue: break;
6867   }
6868 
6869   return T;
6870 }
6871 
6872 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc,
6873                                  bool AsUnevaluated) {
6874   ExprResult ER = CheckPlaceholderExpr(E);
6875   if (ER.isInvalid()) return QualType();
6876   E = ER.get();
6877 
6878   if (AsUnevaluated && ActiveTemplateInstantiations.empty() &&
6879       E->HasSideEffects(Context, false)) {
6880     // The expression operand for decltype is in an unevaluated expression
6881     // context, so side effects could result in unintended consequences.
6882     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
6883   }
6884 
6885   return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
6886 }
6887 
6888 QualType Sema::BuildUnaryTransformType(QualType BaseType,
6889                                        UnaryTransformType::UTTKind UKind,
6890                                        SourceLocation Loc) {
6891   switch (UKind) {
6892   case UnaryTransformType::EnumUnderlyingType:
6893     if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
6894       Diag(Loc, diag::err_only_enums_have_underlying_types);
6895       return QualType();
6896     } else {
6897       QualType Underlying = BaseType;
6898       if (!BaseType->isDependentType()) {
6899         // The enum could be incomplete if we're parsing its definition or
6900         // recovering from an error.
6901         NamedDecl *FwdDecl = nullptr;
6902         if (BaseType->isIncompleteType(&FwdDecl)) {
6903           Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
6904           Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
6905           return QualType();
6906         }
6907 
6908         EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
6909         assert(ED && "EnumType has no EnumDecl");
6910 
6911         DiagnoseUseOfDecl(ED, Loc);
6912 
6913         Underlying = ED->getIntegerType();
6914         assert(!Underlying.isNull());
6915       }
6916       return Context.getUnaryTransformType(BaseType, Underlying,
6917                                         UnaryTransformType::EnumUnderlyingType);
6918     }
6919   }
6920   llvm_unreachable("unknown unary transform type");
6921 }
6922 
6923 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
6924   if (!T->isDependentType()) {
6925     // FIXME: It isn't entirely clear whether incomplete atomic types
6926     // are allowed or not; for simplicity, ban them for the moment.
6927     if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
6928       return QualType();
6929 
6930     int DisallowedKind = -1;
6931     if (T->isArrayType())
6932       DisallowedKind = 1;
6933     else if (T->isFunctionType())
6934       DisallowedKind = 2;
6935     else if (T->isReferenceType())
6936       DisallowedKind = 3;
6937     else if (T->isAtomicType())
6938       DisallowedKind = 4;
6939     else if (T.hasQualifiers())
6940       DisallowedKind = 5;
6941     else if (!T.isTriviallyCopyableType(Context))
6942       // Some other non-trivially-copyable type (probably a C++ class)
6943       DisallowedKind = 6;
6944 
6945     if (DisallowedKind != -1) {
6946       Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
6947       return QualType();
6948     }
6949 
6950     // FIXME: Do we need any handling for ARC here?
6951   }
6952 
6953   // Build the pointer type.
6954   return Context.getAtomicType(T);
6955 }
6956