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