Home | History | Annotate | Download | only in Sema
      1 //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 //  This file implements type-related semantic analysis.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "clang/Sema/SemaInternal.h"
     15 #include "clang/AST/ASTContext.h"
     16 #include "clang/AST/ASTMutationListener.h"
     17 #include "clang/AST/CXXInheritance.h"
     18 #include "clang/AST/DeclObjC.h"
     19 #include "clang/AST/DeclTemplate.h"
     20 #include "clang/AST/Expr.h"
     21 #include "clang/AST/TypeLoc.h"
     22 #include "clang/AST/TypeLocVisitor.h"
     23 #include "clang/Basic/OpenCL.h"
     24 #include "clang/Basic/PartialDiagnostic.h"
     25 #include "clang/Basic/TargetInfo.h"
     26 #include "clang/Lex/Preprocessor.h"
     27 #include "clang/Parse/ParseDiagnostic.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/Template.h"
     33 #include "llvm/ADT/SmallPtrSet.h"
     34 #include "llvm/Support/ErrorHandling.h"
     35 using namespace clang;
     36 
     37 /// isOmittedBlockReturnType - Return true if this declarator is missing a
     38 /// return type because this is a omitted return type on a block literal.
     39 static bool isOmittedBlockReturnType(const Declarator &D) {
     40   if (D.getContext() != Declarator::BlockLiteralContext ||
     41       D.getDeclSpec().hasTypeSpecifier())
     42     return false;
     43 
     44   if (D.getNumTypeObjects() == 0)
     45     return true;   // ^{ ... }
     46 
     47   if (D.getNumTypeObjects() == 1 &&
     48       D.getTypeObject(0).Kind == DeclaratorChunk::Function)
     49     return true;   // ^(int X, float Y) { ... }
     50 
     51   return false;
     52 }
     53 
     54 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
     55 /// doesn't apply to the given type.
     56 static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
     57                                      QualType type) {
     58   bool useExpansionLoc = false;
     59 
     60   unsigned diagID = 0;
     61   switch (attr.getKind()) {
     62   case AttributeList::AT_ObjCGC:
     63     diagID = diag::warn_pointer_attribute_wrong_type;
     64     useExpansionLoc = true;
     65     break;
     66 
     67   case AttributeList::AT_ObjCOwnership:
     68     diagID = diag::warn_objc_object_attribute_wrong_type;
     69     useExpansionLoc = true;
     70     break;
     71 
     72   default:
     73     // Assume everything else was a function attribute.
     74     diagID = diag::warn_function_attribute_wrong_type;
     75     break;
     76   }
     77 
     78   SourceLocation loc = attr.getLoc();
     79   StringRef name = attr.getName()->getName();
     80 
     81   // The GC attributes are usually written with macros;  special-case them.
     82   if (useExpansionLoc && loc.isMacroID() && attr.getParameterName()) {
     83     if (attr.getParameterName()->isStr("strong")) {
     84       if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
     85     } else if (attr.getParameterName()->isStr("weak")) {
     86       if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
     87     }
     88   }
     89 
     90   S.Diag(loc, diagID) << name << type;
     91 }
     92 
     93 // objc_gc applies to Objective-C pointers or, otherwise, to the
     94 // smallest available pointer type (i.e. 'void*' in 'void**').
     95 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
     96     case AttributeList::AT_ObjCGC: \
     97     case AttributeList::AT_ObjCOwnership
     98 
     99 // Function type attributes.
    100 #define FUNCTION_TYPE_ATTRS_CASELIST \
    101     case AttributeList::AT_NoReturn: \
    102     case AttributeList::AT_CDecl: \
    103     case AttributeList::AT_FastCall: \
    104     case AttributeList::AT_StdCall: \
    105     case AttributeList::AT_ThisCall: \
    106     case AttributeList::AT_Pascal: \
    107     case AttributeList::AT_Regparm: \
    108     case AttributeList::AT_Pcs: \
    109     case AttributeList::AT_PnaclCall: \
    110     case AttributeList::AT_IntelOclBicc \
    111 
    112 namespace {
    113   /// An object which stores processing state for the entire
    114   /// GetTypeForDeclarator process.
    115   class TypeProcessingState {
    116     Sema &sema;
    117 
    118     /// The declarator being processed.
    119     Declarator &declarator;
    120 
    121     /// The index of the declarator chunk we're currently processing.
    122     /// May be the total number of valid chunks, indicating the
    123     /// DeclSpec.
    124     unsigned chunkIndex;
    125 
    126     /// Whether there are non-trivial modifications to the decl spec.
    127     bool trivial;
    128 
    129     /// Whether we saved the attributes in the decl spec.
    130     bool hasSavedAttrs;
    131 
    132     /// The original set of attributes on the DeclSpec.
    133     SmallVector<AttributeList*, 2> savedAttrs;
    134 
    135     /// A list of attributes to diagnose the uselessness of when the
    136     /// processing is complete.
    137     SmallVector<AttributeList*, 2> ignoredTypeAttrs;
    138 
    139   public:
    140     TypeProcessingState(Sema &sema, Declarator &declarator)
    141       : sema(sema), declarator(declarator),
    142         chunkIndex(declarator.getNumTypeObjects()),
    143         trivial(true), hasSavedAttrs(false) {}
    144 
    145     Sema &getSema() const {
    146       return sema;
    147     }
    148 
    149     Declarator &getDeclarator() const {
    150       return declarator;
    151     }
    152 
    153     bool isProcessingDeclSpec() const {
    154       return chunkIndex == declarator.getNumTypeObjects();
    155     }
    156 
    157     unsigned getCurrentChunkIndex() const {
    158       return chunkIndex;
    159     }
    160 
    161     void setCurrentChunkIndex(unsigned idx) {
    162       assert(idx <= declarator.getNumTypeObjects());
    163       chunkIndex = idx;
    164     }
    165 
    166     AttributeList *&getCurrentAttrListRef() const {
    167       if (isProcessingDeclSpec())
    168         return getMutableDeclSpec().getAttributes().getListRef();
    169       return declarator.getTypeObject(chunkIndex).getAttrListRef();
    170     }
    171 
    172     /// Save the current set of attributes on the DeclSpec.
    173     void saveDeclSpecAttrs() {
    174       // Don't try to save them multiple times.
    175       if (hasSavedAttrs) return;
    176 
    177       DeclSpec &spec = getMutableDeclSpec();
    178       for (AttributeList *attr = spec.getAttributes().getList(); attr;
    179              attr = attr->getNext())
    180         savedAttrs.push_back(attr);
    181       trivial &= savedAttrs.empty();
    182       hasSavedAttrs = true;
    183     }
    184 
    185     /// Record that we had nowhere to put the given type attribute.
    186     /// We will diagnose such attributes later.
    187     void addIgnoredTypeAttr(AttributeList &attr) {
    188       ignoredTypeAttrs.push_back(&attr);
    189     }
    190 
    191     /// Diagnose all the ignored type attributes, given that the
    192     /// declarator worked out to the given type.
    193     void diagnoseIgnoredTypeAttrs(QualType type) const {
    194       for (SmallVectorImpl<AttributeList*>::const_iterator
    195              i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end();
    196            i != e; ++i)
    197         diagnoseBadTypeAttribute(getSema(), **i, type);
    198     }
    199 
    200     ~TypeProcessingState() {
    201       if (trivial) return;
    202 
    203       restoreDeclSpecAttrs();
    204     }
    205 
    206   private:
    207     DeclSpec &getMutableDeclSpec() const {
    208       return const_cast<DeclSpec&>(declarator.getDeclSpec());
    209     }
    210 
    211     void restoreDeclSpecAttrs() {
    212       assert(hasSavedAttrs);
    213 
    214       if (savedAttrs.empty()) {
    215         getMutableDeclSpec().getAttributes().set(0);
    216         return;
    217       }
    218 
    219       getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
    220       for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
    221         savedAttrs[i]->setNext(savedAttrs[i+1]);
    222       savedAttrs.back()->setNext(0);
    223     }
    224   };
    225 
    226   /// Basically std::pair except that we really want to avoid an
    227   /// implicit operator= for safety concerns.  It's also a minor
    228   /// link-time optimization for this to be a private type.
    229   struct AttrAndList {
    230     /// The attribute.
    231     AttributeList &first;
    232 
    233     /// The head of the list the attribute is currently in.
    234     AttributeList *&second;
    235 
    236     AttrAndList(AttributeList &attr, AttributeList *&head)
    237       : first(attr), second(head) {}
    238   };
    239 }
    240 
    241 namespace llvm {
    242   template <> struct isPodLike<AttrAndList> {
    243     static const bool value = true;
    244   };
    245 }
    246 
    247 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
    248   attr.setNext(head);
    249   head = &attr;
    250 }
    251 
    252 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
    253   if (head == &attr) {
    254     head = attr.getNext();
    255     return;
    256   }
    257 
    258   AttributeList *cur = head;
    259   while (true) {
    260     assert(cur && cur->getNext() && "ran out of attrs?");
    261     if (cur->getNext() == &attr) {
    262       cur->setNext(attr.getNext());
    263       return;
    264     }
    265     cur = cur->getNext();
    266   }
    267 }
    268 
    269 static void moveAttrFromListToList(AttributeList &attr,
    270                                    AttributeList *&fromList,
    271                                    AttributeList *&toList) {
    272   spliceAttrOutOfList(attr, fromList);
    273   spliceAttrIntoList(attr, toList);
    274 }
    275 
    276 /// The location of a type attribute.
    277 enum TypeAttrLocation {
    278   /// The attribute is in the decl-specifier-seq.
    279   TAL_DeclSpec,
    280   /// The attribute is part of a DeclaratorChunk.
    281   TAL_DeclChunk,
    282   /// The attribute is immediately after the declaration's name.
    283   TAL_DeclName
    284 };
    285 
    286 static void processTypeAttrs(TypeProcessingState &state,
    287                              QualType &type, TypeAttrLocation TAL,
    288                              AttributeList *attrs);
    289 
    290 static bool handleFunctionTypeAttr(TypeProcessingState &state,
    291                                    AttributeList &attr,
    292                                    QualType &type);
    293 
    294 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
    295                                  AttributeList &attr, QualType &type);
    296 
    297 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
    298                                        AttributeList &attr, QualType &type);
    299 
    300 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
    301                                       AttributeList &attr, QualType &type) {
    302   if (attr.getKind() == AttributeList::AT_ObjCGC)
    303     return handleObjCGCTypeAttr(state, attr, type);
    304   assert(attr.getKind() == AttributeList::AT_ObjCOwnership);
    305   return handleObjCOwnershipTypeAttr(state, attr, type);
    306 }
    307 
    308 /// Given the index of a declarator chunk, check whether that chunk
    309 /// directly specifies the return type of a function and, if so, find
    310 /// an appropriate place for it.
    311 ///
    312 /// \param i - a notional index which the search will start
    313 ///   immediately inside
    314 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
    315                                                 unsigned i) {
    316   assert(i <= declarator.getNumTypeObjects());
    317 
    318   DeclaratorChunk *result = 0;
    319 
    320   // First, look inwards past parens for a function declarator.
    321   for (; i != 0; --i) {
    322     DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
    323     switch (fnChunk.Kind) {
    324     case DeclaratorChunk::Paren:
    325       continue;
    326 
    327     // If we find anything except a function, bail out.
    328     case DeclaratorChunk::Pointer:
    329     case DeclaratorChunk::BlockPointer:
    330     case DeclaratorChunk::Array:
    331     case DeclaratorChunk::Reference:
    332     case DeclaratorChunk::MemberPointer:
    333       return result;
    334 
    335     // If we do find a function declarator, scan inwards from that,
    336     // looking for a block-pointer declarator.
    337     case DeclaratorChunk::Function:
    338       for (--i; i != 0; --i) {
    339         DeclaratorChunk &blockChunk = declarator.getTypeObject(i-1);
    340         switch (blockChunk.Kind) {
    341         case DeclaratorChunk::Paren:
    342         case DeclaratorChunk::Pointer:
    343         case DeclaratorChunk::Array:
    344         case DeclaratorChunk::Function:
    345         case DeclaratorChunk::Reference:
    346         case DeclaratorChunk::MemberPointer:
    347           continue;
    348         case DeclaratorChunk::BlockPointer:
    349           result = &blockChunk;
    350           goto continue_outer;
    351         }
    352         llvm_unreachable("bad declarator chunk kind");
    353       }
    354 
    355       // If we run out of declarators doing that, we're done.
    356       return result;
    357     }
    358     llvm_unreachable("bad declarator chunk kind");
    359 
    360     // Okay, reconsider from our new point.
    361   continue_outer: ;
    362   }
    363 
    364   // Ran out of chunks, bail out.
    365   return result;
    366 }
    367 
    368 /// Given that an objc_gc attribute was written somewhere on a
    369 /// declaration *other* than on the declarator itself (for which, use
    370 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
    371 /// didn't apply in whatever position it was written in, try to move
    372 /// it to a more appropriate position.
    373 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
    374                                           AttributeList &attr,
    375                                           QualType type) {
    376   Declarator &declarator = state.getDeclarator();
    377 
    378   // Move it to the outermost normal or block pointer declarator.
    379   for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
    380     DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
    381     switch (chunk.Kind) {
    382     case DeclaratorChunk::Pointer:
    383     case DeclaratorChunk::BlockPointer: {
    384       // But don't move an ARC ownership attribute to the return type
    385       // of a block.
    386       DeclaratorChunk *destChunk = 0;
    387       if (state.isProcessingDeclSpec() &&
    388           attr.getKind() == AttributeList::AT_ObjCOwnership)
    389         destChunk = maybeMovePastReturnType(declarator, i - 1);
    390       if (!destChunk) destChunk = &chunk;
    391 
    392       moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
    393                              destChunk->getAttrListRef());
    394       return;
    395     }
    396 
    397     case DeclaratorChunk::Paren:
    398     case DeclaratorChunk::Array:
    399       continue;
    400 
    401     // We may be starting at the return type of a block.
    402     case DeclaratorChunk::Function:
    403       if (state.isProcessingDeclSpec() &&
    404           attr.getKind() == AttributeList::AT_ObjCOwnership) {
    405         if (DeclaratorChunk *dest = maybeMovePastReturnType(declarator, i)) {
    406           moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
    407                                  dest->getAttrListRef());
    408           return;
    409         }
    410       }
    411       goto error;
    412 
    413     // Don't walk through these.
    414     case DeclaratorChunk::Reference:
    415     case DeclaratorChunk::MemberPointer:
    416       goto error;
    417     }
    418   }
    419  error:
    420 
    421   diagnoseBadTypeAttribute(state.getSema(), attr, type);
    422 }
    423 
    424 /// Distribute an objc_gc type attribute that was written on the
    425 /// declarator.
    426 static void
    427 distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
    428                                             AttributeList &attr,
    429                                             QualType &declSpecType) {
    430   Declarator &declarator = state.getDeclarator();
    431 
    432   // objc_gc goes on the innermost pointer to something that's not a
    433   // pointer.
    434   unsigned innermost = -1U;
    435   bool considerDeclSpec = true;
    436   for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
    437     DeclaratorChunk &chunk = declarator.getTypeObject(i);
    438     switch (chunk.Kind) {
    439     case DeclaratorChunk::Pointer:
    440     case DeclaratorChunk::BlockPointer:
    441       innermost = i;
    442       continue;
    443 
    444     case DeclaratorChunk::Reference:
    445     case DeclaratorChunk::MemberPointer:
    446     case DeclaratorChunk::Paren:
    447     case DeclaratorChunk::Array:
    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.getAttrListRef(),
    466                declarator.getMutableDeclSpec().getAttributes().getListRef());
    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.getAttrListRef(),
    475                        declarator.getTypeObject(innermost).getAttrListRef());
    476     return;
    477   }
    478 
    479   // Otherwise, diagnose when we're done building the type.
    480   spliceAttrOutOfList(attr, declarator.getAttrListRef());
    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                                        AttributeList &attr,
    490                                        QualType type) {
    491   Declarator &declarator = state.getDeclarator();
    492 
    493   // Try to push the attribute from the return type of a function to
    494   // the function itself.
    495   for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
    496     DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
    497     switch (chunk.Kind) {
    498     case DeclaratorChunk::Function:
    499       moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
    500                              chunk.getAttrListRef());
    501       return;
    502 
    503     case DeclaratorChunk::Paren:
    504     case DeclaratorChunk::Pointer:
    505     case DeclaratorChunk::BlockPointer:
    506     case DeclaratorChunk::Array:
    507     case DeclaratorChunk::Reference:
    508     case DeclaratorChunk::MemberPointer:
    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
    520 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
    521                                       AttributeList &attr,
    522                                       AttributeList *&attrList,
    523                                       QualType &declSpecType) {
    524   Declarator &declarator = state.getDeclarator();
    525 
    526   // Put it on the innermost function chunk, if there is one.
    527   for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
    528     DeclaratorChunk &chunk = declarator.getTypeObject(i);
    529     if (chunk.Kind != DeclaratorChunk::Function) continue;
    530 
    531     moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
    532     return true;
    533   }
    534 
    535   if (handleFunctionTypeAttr(state, attr, declSpecType)) {
    536     spliceAttrOutOfList(attr, attrList);
    537     return true;
    538   }
    539 
    540   return false;
    541 }
    542 
    543 /// A function type attribute was written in the decl spec.  Try to
    544 /// apply it somewhere.
    545 static void
    546 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
    547                                        AttributeList &attr,
    548                                        QualType &declSpecType) {
    549   state.saveDeclSpecAttrs();
    550 
    551   // C++11 attributes before the decl specifiers actually appertain to
    552   // the declarators. Move them straight there. We don't support the
    553   // 'put them wherever you like' semantics we allow for GNU attributes.
    554   if (attr.isCXX11Attribute()) {
    555     moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
    556                            state.getDeclarator().getAttrListRef());
    557     return;
    558   }
    559 
    560   // Try to distribute to the innermost.
    561   if (distributeFunctionTypeAttrToInnermost(state, attr,
    562                                             state.getCurrentAttrListRef(),
    563                                             declSpecType))
    564     return;
    565 
    566   // If that failed, diagnose the bad attribute when the declarator is
    567   // fully built.
    568   state.addIgnoredTypeAttr(attr);
    569 }
    570 
    571 /// A function type attribute was written on the declarator.  Try to
    572 /// apply it somewhere.
    573 static void
    574 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
    575                                          AttributeList &attr,
    576                                          QualType &declSpecType) {
    577   Declarator &declarator = state.getDeclarator();
    578 
    579   // Try to distribute to the innermost.
    580   if (distributeFunctionTypeAttrToInnermost(state, attr,
    581                                             declarator.getAttrListRef(),
    582                                             declSpecType))
    583     return;
    584 
    585   // If that failed, diagnose the bad attribute when the declarator is
    586   // fully built.
    587   spliceAttrOutOfList(attr, declarator.getAttrListRef());
    588   state.addIgnoredTypeAttr(attr);
    589 }
    590 
    591 /// \brief Given that there are attributes written on the declarator
    592 /// itself, try to distribute any type attributes to the appropriate
    593 /// declarator chunk.
    594 ///
    595 /// These are attributes like the following:
    596 ///   int f ATTR;
    597 ///   int (f ATTR)();
    598 /// but not necessarily this:
    599 ///   int f() ATTR;
    600 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
    601                                               QualType &declSpecType) {
    602   // Collect all the type attributes from the declarator itself.
    603   assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
    604   AttributeList *attr = state.getDeclarator().getAttributes();
    605   AttributeList *next;
    606   do {
    607     next = attr->getNext();
    608 
    609     // Do not distribute C++11 attributes. They have strict rules for what
    610     // they appertain to.
    611     if (attr->isCXX11Attribute())
    612       continue;
    613 
    614     switch (attr->getKind()) {
    615     OBJC_POINTER_TYPE_ATTRS_CASELIST:
    616       distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
    617       break;
    618 
    619     case AttributeList::AT_NSReturnsRetained:
    620       if (!state.getSema().getLangOpts().ObjCAutoRefCount)
    621         break;
    622       // fallthrough
    623 
    624     FUNCTION_TYPE_ATTRS_CASELIST:
    625       distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
    626       break;
    627 
    628     default:
    629       break;
    630     }
    631   } while ((attr = next));
    632 }
    633 
    634 /// Add a synthetic '()' to a block-literal declarator if it is
    635 /// required, given the return type.
    636 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
    637                                           QualType declSpecType) {
    638   Declarator &declarator = state.getDeclarator();
    639 
    640   // First, check whether the declarator would produce a function,
    641   // i.e. whether the innermost semantic chunk is a function.
    642   if (declarator.isFunctionDeclarator()) {
    643     // If so, make that declarator a prototyped declarator.
    644     declarator.getFunctionTypeInfo().hasPrototype = true;
    645     return;
    646   }
    647 
    648   // If there are any type objects, the type as written won't name a
    649   // function, regardless of the decl spec type.  This is because a
    650   // block signature declarator is always an abstract-declarator, and
    651   // abstract-declarators can't just be parentheses chunks.  Therefore
    652   // we need to build a function chunk unless there are no type
    653   // objects and the decl spec type is a function.
    654   if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
    655     return;
    656 
    657   // Note that there *are* cases with invalid declarators where
    658   // declarators consist solely of parentheses.  In general, these
    659   // occur only in failed efforts to make function declarators, so
    660   // faking up the function chunk is still the right thing to do.
    661 
    662   // Otherwise, we need to fake up a function declarator.
    663   SourceLocation loc = declarator.getLocStart();
    664 
    665   // ...and *prepend* it to the declarator.
    666   SourceLocation NoLoc;
    667   declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
    668                              /*HasProto=*/true,
    669                              /*IsAmbiguous=*/false,
    670                              /*LParenLoc=*/NoLoc,
    671                              /*ArgInfo=*/0,
    672                              /*NumArgs=*/0,
    673                              /*EllipsisLoc=*/NoLoc,
    674                              /*RParenLoc=*/NoLoc,
    675                              /*TypeQuals=*/0,
    676                              /*RefQualifierIsLvalueRef=*/true,
    677                              /*RefQualifierLoc=*/NoLoc,
    678                              /*ConstQualifierLoc=*/NoLoc,
    679                              /*VolatileQualifierLoc=*/NoLoc,
    680                              /*MutableLoc=*/NoLoc,
    681                              EST_None,
    682                              /*ESpecLoc=*/NoLoc,
    683                              /*Exceptions=*/0,
    684                              /*ExceptionRanges=*/0,
    685                              /*NumExceptions=*/0,
    686                              /*NoexceptExpr=*/0,
    687                              loc, loc, declarator));
    688 
    689   // For consistency, make sure the state still has us as processing
    690   // the decl spec.
    691   assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
    692   state.setCurrentChunkIndex(declarator.getNumTypeObjects());
    693 }
    694 
    695 /// \brief Convert the specified declspec to the appropriate type
    696 /// object.
    697 /// \param state Specifies the declarator containing the declaration specifier
    698 /// to be converted, along with other associated processing state.
    699 /// \returns The type described by the declaration specifiers.  This function
    700 /// never returns null.
    701 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
    702   // FIXME: Should move the logic from DeclSpec::Finish to here for validity
    703   // checking.
    704 
    705   Sema &S = state.getSema();
    706   Declarator &declarator = state.getDeclarator();
    707   const DeclSpec &DS = declarator.getDeclSpec();
    708   SourceLocation DeclLoc = declarator.getIdentifierLoc();
    709   if (DeclLoc.isInvalid())
    710     DeclLoc = DS.getLocStart();
    711 
    712   ASTContext &Context = S.Context;
    713 
    714   QualType Result;
    715   switch (DS.getTypeSpecType()) {
    716   case DeclSpec::TST_void:
    717     Result = Context.VoidTy;
    718     break;
    719   case DeclSpec::TST_char:
    720     if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
    721       Result = Context.CharTy;
    722     else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
    723       Result = Context.SignedCharTy;
    724     else {
    725       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
    726              "Unknown TSS value");
    727       Result = Context.UnsignedCharTy;
    728     }
    729     break;
    730   case DeclSpec::TST_wchar:
    731     if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
    732       Result = Context.WCharTy;
    733     else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
    734       S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
    735         << DS.getSpecifierName(DS.getTypeSpecType());
    736       Result = Context.getSignedWCharType();
    737     } else {
    738       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
    739         "Unknown TSS value");
    740       S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
    741         << DS.getSpecifierName(DS.getTypeSpecType());
    742       Result = Context.getUnsignedWCharType();
    743     }
    744     break;
    745   case DeclSpec::TST_char16:
    746       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
    747         "Unknown TSS value");
    748       Result = Context.Char16Ty;
    749     break;
    750   case DeclSpec::TST_char32:
    751       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
    752         "Unknown TSS value");
    753       Result = Context.Char32Ty;
    754     break;
    755   case DeclSpec::TST_unspecified:
    756     // "<proto1,proto2>" is an objc qualified ID with a missing id.
    757     if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
    758       Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
    759                                          (ObjCProtocolDecl*const*)PQ,
    760                                          DS.getNumProtocolQualifiers());
    761       Result = Context.getObjCObjectPointerType(Result);
    762       break;
    763     }
    764 
    765     // If this is a missing declspec in a block literal return context, then it
    766     // is inferred from the return statements inside the block.
    767     // The declspec is always missing in a lambda expr context; it is either
    768     // specified with a trailing return type or inferred.
    769     if (declarator.getContext() == Declarator::LambdaExprContext ||
    770         isOmittedBlockReturnType(declarator)) {
    771       Result = Context.DependentTy;
    772       break;
    773     }
    774 
    775     // Unspecified typespec defaults to int in C90.  However, the C90 grammar
    776     // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
    777     // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
    778     // Note that the one exception to this is function definitions, which are
    779     // allowed to be completely missing a declspec.  This is handled in the
    780     // parser already though by it pretending to have seen an 'int' in this
    781     // case.
    782     if (S.getLangOpts().ImplicitInt) {
    783       // In C89 mode, we only warn if there is a completely missing declspec
    784       // when one is not allowed.
    785       if (DS.isEmpty()) {
    786         S.Diag(DeclLoc, diag::ext_missing_declspec)
    787           << DS.getSourceRange()
    788         << FixItHint::CreateInsertion(DS.getLocStart(), "int");
    789       }
    790     } else if (!DS.hasTypeSpecifier()) {
    791       // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
    792       // "At least one type specifier shall be given in the declaration
    793       // specifiers in each declaration, and in the specifier-qualifier list in
    794       // each struct declaration and type name."
    795       // FIXME: Does Microsoft really have the implicit int extension in C++?
    796       if (S.getLangOpts().CPlusPlus &&
    797           !S.getLangOpts().MicrosoftExt) {
    798         S.Diag(DeclLoc, diag::err_missing_type_specifier)
    799           << DS.getSourceRange();
    800 
    801         // When this occurs in C++ code, often something is very broken with the
    802         // value being declared, poison it as invalid so we don't get chains of
    803         // errors.
    804         declarator.setInvalidType(true);
    805       } else {
    806         S.Diag(DeclLoc, diag::ext_missing_type_specifier)
    807           << DS.getSourceRange();
    808       }
    809     }
    810 
    811     // FALL THROUGH.
    812   case DeclSpec::TST_int: {
    813     if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
    814       switch (DS.getTypeSpecWidth()) {
    815       case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
    816       case DeclSpec::TSW_short:       Result = Context.ShortTy; break;
    817       case DeclSpec::TSW_long:        Result = Context.LongTy; break;
    818       case DeclSpec::TSW_longlong:
    819         Result = Context.LongLongTy;
    820 
    821         // 'long long' is a C99 or C++11 feature.
    822         if (!S.getLangOpts().C99) {
    823           if (S.getLangOpts().CPlusPlus)
    824             S.Diag(DS.getTypeSpecWidthLoc(),
    825                    S.getLangOpts().CPlusPlus11 ?
    826                    diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
    827           else
    828             S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
    829         }
    830         break;
    831       }
    832     } else {
    833       switch (DS.getTypeSpecWidth()) {
    834       case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
    835       case DeclSpec::TSW_short:       Result = Context.UnsignedShortTy; break;
    836       case DeclSpec::TSW_long:        Result = Context.UnsignedLongTy; break;
    837       case DeclSpec::TSW_longlong:
    838         Result = Context.UnsignedLongLongTy;
    839 
    840         // 'long long' is a C99 or C++11 feature.
    841         if (!S.getLangOpts().C99) {
    842           if (S.getLangOpts().CPlusPlus)
    843             S.Diag(DS.getTypeSpecWidthLoc(),
    844                    S.getLangOpts().CPlusPlus11 ?
    845                    diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
    846           else
    847             S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
    848         }
    849         break;
    850       }
    851     }
    852     break;
    853   }
    854   case DeclSpec::TST_int128:
    855     if (!S.PP.getTargetInfo().hasInt128Type())
    856       S.Diag(DS.getTypeSpecTypeLoc(), diag::err_int128_unsupported);
    857     if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
    858       Result = Context.UnsignedInt128Ty;
    859     else
    860       Result = Context.Int128Ty;
    861     break;
    862   case DeclSpec::TST_half: Result = Context.HalfTy; break;
    863   case DeclSpec::TST_float: Result = Context.FloatTy; break;
    864   case DeclSpec::TST_double:
    865     if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
    866       Result = Context.LongDoubleTy;
    867     else
    868       Result = Context.DoubleTy;
    869 
    870     if (S.getLangOpts().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) {
    871       S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64);
    872       declarator.setInvalidType(true);
    873     }
    874     break;
    875   case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
    876   case DeclSpec::TST_decimal32:    // _Decimal32
    877   case DeclSpec::TST_decimal64:    // _Decimal64
    878   case DeclSpec::TST_decimal128:   // _Decimal128
    879     S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
    880     Result = Context.IntTy;
    881     declarator.setInvalidType(true);
    882     break;
    883   case DeclSpec::TST_class:
    884   case DeclSpec::TST_enum:
    885   case DeclSpec::TST_union:
    886   case DeclSpec::TST_struct:
    887   case DeclSpec::TST_interface: {
    888     TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
    889     if (!D) {
    890       // This can happen in C++ with ambiguous lookups.
    891       Result = Context.IntTy;
    892       declarator.setInvalidType(true);
    893       break;
    894     }
    895 
    896     // If the type is deprecated or unavailable, diagnose it.
    897     S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
    898 
    899     assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
    900            DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
    901 
    902     // TypeQuals handled by caller.
    903     Result = Context.getTypeDeclType(D);
    904 
    905     // In both C and C++, make an ElaboratedType.
    906     ElaboratedTypeKeyword Keyword
    907       = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
    908     Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
    909     break;
    910   }
    911   case DeclSpec::TST_typename: {
    912     assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
    913            DS.getTypeSpecSign() == 0 &&
    914            "Can't handle qualifiers on typedef names yet!");
    915     Result = S.GetTypeFromParser(DS.getRepAsType());
    916     if (Result.isNull())
    917       declarator.setInvalidType(true);
    918     else if (DeclSpec::ProtocolQualifierListTy PQ
    919                = DS.getProtocolQualifiers()) {
    920       if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
    921         // Silently drop any existing protocol qualifiers.
    922         // TODO: determine whether that's the right thing to do.
    923         if (ObjT->getNumProtocols())
    924           Result = ObjT->getBaseType();
    925 
    926         if (DS.getNumProtocolQualifiers())
    927           Result = Context.getObjCObjectType(Result,
    928                                              (ObjCProtocolDecl*const*) PQ,
    929                                              DS.getNumProtocolQualifiers());
    930       } else if (Result->isObjCIdType()) {
    931         // id<protocol-list>
    932         Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
    933                                            (ObjCProtocolDecl*const*) PQ,
    934                                            DS.getNumProtocolQualifiers());
    935         Result = Context.getObjCObjectPointerType(Result);
    936       } else if (Result->isObjCClassType()) {
    937         // Class<protocol-list>
    938         Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
    939                                            (ObjCProtocolDecl*const*) PQ,
    940                                            DS.getNumProtocolQualifiers());
    941         Result = Context.getObjCObjectPointerType(Result);
    942       } else {
    943         S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
    944           << DS.getSourceRange();
    945         declarator.setInvalidType(true);
    946       }
    947     }
    948 
    949     // TypeQuals handled by caller.
    950     break;
    951   }
    952   case DeclSpec::TST_typeofType:
    953     // FIXME: Preserve type source info.
    954     Result = S.GetTypeFromParser(DS.getRepAsType());
    955     assert(!Result.isNull() && "Didn't get a type for typeof?");
    956     if (!Result->isDependentType())
    957       if (const TagType *TT = Result->getAs<TagType>())
    958         S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
    959     // TypeQuals handled by caller.
    960     Result = Context.getTypeOfType(Result);
    961     break;
    962   case DeclSpec::TST_typeofExpr: {
    963     Expr *E = DS.getRepAsExpr();
    964     assert(E && "Didn't get an expression for typeof?");
    965     // TypeQuals handled by caller.
    966     Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
    967     if (Result.isNull()) {
    968       Result = Context.IntTy;
    969       declarator.setInvalidType(true);
    970     }
    971     break;
    972   }
    973   case DeclSpec::TST_decltype: {
    974     Expr *E = DS.getRepAsExpr();
    975     assert(E && "Didn't get an expression for decltype?");
    976     // TypeQuals handled by caller.
    977     Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
    978     if (Result.isNull()) {
    979       Result = Context.IntTy;
    980       declarator.setInvalidType(true);
    981     }
    982     break;
    983   }
    984   case DeclSpec::TST_underlyingType:
    985     Result = S.GetTypeFromParser(DS.getRepAsType());
    986     assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
    987     Result = S.BuildUnaryTransformType(Result,
    988                                        UnaryTransformType::EnumUnderlyingType,
    989                                        DS.getTypeSpecTypeLoc());
    990     if (Result.isNull()) {
    991       Result = Context.IntTy;
    992       declarator.setInvalidType(true);
    993     }
    994     break;
    995 
    996   case DeclSpec::TST_auto: {
    997     // TypeQuals handled by caller.
    998     Result = Context.getAutoType(QualType());
    999     break;
   1000   }
   1001 
   1002   case DeclSpec::TST_unknown_anytype:
   1003     Result = Context.UnknownAnyTy;
   1004     break;
   1005 
   1006   case DeclSpec::TST_atomic:
   1007     Result = S.GetTypeFromParser(DS.getRepAsType());
   1008     assert(!Result.isNull() && "Didn't get a type for _Atomic?");
   1009     Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
   1010     if (Result.isNull()) {
   1011       Result = Context.IntTy;
   1012       declarator.setInvalidType(true);
   1013     }
   1014     break;
   1015 
   1016   case DeclSpec::TST_image1d_t:
   1017     Result = Context.OCLImage1dTy;
   1018     break;
   1019 
   1020   case DeclSpec::TST_image1d_array_t:
   1021     Result = Context.OCLImage1dArrayTy;
   1022     break;
   1023 
   1024   case DeclSpec::TST_image1d_buffer_t:
   1025     Result = Context.OCLImage1dBufferTy;
   1026     break;
   1027 
   1028   case DeclSpec::TST_image2d_t:
   1029     Result = Context.OCLImage2dTy;
   1030     break;
   1031 
   1032   case DeclSpec::TST_image2d_array_t:
   1033     Result = Context.OCLImage2dArrayTy;
   1034     break;
   1035 
   1036   case DeclSpec::TST_image3d_t:
   1037     Result = Context.OCLImage3dTy;
   1038     break;
   1039 
   1040   case DeclSpec::TST_sampler_t:
   1041     Result = Context.OCLSamplerTy;
   1042     break;
   1043 
   1044   case DeclSpec::TST_event_t:
   1045     Result = Context.OCLEventTy;
   1046     break;
   1047 
   1048   case DeclSpec::TST_error:
   1049     Result = Context.IntTy;
   1050     declarator.setInvalidType(true);
   1051     break;
   1052   }
   1053 
   1054   // Handle complex types.
   1055   if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
   1056     if (S.getLangOpts().Freestanding)
   1057       S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
   1058     Result = Context.getComplexType(Result);
   1059   } else if (DS.isTypeAltiVecVector()) {
   1060     unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
   1061     assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
   1062     VectorType::VectorKind VecKind = VectorType::AltiVecVector;
   1063     if (DS.isTypeAltiVecPixel())
   1064       VecKind = VectorType::AltiVecPixel;
   1065     else if (DS.isTypeAltiVecBool())
   1066       VecKind = VectorType::AltiVecBool;
   1067     Result = Context.getVectorType(Result, 128/typeSize, VecKind);
   1068   }
   1069 
   1070   // FIXME: Imaginary.
   1071   if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
   1072     S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
   1073 
   1074   // Before we process any type attributes, synthesize a block literal
   1075   // function declarator if necessary.
   1076   if (declarator.getContext() == Declarator::BlockLiteralContext)
   1077     maybeSynthesizeBlockSignature(state, Result);
   1078 
   1079   // Apply any type attributes from the decl spec.  This may cause the
   1080   // list of type attributes to be temporarily saved while the type
   1081   // attributes are pushed around.
   1082   if (AttributeList *attrs = DS.getAttributes().getList())
   1083     processTypeAttrs(state, Result, TAL_DeclSpec, attrs);
   1084 
   1085   // Apply const/volatile/restrict qualifiers to T.
   1086   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
   1087 
   1088     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
   1089     // or incomplete types shall not be restrict-qualified."  C++ also allows
   1090     // restrict-qualified references.
   1091     if (TypeQuals & DeclSpec::TQ_restrict) {
   1092       if (Result->isAnyPointerType() || Result->isReferenceType()) {
   1093         QualType EltTy;
   1094         if (Result->isObjCObjectPointerType())
   1095           EltTy = Result;
   1096         else
   1097           EltTy = Result->isPointerType() ?
   1098                     Result->getAs<PointerType>()->getPointeeType() :
   1099                     Result->getAs<ReferenceType>()->getPointeeType();
   1100 
   1101         // If we have a pointer or reference, the pointee must have an object
   1102         // incomplete type.
   1103         if (!EltTy->isIncompleteOrObjectType()) {
   1104           S.Diag(DS.getRestrictSpecLoc(),
   1105                diag::err_typecheck_invalid_restrict_invalid_pointee)
   1106             << EltTy << DS.getSourceRange();
   1107           TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
   1108         }
   1109       } else {
   1110         S.Diag(DS.getRestrictSpecLoc(),
   1111                diag::err_typecheck_invalid_restrict_not_pointer)
   1112           << Result << DS.getSourceRange();
   1113         TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
   1114       }
   1115     }
   1116 
   1117     // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
   1118     // of a function type includes any type qualifiers, the behavior is
   1119     // undefined."
   1120     if (Result->isFunctionType() && TypeQuals) {
   1121       // Get some location to point at, either the C or V location.
   1122       SourceLocation Loc;
   1123       if (TypeQuals & DeclSpec::TQ_const)
   1124         Loc = DS.getConstSpecLoc();
   1125       else if (TypeQuals & DeclSpec::TQ_volatile)
   1126         Loc = DS.getVolatileSpecLoc();
   1127       else {
   1128         assert((TypeQuals & DeclSpec::TQ_restrict) &&
   1129                "Has CVR quals but not C, V, or R?");
   1130         Loc = DS.getRestrictSpecLoc();
   1131       }
   1132       S.Diag(Loc, diag::warn_typecheck_function_qualifiers)
   1133         << Result << DS.getSourceRange();
   1134     }
   1135 
   1136     // C++ [dcl.ref]p1:
   1137     //   Cv-qualified references are ill-formed except when the
   1138     //   cv-qualifiers are introduced through the use of a typedef
   1139     //   (7.1.3) or of a template type argument (14.3), in which
   1140     //   case the cv-qualifiers are ignored.
   1141     // FIXME: Shouldn't we be checking SCS_typedef here?
   1142     if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
   1143         TypeQuals && Result->isReferenceType()) {
   1144       TypeQuals &= ~DeclSpec::TQ_const;
   1145       TypeQuals &= ~DeclSpec::TQ_volatile;
   1146     }
   1147 
   1148     // C90 6.5.3 constraints: "The same type qualifier shall not appear more
   1149     // than once in the same specifier-list or qualifier-list, either directly
   1150     // or via one or more typedefs."
   1151     if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
   1152         && TypeQuals & Result.getCVRQualifiers()) {
   1153       if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
   1154         S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
   1155           << "const";
   1156       }
   1157 
   1158       if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
   1159         S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
   1160           << "volatile";
   1161       }
   1162 
   1163       // C90 doesn't have restrict, so it doesn't force us to produce a warning
   1164       // in this case.
   1165     }
   1166 
   1167     Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals);
   1168     Result = Context.getQualifiedType(Result, Quals);
   1169   }
   1170 
   1171   return Result;
   1172 }
   1173 
   1174 static std::string getPrintableNameForEntity(DeclarationName Entity) {
   1175   if (Entity)
   1176     return Entity.getAsString();
   1177 
   1178   return "type name";
   1179 }
   1180 
   1181 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
   1182                                   Qualifiers Qs) {
   1183   // Enforce C99 6.7.3p2: "Types other than pointer types derived from
   1184   // object or incomplete types shall not be restrict-qualified."
   1185   if (Qs.hasRestrict()) {
   1186     unsigned DiagID = 0;
   1187     QualType ProblemTy;
   1188 
   1189     const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
   1190     if (const ReferenceType *RTy = dyn_cast<ReferenceType>(Ty)) {
   1191       if (!RTy->getPointeeType()->isIncompleteOrObjectType()) {
   1192         DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
   1193         ProblemTy = T->getAs<ReferenceType>()->getPointeeType();
   1194       }
   1195     } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
   1196       if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
   1197         DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
   1198         ProblemTy = T->getAs<PointerType>()->getPointeeType();
   1199       }
   1200     } else if (const MemberPointerType *PTy = dyn_cast<MemberPointerType>(Ty)) {
   1201       if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
   1202         DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
   1203         ProblemTy = T->getAs<PointerType>()->getPointeeType();
   1204       }
   1205     } else if (!Ty->isDependentType()) {
   1206       // FIXME: this deserves a proper diagnostic
   1207       DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
   1208       ProblemTy = T;
   1209     }
   1210 
   1211     if (DiagID) {
   1212       Diag(Loc, DiagID) << ProblemTy;
   1213       Qs.removeRestrict();
   1214     }
   1215   }
   1216 
   1217   return Context.getQualifiedType(T, Qs);
   1218 }
   1219 
   1220 /// \brief Build a paren type including \p T.
   1221 QualType Sema::BuildParenType(QualType T) {
   1222   return Context.getParenType(T);
   1223 }
   1224 
   1225 /// Given that we're building a pointer or reference to the given
   1226 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
   1227                                            SourceLocation loc,
   1228                                            bool isReference) {
   1229   // Bail out if retention is unrequired or already specified.
   1230   if (!type->isObjCLifetimeType() ||
   1231       type.getObjCLifetime() != Qualifiers::OCL_None)
   1232     return type;
   1233 
   1234   Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
   1235 
   1236   // If the object type is const-qualified, we can safely use
   1237   // __unsafe_unretained.  This is safe (because there are no read
   1238   // barriers), and it'll be safe to coerce anything but __weak* to
   1239   // the resulting type.
   1240   if (type.isConstQualified()) {
   1241     implicitLifetime = Qualifiers::OCL_ExplicitNone;
   1242 
   1243   // Otherwise, check whether the static type does not require
   1244   // retaining.  This currently only triggers for Class (possibly
   1245   // protocol-qualifed, and arrays thereof).
   1246   } else if (type->isObjCARCImplicitlyUnretainedType()) {
   1247     implicitLifetime = Qualifiers::OCL_ExplicitNone;
   1248 
   1249   // If we are in an unevaluated context, like sizeof, skip adding a
   1250   // qualification.
   1251   } else if (S.isUnevaluatedContext()) {
   1252     return type;
   1253 
   1254   // If that failed, give an error and recover using __strong.  __strong
   1255   // is the option most likely to prevent spurious second-order diagnostics,
   1256   // like when binding a reference to a field.
   1257   } else {
   1258     // These types can show up in private ivars in system headers, so
   1259     // we need this to not be an error in those cases.  Instead we
   1260     // want to delay.
   1261     if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
   1262       S.DelayedDiagnostics.add(
   1263           sema::DelayedDiagnostic::makeForbiddenType(loc,
   1264               diag::err_arc_indirect_no_ownership, type, isReference));
   1265     } else {
   1266       S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
   1267     }
   1268     implicitLifetime = Qualifiers::OCL_Strong;
   1269   }
   1270   assert(implicitLifetime && "didn't infer any lifetime!");
   1271 
   1272   Qualifiers qs;
   1273   qs.addObjCLifetime(implicitLifetime);
   1274   return S.Context.getQualifiedType(type, qs);
   1275 }
   1276 
   1277 /// \brief Build a pointer type.
   1278 ///
   1279 /// \param T The type to which we'll be building a pointer.
   1280 ///
   1281 /// \param Loc The location of the entity whose type involves this
   1282 /// pointer type or, if there is no such entity, the location of the
   1283 /// type that will have pointer type.
   1284 ///
   1285 /// \param Entity The name of the entity that involves the pointer
   1286 /// type, if known.
   1287 ///
   1288 /// \returns A suitable pointer type, if there are no
   1289 /// errors. Otherwise, returns a NULL type.
   1290 QualType Sema::BuildPointerType(QualType T,
   1291                                 SourceLocation Loc, DeclarationName Entity) {
   1292   if (T->isReferenceType()) {
   1293     // C++ 8.3.2p4: There shall be no ... pointers to references ...
   1294     Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
   1295       << getPrintableNameForEntity(Entity) << T;
   1296     return QualType();
   1297   }
   1298 
   1299   assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
   1300 
   1301   // In ARC, it is forbidden to build pointers to unqualified pointers.
   1302   if (getLangOpts().ObjCAutoRefCount)
   1303     T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
   1304 
   1305   // Build the pointer type.
   1306   return Context.getPointerType(T);
   1307 }
   1308 
   1309 /// \brief Build a reference type.
   1310 ///
   1311 /// \param T The type to which we'll be building a reference.
   1312 ///
   1313 /// \param Loc The location of the entity whose type involves this
   1314 /// reference type or, if there is no such entity, the location of the
   1315 /// type that will have reference type.
   1316 ///
   1317 /// \param Entity The name of the entity that involves the reference
   1318 /// type, if known.
   1319 ///
   1320 /// \returns A suitable reference type, if there are no
   1321 /// errors. Otherwise, returns a NULL type.
   1322 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
   1323                                   SourceLocation Loc,
   1324                                   DeclarationName Entity) {
   1325   assert(Context.getCanonicalType(T) != Context.OverloadTy &&
   1326          "Unresolved overloaded function type");
   1327 
   1328   // C++0x [dcl.ref]p6:
   1329   //   If a typedef (7.1.3), a type template-parameter (14.3.1), or a
   1330   //   decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
   1331   //   type T, an attempt to create the type "lvalue reference to cv TR" creates
   1332   //   the type "lvalue reference to T", while an attempt to create the type
   1333   //   "rvalue reference to cv TR" creates the type TR.
   1334   bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
   1335 
   1336   // C++ [dcl.ref]p4: There shall be no references to references.
   1337   //
   1338   // According to C++ DR 106, references to references are only
   1339   // diagnosed when they are written directly (e.g., "int & &"),
   1340   // but not when they happen via a typedef:
   1341   //
   1342   //   typedef int& intref;
   1343   //   typedef intref& intref2;
   1344   //
   1345   // Parser::ParseDeclaratorInternal diagnoses the case where
   1346   // references are written directly; here, we handle the
   1347   // collapsing of references-to-references as described in C++0x.
   1348   // DR 106 and 540 introduce reference-collapsing into C++98/03.
   1349 
   1350   // C++ [dcl.ref]p1:
   1351   //   A declarator that specifies the type "reference to cv void"
   1352   //   is ill-formed.
   1353   if (T->isVoidType()) {
   1354     Diag(Loc, diag::err_reference_to_void);
   1355     return QualType();
   1356   }
   1357 
   1358   // In ARC, it is forbidden to build references to unqualified pointers.
   1359   if (getLangOpts().ObjCAutoRefCount)
   1360     T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
   1361 
   1362   // Handle restrict on references.
   1363   if (LValueRef)
   1364     return Context.getLValueReferenceType(T, SpelledAsLValue);
   1365   return Context.getRValueReferenceType(T);
   1366 }
   1367 
   1368 /// Check whether the specified array size makes the array type a VLA.  If so,
   1369 /// return true, if not, return the size of the array in SizeVal.
   1370 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
   1371   // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
   1372   // (like gnu99, but not c99) accept any evaluatable value as an extension.
   1373   class VLADiagnoser : public Sema::VerifyICEDiagnoser {
   1374   public:
   1375     VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
   1376 
   1377     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
   1378     }
   1379 
   1380     virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) {
   1381       S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
   1382     }
   1383   } Diagnoser;
   1384 
   1385   return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
   1386                                            S.LangOpts.GNUMode).isInvalid();
   1387 }
   1388 
   1389 
   1390 /// \brief Build an array type.
   1391 ///
   1392 /// \param T The type of each element in the array.
   1393 ///
   1394 /// \param ASM C99 array size modifier (e.g., '*', 'static').
   1395 ///
   1396 /// \param ArraySize Expression describing the size of the array.
   1397 ///
   1398 /// \param Brackets The range from the opening '[' to the closing ']'.
   1399 ///
   1400 /// \param Entity The name of the entity that involves the array
   1401 /// type, if known.
   1402 ///
   1403 /// \returns A suitable array type, if there are no errors. Otherwise,
   1404 /// returns a NULL type.
   1405 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
   1406                               Expr *ArraySize, unsigned Quals,
   1407                               SourceRange Brackets, DeclarationName Entity) {
   1408 
   1409   SourceLocation Loc = Brackets.getBegin();
   1410   if (getLangOpts().CPlusPlus) {
   1411     // C++ [dcl.array]p1:
   1412     //   T is called the array element type; this type shall not be a reference
   1413     //   type, the (possibly cv-qualified) type void, a function type or an
   1414     //   abstract class type.
   1415     //
   1416     // C++ [dcl.array]p3:
   1417     //   When several "array of" specifications are adjacent, [...] only the
   1418     //   first of the constant expressions that specify the bounds of the arrays
   1419     //   may be omitted.
   1420     //
   1421     // Note: function types are handled in the common path with C.
   1422     if (T->isReferenceType()) {
   1423       Diag(Loc, diag::err_illegal_decl_array_of_references)
   1424       << getPrintableNameForEntity(Entity) << T;
   1425       return QualType();
   1426     }
   1427 
   1428     if (T->isVoidType() || T->isIncompleteArrayType()) {
   1429       Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
   1430       return QualType();
   1431     }
   1432 
   1433     if (RequireNonAbstractType(Brackets.getBegin(), T,
   1434                                diag::err_array_of_abstract_type))
   1435       return QualType();
   1436 
   1437   } else {
   1438     // C99 6.7.5.2p1: If the element type is an incomplete or function type,
   1439     // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
   1440     if (RequireCompleteType(Loc, T,
   1441                             diag::err_illegal_decl_array_incomplete_type))
   1442       return QualType();
   1443   }
   1444 
   1445   if (T->isFunctionType()) {
   1446     Diag(Loc, diag::err_illegal_decl_array_of_functions)
   1447       << getPrintableNameForEntity(Entity) << T;
   1448     return QualType();
   1449   }
   1450 
   1451   if (T->getContainedAutoType()) {
   1452     Diag(Loc, diag::err_illegal_decl_array_of_auto)
   1453       << getPrintableNameForEntity(Entity) << T;
   1454     return QualType();
   1455   }
   1456 
   1457   if (const RecordType *EltTy = T->getAs<RecordType>()) {
   1458     // If the element type is a struct or union that contains a variadic
   1459     // array, accept it as a GNU extension: C99 6.7.2.1p2.
   1460     if (EltTy->getDecl()->hasFlexibleArrayMember())
   1461       Diag(Loc, diag::ext_flexible_array_in_array) << T;
   1462   } else if (T->isObjCObjectType()) {
   1463     Diag(Loc, diag::err_objc_array_of_interfaces) << T;
   1464     return QualType();
   1465   }
   1466 
   1467   // Do placeholder conversions on the array size expression.
   1468   if (ArraySize && ArraySize->hasPlaceholderType()) {
   1469     ExprResult Result = CheckPlaceholderExpr(ArraySize);
   1470     if (Result.isInvalid()) return QualType();
   1471     ArraySize = Result.take();
   1472   }
   1473 
   1474   // Do lvalue-to-rvalue conversions on the array size expression.
   1475   if (ArraySize && !ArraySize->isRValue()) {
   1476     ExprResult Result = DefaultLvalueConversion(ArraySize);
   1477     if (Result.isInvalid())
   1478       return QualType();
   1479 
   1480     ArraySize = Result.take();
   1481   }
   1482 
   1483   // C99 6.7.5.2p1: The size expression shall have integer type.
   1484   // C++11 allows contextual conversions to such types.
   1485   if (!getLangOpts().CPlusPlus11 &&
   1486       ArraySize && !ArraySize->isTypeDependent() &&
   1487       !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
   1488     Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
   1489       << ArraySize->getType() << ArraySize->getSourceRange();
   1490     return QualType();
   1491   }
   1492 
   1493   llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
   1494   if (!ArraySize) {
   1495     if (ASM == ArrayType::Star)
   1496       T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
   1497     else
   1498       T = Context.getIncompleteArrayType(T, ASM, Quals);
   1499   } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
   1500     T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
   1501   } else if ((!T->isDependentType() && !T->isIncompleteType() &&
   1502               !T->isConstantSizeType()) ||
   1503              isArraySizeVLA(*this, ArraySize, ConstVal)) {
   1504     // Even in C++11, don't allow contextual conversions in the array bound
   1505     // of a VLA.
   1506     if (getLangOpts().CPlusPlus11 &&
   1507         !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
   1508       Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
   1509         << ArraySize->getType() << ArraySize->getSourceRange();
   1510       return QualType();
   1511     }
   1512 
   1513     // C99: an array with an element type that has a non-constant-size is a VLA.
   1514     // C99: an array with a non-ICE size is a VLA.  We accept any expression
   1515     // that we can fold to a non-zero positive value as an extension.
   1516     T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
   1517   } else {
   1518     // C99 6.7.5.2p1: If the expression is a constant expression, it shall
   1519     // have a value greater than zero.
   1520     if (ConstVal.isSigned() && ConstVal.isNegative()) {
   1521       if (Entity)
   1522         Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
   1523           << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
   1524       else
   1525         Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
   1526           << ArraySize->getSourceRange();
   1527       return QualType();
   1528     }
   1529     if (ConstVal == 0) {
   1530       // GCC accepts zero sized static arrays. We allow them when
   1531       // we're not in a SFINAE context.
   1532       Diag(ArraySize->getLocStart(),
   1533            isSFINAEContext()? diag::err_typecheck_zero_array_size
   1534                             : diag::ext_typecheck_zero_array_size)
   1535         << ArraySize->getSourceRange();
   1536 
   1537       if (ASM == ArrayType::Static) {
   1538         Diag(ArraySize->getLocStart(),
   1539              diag::warn_typecheck_zero_static_array_size)
   1540           << ArraySize->getSourceRange();
   1541         ASM = ArrayType::Normal;
   1542       }
   1543     } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
   1544                !T->isIncompleteType()) {
   1545       // Is the array too large?
   1546       unsigned ActiveSizeBits
   1547         = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
   1548       if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
   1549         Diag(ArraySize->getLocStart(), diag::err_array_too_large)
   1550           << ConstVal.toString(10)
   1551           << ArraySize->getSourceRange();
   1552     }
   1553 
   1554     T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
   1555   }
   1556 
   1557   // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
   1558   if (getLangOpts().OpenCL && T->isVariableArrayType()) {
   1559     Diag(Loc, diag::err_opencl_vla);
   1560     return QualType();
   1561   }
   1562   // If this is not C99, extwarn about VLA's and C99 array size modifiers.
   1563   if (!getLangOpts().C99) {
   1564     if (T->isVariableArrayType()) {
   1565       // Prohibit the use of non-POD types in VLAs.
   1566       QualType BaseT = Context.getBaseElementType(T);
   1567       if (!T->isDependentType() &&
   1568           !BaseT.isPODType(Context) &&
   1569           !BaseT->isObjCLifetimeType()) {
   1570         Diag(Loc, diag::err_vla_non_pod)
   1571           << BaseT;
   1572         return QualType();
   1573       }
   1574       // Prohibit the use of VLAs during template argument deduction.
   1575       else if (isSFINAEContext()) {
   1576         Diag(Loc, diag::err_vla_in_sfinae);
   1577         return QualType();
   1578       }
   1579       // Just extwarn about VLAs.
   1580       else
   1581         Diag(Loc, diag::ext_vla);
   1582     } else if (ASM != ArrayType::Normal || Quals != 0)
   1583       Diag(Loc,
   1584            getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
   1585                                      : diag::ext_c99_array_usage) << ASM;
   1586   }
   1587 
   1588   if (T->isVariableArrayType()) {
   1589     // Warn about VLAs for -Wvla.
   1590     Diag(Loc, diag::warn_vla_used);
   1591   }
   1592 
   1593   return T;
   1594 }
   1595 
   1596 /// \brief Build an ext-vector type.
   1597 ///
   1598 /// Run the required checks for the extended vector type.
   1599 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
   1600                                   SourceLocation AttrLoc) {
   1601   // unlike gcc's vector_size attribute, we do not allow vectors to be defined
   1602   // in conjunction with complex types (pointers, arrays, functions, etc.).
   1603   if (!T->isDependentType() &&
   1604       !T->isIntegerType() && !T->isRealFloatingType()) {
   1605     Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
   1606     return QualType();
   1607   }
   1608 
   1609   if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
   1610     llvm::APSInt vecSize(32);
   1611     if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
   1612       Diag(AttrLoc, diag::err_attribute_argument_not_int)
   1613         << "ext_vector_type" << ArraySize->getSourceRange();
   1614       return QualType();
   1615     }
   1616 
   1617     // unlike gcc's vector_size attribute, the size is specified as the
   1618     // number of elements, not the number of bytes.
   1619     unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
   1620 
   1621     if (vectorSize == 0) {
   1622       Diag(AttrLoc, diag::err_attribute_zero_size)
   1623       << ArraySize->getSourceRange();
   1624       return QualType();
   1625     }
   1626 
   1627     return Context.getExtVectorType(T, vectorSize);
   1628   }
   1629 
   1630   return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
   1631 }
   1632 
   1633 QualType Sema::BuildFunctionType(QualType T,
   1634                                  llvm::MutableArrayRef<QualType> ParamTypes,
   1635                                  SourceLocation Loc, DeclarationName Entity,
   1636                                  const FunctionProtoType::ExtProtoInfo &EPI) {
   1637   if (T->isArrayType() || T->isFunctionType()) {
   1638     Diag(Loc, diag::err_func_returning_array_function)
   1639       << T->isFunctionType() << T;
   1640     return QualType();
   1641   }
   1642 
   1643   // Functions cannot return half FP.
   1644   if (T->isHalfType()) {
   1645     Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
   1646       FixItHint::CreateInsertion(Loc, "*");
   1647     return QualType();
   1648   }
   1649 
   1650   bool Invalid = false;
   1651   for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
   1652     // FIXME: Loc is too inprecise here, should use proper locations for args.
   1653     QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
   1654     if (ParamType->isVoidType()) {
   1655       Diag(Loc, diag::err_param_with_void_type);
   1656       Invalid = true;
   1657     } else if (ParamType->isHalfType()) {
   1658       // Disallow half FP arguments.
   1659       Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
   1660         FixItHint::CreateInsertion(Loc, "*");
   1661       Invalid = true;
   1662     }
   1663 
   1664     ParamTypes[Idx] = ParamType;
   1665   }
   1666 
   1667   if (Invalid)
   1668     return QualType();
   1669 
   1670   return Context.getFunctionType(T, ParamTypes, EPI);
   1671 }
   1672 
   1673 /// \brief Build a member pointer type \c T Class::*.
   1674 ///
   1675 /// \param T the type to which the member pointer refers.
   1676 /// \param Class the class type into which the member pointer points.
   1677 /// \param Loc the location where this type begins
   1678 /// \param Entity the name of the entity that will have this member pointer type
   1679 ///
   1680 /// \returns a member pointer type, if successful, or a NULL type if there was
   1681 /// an error.
   1682 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
   1683                                       SourceLocation Loc,
   1684                                       DeclarationName Entity) {
   1685   // Verify that we're not building a pointer to pointer to function with
   1686   // exception specification.
   1687   if (CheckDistantExceptionSpec(T)) {
   1688     Diag(Loc, diag::err_distant_exception_spec);
   1689 
   1690     // FIXME: If we're doing this as part of template instantiation,
   1691     // we should return immediately.
   1692 
   1693     // Build the type anyway, but use the canonical type so that the
   1694     // exception specifiers are stripped off.
   1695     T = Context.getCanonicalType(T);
   1696   }
   1697 
   1698   // C++ 8.3.3p3: A pointer to member shall not point to ... a member
   1699   //   with reference type, or "cv void."
   1700   if (T->isReferenceType()) {
   1701     Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
   1702       << (Entity? Entity.getAsString() : "type name") << T;
   1703     return QualType();
   1704   }
   1705 
   1706   if (T->isVoidType()) {
   1707     Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
   1708       << (Entity? Entity.getAsString() : "type name");
   1709     return QualType();
   1710   }
   1711 
   1712   if (!Class->isDependentType() && !Class->isRecordType()) {
   1713     Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
   1714     return QualType();
   1715   }
   1716 
   1717   // C++ allows the class type in a member pointer to be an incomplete type.
   1718   // In the Microsoft ABI, the size of the member pointer can vary
   1719   // according to the class type, which means that we really need a
   1720   // complete type if possible, which means we need to instantiate templates.
   1721   //
   1722   // For now, just require a complete type, which will instantiate
   1723   // templates.  This will also error if the type is just forward-declared,
   1724   // which is a bug, but it's a bug that saves us from dealing with some
   1725   // complexities at the moment.
   1726   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
   1727       RequireCompleteType(Loc, Class, diag::err_incomplete_type))
   1728     return QualType();
   1729 
   1730   return Context.getMemberPointerType(T, Class.getTypePtr());
   1731 }
   1732 
   1733 /// \brief Build a block pointer type.
   1734 ///
   1735 /// \param T The type to which we'll be building a block pointer.
   1736 ///
   1737 /// \param Loc The source location, used for diagnostics.
   1738 ///
   1739 /// \param Entity The name of the entity that involves the block pointer
   1740 /// type, if known.
   1741 ///
   1742 /// \returns A suitable block pointer type, if there are no
   1743 /// errors. Otherwise, returns a NULL type.
   1744 QualType Sema::BuildBlockPointerType(QualType T,
   1745                                      SourceLocation Loc,
   1746                                      DeclarationName Entity) {
   1747   if (!T->isFunctionType()) {
   1748     Diag(Loc, diag::err_nonfunction_block_type);
   1749     return QualType();
   1750   }
   1751 
   1752   return Context.getBlockPointerType(T);
   1753 }
   1754 
   1755 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
   1756   QualType QT = Ty.get();
   1757   if (QT.isNull()) {
   1758     if (TInfo) *TInfo = 0;
   1759     return QualType();
   1760   }
   1761 
   1762   TypeSourceInfo *DI = 0;
   1763   if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
   1764     QT = LIT->getType();
   1765     DI = LIT->getTypeSourceInfo();
   1766   }
   1767 
   1768   if (TInfo) *TInfo = DI;
   1769   return QT;
   1770 }
   1771 
   1772 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
   1773                                             Qualifiers::ObjCLifetime ownership,
   1774                                             unsigned chunkIndex);
   1775 
   1776 /// Given that this is the declaration of a parameter under ARC,
   1777 /// attempt to infer attributes and such for pointer-to-whatever
   1778 /// types.
   1779 static void inferARCWriteback(TypeProcessingState &state,
   1780                               QualType &declSpecType) {
   1781   Sema &S = state.getSema();
   1782   Declarator &declarator = state.getDeclarator();
   1783 
   1784   // TODO: should we care about decl qualifiers?
   1785 
   1786   // Check whether the declarator has the expected form.  We walk
   1787   // from the inside out in order to make the block logic work.
   1788   unsigned outermostPointerIndex = 0;
   1789   bool isBlockPointer = false;
   1790   unsigned numPointers = 0;
   1791   for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
   1792     unsigned chunkIndex = i;
   1793     DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
   1794     switch (chunk.Kind) {
   1795     case DeclaratorChunk::Paren:
   1796       // Ignore parens.
   1797       break;
   1798 
   1799     case DeclaratorChunk::Reference:
   1800     case DeclaratorChunk::Pointer:
   1801       // Count the number of pointers.  Treat references
   1802       // interchangeably as pointers; if they're mis-ordered, normal
   1803       // type building will discover that.
   1804       outermostPointerIndex = chunkIndex;
   1805       numPointers++;
   1806       break;
   1807 
   1808     case DeclaratorChunk::BlockPointer:
   1809       // If we have a pointer to block pointer, that's an acceptable
   1810       // indirect reference; anything else is not an application of
   1811       // the rules.
   1812       if (numPointers != 1) return;
   1813       numPointers++;
   1814       outermostPointerIndex = chunkIndex;
   1815       isBlockPointer = true;
   1816 
   1817       // We don't care about pointer structure in return values here.
   1818       goto done;
   1819 
   1820     case DeclaratorChunk::Array: // suppress if written (id[])?
   1821     case DeclaratorChunk::Function:
   1822     case DeclaratorChunk::MemberPointer:
   1823       return;
   1824     }
   1825   }
   1826  done:
   1827 
   1828   // If we have *one* pointer, then we want to throw the qualifier on
   1829   // the declaration-specifiers, which means that it needs to be a
   1830   // retainable object type.
   1831   if (numPointers == 1) {
   1832     // If it's not a retainable object type, the rule doesn't apply.
   1833     if (!declSpecType->isObjCRetainableType()) return;
   1834 
   1835     // If it already has lifetime, don't do anything.
   1836     if (declSpecType.getObjCLifetime()) return;
   1837 
   1838     // Otherwise, modify the type in-place.
   1839     Qualifiers qs;
   1840 
   1841     if (declSpecType->isObjCARCImplicitlyUnretainedType())
   1842       qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
   1843     else
   1844       qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
   1845     declSpecType = S.Context.getQualifiedType(declSpecType, qs);
   1846 
   1847   // If we have *two* pointers, then we want to throw the qualifier on
   1848   // the outermost pointer.
   1849   } else if (numPointers == 2) {
   1850     // If we don't have a block pointer, we need to check whether the
   1851     // declaration-specifiers gave us something that will turn into a
   1852     // retainable object pointer after we slap the first pointer on it.
   1853     if (!isBlockPointer && !declSpecType->isObjCObjectType())
   1854       return;
   1855 
   1856     // Look for an explicit lifetime attribute there.
   1857     DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
   1858     if (chunk.Kind != DeclaratorChunk::Pointer &&
   1859         chunk.Kind != DeclaratorChunk::BlockPointer)
   1860       return;
   1861     for (const AttributeList *attr = chunk.getAttrs(); attr;
   1862            attr = attr->getNext())
   1863       if (attr->getKind() == AttributeList::AT_ObjCOwnership)
   1864         return;
   1865 
   1866     transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
   1867                                           outermostPointerIndex);
   1868 
   1869   // Any other number of pointers/references does not trigger the rule.
   1870   } else return;
   1871 
   1872   // TODO: mark whether we did this inference?
   1873 }
   1874 
   1875 static void DiagnoseIgnoredQualifiers(unsigned Quals,
   1876                                       SourceLocation ConstQualLoc,
   1877                                       SourceLocation VolatileQualLoc,
   1878                                       SourceLocation RestrictQualLoc,
   1879                                       Sema& S) {
   1880   std::string QualStr;
   1881   unsigned NumQuals = 0;
   1882   SourceLocation Loc;
   1883 
   1884   FixItHint ConstFixIt;
   1885   FixItHint VolatileFixIt;
   1886   FixItHint RestrictFixIt;
   1887 
   1888   const SourceManager &SM = S.getSourceManager();
   1889 
   1890   // FIXME: The locations here are set kind of arbitrarily. It'd be nicer to
   1891   // find a range and grow it to encompass all the qualifiers, regardless of
   1892   // the order in which they textually appear.
   1893   if (Quals & Qualifiers::Const) {
   1894     ConstFixIt = FixItHint::CreateRemoval(ConstQualLoc);
   1895     QualStr = "const";
   1896     ++NumQuals;
   1897     if (!Loc.isValid() || SM.isBeforeInTranslationUnit(ConstQualLoc, Loc))
   1898       Loc = ConstQualLoc;
   1899   }
   1900   if (Quals & Qualifiers::Volatile) {
   1901     VolatileFixIt = FixItHint::CreateRemoval(VolatileQualLoc);
   1902     QualStr += (NumQuals == 0 ? "volatile" : " volatile");
   1903     ++NumQuals;
   1904     if (!Loc.isValid() || SM.isBeforeInTranslationUnit(VolatileQualLoc, Loc))
   1905       Loc = VolatileQualLoc;
   1906   }
   1907   if (Quals & Qualifiers::Restrict) {
   1908     RestrictFixIt = FixItHint::CreateRemoval(RestrictQualLoc);
   1909     QualStr += (NumQuals == 0 ? "restrict" : " restrict");
   1910     ++NumQuals;
   1911     if (!Loc.isValid() || SM.isBeforeInTranslationUnit(RestrictQualLoc, Loc))
   1912       Loc = RestrictQualLoc;
   1913   }
   1914 
   1915   assert(NumQuals > 0 && "No known qualifiers?");
   1916 
   1917   S.Diag(Loc, diag::warn_qual_return_type)
   1918     << QualStr << NumQuals << ConstFixIt << VolatileFixIt << RestrictFixIt;
   1919 }
   1920 
   1921 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
   1922                                              TypeSourceInfo *&ReturnTypeInfo) {
   1923   Sema &SemaRef = state.getSema();
   1924   Declarator &D = state.getDeclarator();
   1925   QualType T;
   1926   ReturnTypeInfo = 0;
   1927 
   1928   // The TagDecl owned by the DeclSpec.
   1929   TagDecl *OwnedTagDecl = 0;
   1930 
   1931   switch (D.getName().getKind()) {
   1932   case UnqualifiedId::IK_ImplicitSelfParam:
   1933   case UnqualifiedId::IK_OperatorFunctionId:
   1934   case UnqualifiedId::IK_Identifier:
   1935   case UnqualifiedId::IK_LiteralOperatorId:
   1936   case UnqualifiedId::IK_TemplateId:
   1937     T = ConvertDeclSpecToType(state);
   1938 
   1939     if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
   1940       OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
   1941       // Owned declaration is embedded in declarator.
   1942       OwnedTagDecl->setEmbeddedInDeclarator(true);
   1943     }
   1944     break;
   1945 
   1946   case UnqualifiedId::IK_ConstructorName:
   1947   case UnqualifiedId::IK_ConstructorTemplateId:
   1948   case UnqualifiedId::IK_DestructorName:
   1949     // Constructors and destructors don't have return types. Use
   1950     // "void" instead.
   1951     T = SemaRef.Context.VoidTy;
   1952     if (AttributeList *attrs = D.getDeclSpec().getAttributes().getList())
   1953       processTypeAttrs(state, T, TAL_DeclSpec, attrs);
   1954     break;
   1955 
   1956   case UnqualifiedId::IK_ConversionFunctionId:
   1957     // The result type of a conversion function is the type that it
   1958     // converts to.
   1959     T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
   1960                                   &ReturnTypeInfo);
   1961     break;
   1962   }
   1963 
   1964   if (D.getAttributes())
   1965     distributeTypeAttrsFromDeclarator(state, T);
   1966 
   1967   // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
   1968   // In C++11, a function declarator using 'auto' must have a trailing return
   1969   // type (this is checked later) and we can skip this. In other languages
   1970   // using auto, we need to check regardless.
   1971   if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
   1972       (!SemaRef.getLangOpts().CPlusPlus11 || !D.isFunctionDeclarator())) {
   1973     int Error = -1;
   1974 
   1975     switch (D.getContext()) {
   1976     case Declarator::KNRTypeListContext:
   1977       llvm_unreachable("K&R type lists aren't allowed in C++");
   1978     case Declarator::LambdaExprContext:
   1979       llvm_unreachable("Can't specify a type specifier in lambda grammar");
   1980     case Declarator::ObjCParameterContext:
   1981     case Declarator::ObjCResultContext:
   1982     case Declarator::PrototypeContext:
   1983       Error = 0; // Function prototype
   1984       break;
   1985     case Declarator::MemberContext:
   1986       if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
   1987         break;
   1988       switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
   1989       case TTK_Enum: llvm_unreachable("unhandled tag kind");
   1990       case TTK_Struct: Error = 1; /* Struct member */ break;
   1991       case TTK_Union:  Error = 2; /* Union member */ break;
   1992       case TTK_Class:  Error = 3; /* Class member */ break;
   1993       case TTK_Interface: Error = 4; /* Interface member */ break;
   1994       }
   1995       break;
   1996     case Declarator::CXXCatchContext:
   1997     case Declarator::ObjCCatchContext:
   1998       Error = 5; // Exception declaration
   1999       break;
   2000     case Declarator::TemplateParamContext:
   2001       Error = 6; // Template parameter
   2002       break;
   2003     case Declarator::BlockLiteralContext:
   2004       Error = 7; // Block literal
   2005       break;
   2006     case Declarator::TemplateTypeArgContext:
   2007       Error = 8; // Template type argument
   2008       break;
   2009     case Declarator::AliasDeclContext:
   2010     case Declarator::AliasTemplateContext:
   2011       Error = 10; // Type alias
   2012       break;
   2013     case Declarator::TrailingReturnContext:
   2014       Error = 11; // Function return type
   2015       break;
   2016     case Declarator::TypeNameContext:
   2017       Error = 12; // Generic
   2018       break;
   2019     case Declarator::FileContext:
   2020     case Declarator::BlockContext:
   2021     case Declarator::ForContext:
   2022     case Declarator::ConditionContext:
   2023     case Declarator::CXXNewContext:
   2024       break;
   2025     }
   2026 
   2027     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
   2028       Error = 9;
   2029 
   2030     // In Objective-C it is an error to use 'auto' on a function declarator.
   2031     if (D.isFunctionDeclarator())
   2032       Error = 11;
   2033 
   2034     // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
   2035     // contains a trailing return type. That is only legal at the outermost
   2036     // level. Check all declarator chunks (outermost first) anyway, to give
   2037     // better diagnostics.
   2038     if (SemaRef.getLangOpts().CPlusPlus11 && Error != -1) {
   2039       for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
   2040         unsigned chunkIndex = e - i - 1;
   2041         state.setCurrentChunkIndex(chunkIndex);
   2042         DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
   2043         if (DeclType.Kind == DeclaratorChunk::Function) {
   2044           const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
   2045           if (FTI.hasTrailingReturnType()) {
   2046             Error = -1;
   2047             break;
   2048           }
   2049         }
   2050       }
   2051     }
   2052 
   2053     if (Error != -1) {
   2054       SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
   2055                    diag::err_auto_not_allowed)
   2056         << Error;
   2057       T = SemaRef.Context.IntTy;
   2058       D.setInvalidType(true);
   2059     } else
   2060       SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
   2061                    diag::warn_cxx98_compat_auto_type_specifier);
   2062   }
   2063 
   2064   if (SemaRef.getLangOpts().CPlusPlus &&
   2065       OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
   2066     // Check the contexts where C++ forbids the declaration of a new class
   2067     // or enumeration in a type-specifier-seq.
   2068     switch (D.getContext()) {
   2069     case Declarator::TrailingReturnContext:
   2070       // Class and enumeration definitions are syntactically not allowed in
   2071       // trailing return types.
   2072       llvm_unreachable("parser should not have allowed this");
   2073       break;
   2074     case Declarator::FileContext:
   2075     case Declarator::MemberContext:
   2076     case Declarator::BlockContext:
   2077     case Declarator::ForContext:
   2078     case Declarator::BlockLiteralContext:
   2079     case Declarator::LambdaExprContext:
   2080       // C++11 [dcl.type]p3:
   2081       //   A type-specifier-seq shall not define a class or enumeration unless
   2082       //   it appears in the type-id of an alias-declaration (7.1.3) that is not
   2083       //   the declaration of a template-declaration.
   2084     case Declarator::AliasDeclContext:
   2085       break;
   2086     case Declarator::AliasTemplateContext:
   2087       SemaRef.Diag(OwnedTagDecl->getLocation(),
   2088              diag::err_type_defined_in_alias_template)
   2089         << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
   2090       D.setInvalidType(true);
   2091       break;
   2092     case Declarator::TypeNameContext:
   2093     case Declarator::TemplateParamContext:
   2094     case Declarator::CXXNewContext:
   2095     case Declarator::CXXCatchContext:
   2096     case Declarator::ObjCCatchContext:
   2097     case Declarator::TemplateTypeArgContext:
   2098       SemaRef.Diag(OwnedTagDecl->getLocation(),
   2099              diag::err_type_defined_in_type_specifier)
   2100         << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
   2101       D.setInvalidType(true);
   2102       break;
   2103     case Declarator::PrototypeContext:
   2104     case Declarator::ObjCParameterContext:
   2105     case Declarator::ObjCResultContext:
   2106     case Declarator::KNRTypeListContext:
   2107       // C++ [dcl.fct]p6:
   2108       //   Types shall not be defined in return or parameter types.
   2109       SemaRef.Diag(OwnedTagDecl->getLocation(),
   2110                    diag::err_type_defined_in_param_type)
   2111         << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
   2112       D.setInvalidType(true);
   2113       break;
   2114     case Declarator::ConditionContext:
   2115       // C++ 6.4p2:
   2116       // The type-specifier-seq shall not contain typedef and shall not declare
   2117       // a new class or enumeration.
   2118       SemaRef.Diag(OwnedTagDecl->getLocation(),
   2119                    diag::err_type_defined_in_condition);
   2120       D.setInvalidType(true);
   2121       break;
   2122     }
   2123   }
   2124 
   2125   return T;
   2126 }
   2127 
   2128 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
   2129   std::string Quals =
   2130     Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
   2131 
   2132   switch (FnTy->getRefQualifier()) {
   2133   case RQ_None:
   2134     break;
   2135 
   2136   case RQ_LValue:
   2137     if (!Quals.empty())
   2138       Quals += ' ';
   2139     Quals += '&';
   2140     break;
   2141 
   2142   case RQ_RValue:
   2143     if (!Quals.empty())
   2144       Quals += ' ';
   2145     Quals += "&&";
   2146     break;
   2147   }
   2148 
   2149   return Quals;
   2150 }
   2151 
   2152 /// Check that the function type T, which has a cv-qualifier or a ref-qualifier,
   2153 /// can be contained within the declarator chunk DeclType, and produce an
   2154 /// appropriate diagnostic if not.
   2155 static void checkQualifiedFunction(Sema &S, QualType T,
   2156                                    DeclaratorChunk &DeclType) {
   2157   // C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: a function type with a
   2158   // cv-qualifier or a ref-qualifier can only appear at the topmost level
   2159   // of a type.
   2160   int DiagKind = -1;
   2161   switch (DeclType.Kind) {
   2162   case DeclaratorChunk::Paren:
   2163   case DeclaratorChunk::MemberPointer:
   2164     // These cases are permitted.
   2165     return;
   2166   case DeclaratorChunk::Array:
   2167   case DeclaratorChunk::Function:
   2168     // These cases don't allow function types at all; no need to diagnose the
   2169     // qualifiers separately.
   2170     return;
   2171   case DeclaratorChunk::BlockPointer:
   2172     DiagKind = 0;
   2173     break;
   2174   case DeclaratorChunk::Pointer:
   2175     DiagKind = 1;
   2176     break;
   2177   case DeclaratorChunk::Reference:
   2178     DiagKind = 2;
   2179     break;
   2180   }
   2181 
   2182   assert(DiagKind != -1);
   2183   S.Diag(DeclType.Loc, diag::err_compound_qualified_function_type)
   2184     << DiagKind << isa<FunctionType>(T.IgnoreParens()) << T
   2185     << getFunctionQualifiersAsString(T->castAs<FunctionProtoType>());
   2186 }
   2187 
   2188 /// Produce an approprioate diagnostic for an ambiguity between a function
   2189 /// declarator and a C++ direct-initializer.
   2190 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
   2191                                        DeclaratorChunk &DeclType, QualType RT) {
   2192   const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
   2193   assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
   2194 
   2195   // If the return type is void there is no ambiguity.
   2196   if (RT->isVoidType())
   2197     return;
   2198 
   2199   // An initializer for a non-class type can have at most one argument.
   2200   if (!RT->isRecordType() && FTI.NumArgs > 1)
   2201     return;
   2202 
   2203   // An initializer for a reference must have exactly one argument.
   2204   if (RT->isReferenceType() && FTI.NumArgs != 1)
   2205     return;
   2206 
   2207   // Only warn if this declarator is declaring a function at block scope, and
   2208   // doesn't have a storage class (such as 'extern') specified.
   2209   if (!D.isFunctionDeclarator() ||
   2210       D.getFunctionDefinitionKind() != FDK_Declaration ||
   2211       !S.CurContext->isFunctionOrMethod() ||
   2212       D.getDeclSpec().getStorageClassSpecAsWritten()
   2213         != DeclSpec::SCS_unspecified)
   2214     return;
   2215 
   2216   // Inside a condition, a direct initializer is not permitted. We allow one to
   2217   // be parsed in order to give better diagnostics in condition parsing.
   2218   if (D.getContext() == Declarator::ConditionContext)
   2219     return;
   2220 
   2221   SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
   2222 
   2223   S.Diag(DeclType.Loc,
   2224          FTI.NumArgs ? diag::warn_parens_disambiguated_as_function_declaration
   2225                      : diag::warn_empty_parens_are_function_decl)
   2226     << ParenRange;
   2227 
   2228   // If the declaration looks like:
   2229   //   T var1,
   2230   //   f();
   2231   // and name lookup finds a function named 'f', then the ',' was
   2232   // probably intended to be a ';'.
   2233   if (!D.isFirstDeclarator() && D.getIdentifier()) {
   2234     FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
   2235     FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
   2236     if (Comma.getFileID() != Name.getFileID() ||
   2237         Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
   2238       LookupResult Result(S, D.getIdentifier(), SourceLocation(),
   2239                           Sema::LookupOrdinaryName);
   2240       if (S.LookupName(Result, S.getCurScope()))
   2241         S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
   2242           << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
   2243           << D.getIdentifier();
   2244     }
   2245   }
   2246 
   2247   if (FTI.NumArgs > 0) {
   2248     // For a declaration with parameters, eg. "T var(T());", suggest adding parens
   2249     // around the first parameter to turn the declaration into a variable
   2250     // declaration.
   2251     SourceRange Range = FTI.ArgInfo[0].Param->getSourceRange();
   2252     SourceLocation B = Range.getBegin();
   2253     SourceLocation E = S.PP.getLocForEndOfToken(Range.getEnd());
   2254     // FIXME: Maybe we should suggest adding braces instead of parens
   2255     // in C++11 for classes that don't have an initializer_list constructor.
   2256     S.Diag(B, diag::note_additional_parens_for_variable_declaration)
   2257       << FixItHint::CreateInsertion(B, "(")
   2258       << FixItHint::CreateInsertion(E, ")");
   2259   } else {
   2260     // For a declaration without parameters, eg. "T var();", suggest replacing the
   2261     // parens with an initializer to turn the declaration into a variable
   2262     // declaration.
   2263     const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
   2264 
   2265     // Empty parens mean value-initialization, and no parens mean
   2266     // default initialization. These are equivalent if the default
   2267     // constructor is user-provided or if zero-initialization is a
   2268     // no-op.
   2269     if (RD && RD->hasDefinition() &&
   2270         (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
   2271       S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
   2272         << FixItHint::CreateRemoval(ParenRange);
   2273     else {
   2274       std::string Init = S.getFixItZeroInitializerForType(RT);
   2275       if (Init.empty() && S.LangOpts.CPlusPlus11)
   2276         Init = "{}";
   2277       if (!Init.empty())
   2278         S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
   2279           << FixItHint::CreateReplacement(ParenRange, Init);
   2280     }
   2281   }
   2282 }
   2283 
   2284 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
   2285                                                 QualType declSpecType,
   2286                                                 TypeSourceInfo *TInfo) {
   2287 
   2288   QualType T = declSpecType;
   2289   Declarator &D = state.getDeclarator();
   2290   Sema &S = state.getSema();
   2291   ASTContext &Context = S.Context;
   2292   const LangOptions &LangOpts = S.getLangOpts();
   2293 
   2294   // The name we're declaring, if any.
   2295   DeclarationName Name;
   2296   if (D.getIdentifier())
   2297     Name = D.getIdentifier();
   2298 
   2299   // Does this declaration declare a typedef-name?
   2300   bool IsTypedefName =
   2301     D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
   2302     D.getContext() == Declarator::AliasDeclContext ||
   2303     D.getContext() == Declarator::AliasTemplateContext;
   2304 
   2305   // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
   2306   bool IsQualifiedFunction = T->isFunctionProtoType() &&
   2307       (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
   2308        T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
   2309 
   2310   // Walk the DeclTypeInfo, building the recursive type as we go.
   2311   // DeclTypeInfos are ordered from the identifier out, which is
   2312   // opposite of what we want :).
   2313   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
   2314     unsigned chunkIndex = e - i - 1;
   2315     state.setCurrentChunkIndex(chunkIndex);
   2316     DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
   2317     if (IsQualifiedFunction) {
   2318       checkQualifiedFunction(S, T, DeclType);
   2319       IsQualifiedFunction = DeclType.Kind == DeclaratorChunk::Paren;
   2320     }
   2321     switch (DeclType.Kind) {
   2322     case DeclaratorChunk::Paren:
   2323       T = S.BuildParenType(T);
   2324       break;
   2325     case DeclaratorChunk::BlockPointer:
   2326       // If blocks are disabled, emit an error.
   2327       if (!LangOpts.Blocks)
   2328         S.Diag(DeclType.Loc, diag::err_blocks_disable);
   2329 
   2330       T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
   2331       if (DeclType.Cls.TypeQuals)
   2332         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
   2333       break;
   2334     case DeclaratorChunk::Pointer:
   2335       // Verify that we're not building a pointer to pointer to function with
   2336       // exception specification.
   2337       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
   2338         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
   2339         D.setInvalidType(true);
   2340         // Build the type anyway.
   2341       }
   2342       if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
   2343         T = Context.getObjCObjectPointerType(T);
   2344         if (DeclType.Ptr.TypeQuals)
   2345           T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
   2346         break;
   2347       }
   2348       T = S.BuildPointerType(T, DeclType.Loc, Name);
   2349       if (DeclType.Ptr.TypeQuals)
   2350         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
   2351 
   2352       break;
   2353     case DeclaratorChunk::Reference: {
   2354       // Verify that we're not building a reference to pointer to function with
   2355       // exception specification.
   2356       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
   2357         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
   2358         D.setInvalidType(true);
   2359         // Build the type anyway.
   2360       }
   2361       T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
   2362 
   2363       Qualifiers Quals;
   2364       if (DeclType.Ref.HasRestrict)
   2365         T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
   2366       break;
   2367     }
   2368     case DeclaratorChunk::Array: {
   2369       // Verify that we're not building an array of pointers to function with
   2370       // exception specification.
   2371       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
   2372         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
   2373         D.setInvalidType(true);
   2374         // Build the type anyway.
   2375       }
   2376       DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
   2377       Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
   2378       ArrayType::ArraySizeModifier ASM;
   2379       if (ATI.isStar)
   2380         ASM = ArrayType::Star;
   2381       else if (ATI.hasStatic)
   2382         ASM = ArrayType::Static;
   2383       else
   2384         ASM = ArrayType::Normal;
   2385       if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
   2386         // FIXME: This check isn't quite right: it allows star in prototypes
   2387         // for function definitions, and disallows some edge cases detailed
   2388         // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
   2389         S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
   2390         ASM = ArrayType::Normal;
   2391         D.setInvalidType(true);
   2392       }
   2393 
   2394       // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
   2395       // shall appear only in a declaration of a function parameter with an
   2396       // array type, ...
   2397       if (ASM == ArrayType::Static || ATI.TypeQuals) {
   2398         if (!(D.isPrototypeContext() ||
   2399               D.getContext() == Declarator::KNRTypeListContext)) {
   2400           S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
   2401               (ASM == ArrayType::Static ? "'static'" : "type qualifier");
   2402           // Remove the 'static' and the type qualifiers.
   2403           if (ASM == ArrayType::Static)
   2404             ASM = ArrayType::Normal;
   2405           ATI.TypeQuals = 0;
   2406           D.setInvalidType(true);
   2407         }
   2408 
   2409         // C99 6.7.5.2p1: ... and then only in the outermost array type
   2410         // derivation.
   2411         unsigned x = chunkIndex;
   2412         while (x != 0) {
   2413           // Walk outwards along the declarator chunks.
   2414           x--;
   2415           const DeclaratorChunk &DC = D.getTypeObject(x);
   2416           switch (DC.Kind) {
   2417           case DeclaratorChunk::Paren:
   2418             continue;
   2419           case DeclaratorChunk::Array:
   2420           case DeclaratorChunk::Pointer:
   2421           case DeclaratorChunk::Reference:
   2422           case DeclaratorChunk::MemberPointer:
   2423             S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
   2424               (ASM == ArrayType::Static ? "'static'" : "type qualifier");
   2425             if (ASM == ArrayType::Static)
   2426               ASM = ArrayType::Normal;
   2427             ATI.TypeQuals = 0;
   2428             D.setInvalidType(true);
   2429             break;
   2430           case DeclaratorChunk::Function:
   2431           case DeclaratorChunk::BlockPointer:
   2432             // These are invalid anyway, so just ignore.
   2433             break;
   2434           }
   2435         }
   2436       }
   2437 
   2438       T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
   2439                            SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
   2440       break;
   2441     }
   2442     case DeclaratorChunk::Function: {
   2443       // If the function declarator has a prototype (i.e. it is not () and
   2444       // does not have a K&R-style identifier list), then the arguments are part
   2445       // of the type, otherwise the argument list is ().
   2446       const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
   2447       IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
   2448 
   2449       // Check for auto functions and trailing return type and adjust the
   2450       // return type accordingly.
   2451       if (!D.isInvalidType()) {
   2452         // trailing-return-type is only required if we're declaring a function,
   2453         // and not, for instance, a pointer to a function.
   2454         if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
   2455             !FTI.hasTrailingReturnType() && chunkIndex == 0) {
   2456           S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
   2457                diag::err_auto_missing_trailing_return);
   2458           T = Context.IntTy;
   2459           D.setInvalidType(true);
   2460         } else if (FTI.hasTrailingReturnType()) {
   2461           // T must be exactly 'auto' at this point. See CWG issue 681.
   2462           if (isa<ParenType>(T)) {
   2463             S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
   2464                  diag::err_trailing_return_in_parens)
   2465               << T << D.getDeclSpec().getSourceRange();
   2466             D.setInvalidType(true);
   2467           } else if (D.getContext() != Declarator::LambdaExprContext &&
   2468                      (T.hasQualifiers() || !isa<AutoType>(T))) {
   2469             S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
   2470                  diag::err_trailing_return_without_auto)
   2471               << T << D.getDeclSpec().getSourceRange();
   2472             D.setInvalidType(true);
   2473           }
   2474           T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
   2475           if (T.isNull()) {
   2476             // An error occurred parsing the trailing return type.
   2477             T = Context.IntTy;
   2478             D.setInvalidType(true);
   2479           }
   2480         }
   2481       }
   2482 
   2483       // C99 6.7.5.3p1: The return type may not be a function or array type.
   2484       // For conversion functions, we'll diagnose this particular error later.
   2485       if ((T->isArrayType() || T->isFunctionType()) &&
   2486           (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
   2487         unsigned diagID = diag::err_func_returning_array_function;
   2488         // Last processing chunk in block context means this function chunk
   2489         // represents the block.
   2490         if (chunkIndex == 0 &&
   2491             D.getContext() == Declarator::BlockLiteralContext)
   2492           diagID = diag::err_block_returning_array_function;
   2493         S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
   2494         T = Context.IntTy;
   2495         D.setInvalidType(true);
   2496       }
   2497 
   2498       // Do not allow returning half FP value.
   2499       // FIXME: This really should be in BuildFunctionType.
   2500       if (T->isHalfType()) {
   2501         if (S.getLangOpts().OpenCL) {
   2502           if (!S.getOpenCLOptions().cl_khr_fp16) {
   2503             S.Diag(D.getIdentifierLoc(), diag::err_opencl_half_return) << T;
   2504             D.setInvalidType(true);
   2505           }
   2506         } else {
   2507           S.Diag(D.getIdentifierLoc(),
   2508             diag::err_parameters_retval_cannot_have_fp16_type) << 1;
   2509           D.setInvalidType(true);
   2510         }
   2511       }
   2512 
   2513       // cv-qualifiers on return types are pointless except when the type is a
   2514       // class type in C++.
   2515       if (isa<PointerType>(T) && T.getLocalCVRQualifiers() &&
   2516           (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId) &&
   2517           (!LangOpts.CPlusPlus || !T->isDependentType())) {
   2518         assert(chunkIndex + 1 < e && "No DeclaratorChunk for the return type?");
   2519         DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
   2520         assert(ReturnTypeChunk.Kind == DeclaratorChunk::Pointer);
   2521 
   2522         DeclaratorChunk::PointerTypeInfo &PTI = ReturnTypeChunk.Ptr;
   2523 
   2524         DiagnoseIgnoredQualifiers(PTI.TypeQuals,
   2525             SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
   2526             SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
   2527             SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
   2528             S);
   2529 
   2530       } else if (T.getCVRQualifiers() && D.getDeclSpec().getTypeQualifiers() &&
   2531           (!LangOpts.CPlusPlus ||
   2532            (!T->isDependentType() && !T->isRecordType()))) {
   2533 
   2534         DiagnoseIgnoredQualifiers(D.getDeclSpec().getTypeQualifiers(),
   2535                                   D.getDeclSpec().getConstSpecLoc(),
   2536                                   D.getDeclSpec().getVolatileSpecLoc(),
   2537                                   D.getDeclSpec().getRestrictSpecLoc(),
   2538                                   S);
   2539       }
   2540 
   2541       // Objective-C ARC ownership qualifiers are ignored on the function
   2542       // return type (by type canonicalization). Complain if this attribute
   2543       // was written here.
   2544       if (T.getQualifiers().hasObjCLifetime()) {
   2545         SourceLocation AttrLoc;
   2546         if (chunkIndex + 1 < D.getNumTypeObjects()) {
   2547           DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
   2548           for (const AttributeList *Attr = ReturnTypeChunk.getAttrs();
   2549                Attr; Attr = Attr->getNext()) {
   2550             if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
   2551               AttrLoc = Attr->getLoc();
   2552               break;
   2553             }
   2554           }
   2555         }
   2556         if (AttrLoc.isInvalid()) {
   2557           for (const AttributeList *Attr
   2558                  = D.getDeclSpec().getAttributes().getList();
   2559                Attr; Attr = Attr->getNext()) {
   2560             if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
   2561               AttrLoc = Attr->getLoc();
   2562               break;
   2563             }
   2564           }
   2565         }
   2566 
   2567         if (AttrLoc.isValid()) {
   2568           // The ownership attributes are almost always written via
   2569           // the predefined
   2570           // __strong/__weak/__autoreleasing/__unsafe_unretained.
   2571           if (AttrLoc.isMacroID())
   2572             AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first;
   2573 
   2574           S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
   2575             << T.getQualifiers().getObjCLifetime();
   2576         }
   2577       }
   2578 
   2579       if (LangOpts.CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
   2580         // C++ [dcl.fct]p6:
   2581         //   Types shall not be defined in return or parameter types.
   2582         TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
   2583         if (Tag->isCompleteDefinition())
   2584           S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
   2585             << Context.getTypeDeclType(Tag);
   2586       }
   2587 
   2588       // Exception specs are not allowed in typedefs. Complain, but add it
   2589       // anyway.
   2590       if (IsTypedefName && FTI.getExceptionSpecType())
   2591         S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef)
   2592           << (D.getContext() == Declarator::AliasDeclContext ||
   2593               D.getContext() == Declarator::AliasTemplateContext);
   2594 
   2595       // If we see "T var();" or "T var(T());" at block scope, it is probably
   2596       // an attempt to initialize a variable, not a function declaration.
   2597       if (FTI.isAmbiguous)
   2598         warnAboutAmbiguousFunction(S, D, DeclType, T);
   2599 
   2600       if (!FTI.NumArgs && !FTI.isVariadic && !LangOpts.CPlusPlus) {
   2601         // Simple void foo(), where the incoming T is the result type.
   2602         T = Context.getFunctionNoProtoType(T);
   2603       } else {
   2604         // We allow a zero-parameter variadic function in C if the
   2605         // function is marked with the "overloadable" attribute. Scan
   2606         // for this attribute now.
   2607         if (!FTI.NumArgs && FTI.isVariadic && !LangOpts.CPlusPlus) {
   2608           bool Overloadable = false;
   2609           for (const AttributeList *Attrs = D.getAttributes();
   2610                Attrs; Attrs = Attrs->getNext()) {
   2611             if (Attrs->getKind() == AttributeList::AT_Overloadable) {
   2612               Overloadable = true;
   2613               break;
   2614             }
   2615           }
   2616 
   2617           if (!Overloadable)
   2618             S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
   2619         }
   2620 
   2621         if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) {
   2622           // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
   2623           // definition.
   2624           S.Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
   2625           D.setInvalidType(true);
   2626           // Recover by creating a K&R-style function type.
   2627           T = Context.getFunctionNoProtoType(T);
   2628           break;
   2629         }
   2630 
   2631         FunctionProtoType::ExtProtoInfo EPI;
   2632         EPI.Variadic = FTI.isVariadic;
   2633         EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
   2634         EPI.TypeQuals = FTI.TypeQuals;
   2635         EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
   2636                     : FTI.RefQualifierIsLValueRef? RQ_LValue
   2637                     : RQ_RValue;
   2638 
   2639         // Otherwise, we have a function with an argument list that is
   2640         // potentially variadic.
   2641         SmallVector<QualType, 16> ArgTys;
   2642         ArgTys.reserve(FTI.NumArgs);
   2643 
   2644         SmallVector<bool, 16> ConsumedArguments;
   2645         ConsumedArguments.reserve(FTI.NumArgs);
   2646         bool HasAnyConsumedArguments = false;
   2647 
   2648         for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
   2649           ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
   2650           QualType ArgTy = Param->getType();
   2651           assert(!ArgTy.isNull() && "Couldn't parse type?");
   2652 
   2653           // Adjust the parameter type.
   2654           assert((ArgTy == Context.getAdjustedParameterType(ArgTy)) &&
   2655                  "Unadjusted type?");
   2656 
   2657           // Look for 'void'.  void is allowed only as a single argument to a
   2658           // function with no other parameters (C99 6.7.5.3p10).  We record
   2659           // int(void) as a FunctionProtoType with an empty argument list.
   2660           if (ArgTy->isVoidType()) {
   2661             // If this is something like 'float(int, void)', reject it.  'void'
   2662             // is an incomplete type (C99 6.2.5p19) and function decls cannot
   2663             // have arguments of incomplete type.
   2664             if (FTI.NumArgs != 1 || FTI.isVariadic) {
   2665               S.Diag(DeclType.Loc, diag::err_void_only_param);
   2666               ArgTy = Context.IntTy;
   2667               Param->setType(ArgTy);
   2668             } else if (FTI.ArgInfo[i].Ident) {
   2669               // Reject, but continue to parse 'int(void abc)'.
   2670               S.Diag(FTI.ArgInfo[i].IdentLoc,
   2671                    diag::err_param_with_void_type);
   2672               ArgTy = Context.IntTy;
   2673               Param->setType(ArgTy);
   2674             } else {
   2675               // Reject, but continue to parse 'float(const void)'.
   2676               if (ArgTy.hasQualifiers())
   2677                 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
   2678 
   2679               // Do not add 'void' to the ArgTys list.
   2680               break;
   2681             }
   2682           } else if (ArgTy->isHalfType()) {
   2683             // Disallow half FP arguments.
   2684             // FIXME: This really should be in BuildFunctionType.
   2685             if (S.getLangOpts().OpenCL) {
   2686               if (!S.getOpenCLOptions().cl_khr_fp16) {
   2687                 S.Diag(Param->getLocation(),
   2688                   diag::err_opencl_half_argument) << ArgTy;
   2689                 D.setInvalidType();
   2690                 Param->setInvalidDecl();
   2691               }
   2692             } else {
   2693               S.Diag(Param->getLocation(),
   2694                 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
   2695               D.setInvalidType();
   2696             }
   2697           } else if (!FTI.hasPrototype) {
   2698             if (ArgTy->isPromotableIntegerType()) {
   2699               ArgTy = Context.getPromotedIntegerType(ArgTy);
   2700               Param->setKNRPromoted(true);
   2701             } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
   2702               if (BTy->getKind() == BuiltinType::Float) {
   2703                 ArgTy = Context.DoubleTy;
   2704                 Param->setKNRPromoted(true);
   2705               }
   2706             }
   2707           }
   2708 
   2709           if (LangOpts.ObjCAutoRefCount) {
   2710             bool Consumed = Param->hasAttr<NSConsumedAttr>();
   2711             ConsumedArguments.push_back(Consumed);
   2712             HasAnyConsumedArguments |= Consumed;
   2713           }
   2714 
   2715           ArgTys.push_back(ArgTy);
   2716         }
   2717 
   2718         if (HasAnyConsumedArguments)
   2719           EPI.ConsumedArguments = ConsumedArguments.data();
   2720 
   2721         SmallVector<QualType, 4> Exceptions;
   2722         SmallVector<ParsedType, 2> DynamicExceptions;
   2723         SmallVector<SourceRange, 2> DynamicExceptionRanges;
   2724         Expr *NoexceptExpr = 0;
   2725 
   2726         if (FTI.getExceptionSpecType() == EST_Dynamic) {
   2727           // FIXME: It's rather inefficient to have to split into two vectors
   2728           // here.
   2729           unsigned N = FTI.NumExceptions;
   2730           DynamicExceptions.reserve(N);
   2731           DynamicExceptionRanges.reserve(N);
   2732           for (unsigned I = 0; I != N; ++I) {
   2733             DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
   2734             DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
   2735           }
   2736         } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
   2737           NoexceptExpr = FTI.NoexceptExpr;
   2738         }
   2739 
   2740         S.checkExceptionSpecification(FTI.getExceptionSpecType(),
   2741                                       DynamicExceptions,
   2742                                       DynamicExceptionRanges,
   2743                                       NoexceptExpr,
   2744                                       Exceptions,
   2745                                       EPI);
   2746 
   2747         T = Context.getFunctionType(T, ArgTys, EPI);
   2748       }
   2749 
   2750       break;
   2751     }
   2752     case DeclaratorChunk::MemberPointer:
   2753       // The scope spec must refer to a class, or be dependent.
   2754       CXXScopeSpec &SS = DeclType.Mem.Scope();
   2755       QualType ClsType;
   2756       if (SS.isInvalid()) {
   2757         // Avoid emitting extra errors if we already errored on the scope.
   2758         D.setInvalidType(true);
   2759       } else if (S.isDependentScopeSpecifier(SS) ||
   2760                  dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
   2761         NestedNameSpecifier *NNS
   2762           = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
   2763         NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
   2764         switch (NNS->getKind()) {
   2765         case NestedNameSpecifier::Identifier:
   2766           ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
   2767                                                  NNS->getAsIdentifier());
   2768           break;
   2769 
   2770         case NestedNameSpecifier::Namespace:
   2771         case NestedNameSpecifier::NamespaceAlias:
   2772         case NestedNameSpecifier::Global:
   2773           llvm_unreachable("Nested-name-specifier must name a type");
   2774 
   2775         case NestedNameSpecifier::TypeSpec:
   2776         case NestedNameSpecifier::TypeSpecWithTemplate:
   2777           ClsType = QualType(NNS->getAsType(), 0);
   2778           // Note: if the NNS has a prefix and ClsType is a nondependent
   2779           // TemplateSpecializationType, then the NNS prefix is NOT included
   2780           // in ClsType; hence we wrap ClsType into an ElaboratedType.
   2781           // NOTE: in particular, no wrap occurs if ClsType already is an
   2782           // Elaborated, DependentName, or DependentTemplateSpecialization.
   2783           if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
   2784             ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
   2785           break;
   2786         }
   2787       } else {
   2788         S.Diag(DeclType.Mem.Scope().getBeginLoc(),
   2789              diag::err_illegal_decl_mempointer_in_nonclass)
   2790           << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
   2791           << DeclType.Mem.Scope().getRange();
   2792         D.setInvalidType(true);
   2793       }
   2794 
   2795       if (!ClsType.isNull())
   2796         T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier());
   2797       if (T.isNull()) {
   2798         T = Context.IntTy;
   2799         D.setInvalidType(true);
   2800       } else if (DeclType.Mem.TypeQuals) {
   2801         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
   2802       }
   2803       break;
   2804     }
   2805 
   2806     if (T.isNull()) {
   2807       D.setInvalidType(true);
   2808       T = Context.IntTy;
   2809     }
   2810 
   2811     // See if there are any attributes on this declarator chunk.
   2812     if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
   2813       processTypeAttrs(state, T, TAL_DeclChunk, attrs);
   2814   }
   2815 
   2816   if (LangOpts.CPlusPlus && T->isFunctionType()) {
   2817     const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
   2818     assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
   2819 
   2820     // C++ 8.3.5p4:
   2821     //   A cv-qualifier-seq shall only be part of the function type
   2822     //   for a nonstatic member function, the function type to which a pointer
   2823     //   to member refers, or the top-level function type of a function typedef
   2824     //   declaration.
   2825     //
   2826     // Core issue 547 also allows cv-qualifiers on function types that are
   2827     // top-level template type arguments.
   2828     bool FreeFunction;
   2829     if (!D.getCXXScopeSpec().isSet()) {
   2830       FreeFunction = ((D.getContext() != Declarator::MemberContext &&
   2831                        D.getContext() != Declarator::LambdaExprContext) ||
   2832                       D.getDeclSpec().isFriendSpecified());
   2833     } else {
   2834       DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
   2835       FreeFunction = (DC && !DC->isRecord());
   2836     }
   2837 
   2838     // C++11 [dcl.fct]p6 (w/DR1417):
   2839     // An attempt to specify a function type with a cv-qualifier-seq or a
   2840     // ref-qualifier (including by typedef-name) is ill-formed unless it is:
   2841     //  - the function type for a non-static member function,
   2842     //  - the function type to which a pointer to member refers,
   2843     //  - the top-level function type of a function typedef declaration or
   2844     //    alias-declaration,
   2845     //  - the type-id in the default argument of a type-parameter, or
   2846     //  - the type-id of a template-argument for a type-parameter
   2847     if (IsQualifiedFunction &&
   2848         !(!FreeFunction &&
   2849           D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
   2850         !IsTypedefName &&
   2851         D.getContext() != Declarator::TemplateTypeArgContext) {
   2852       SourceLocation Loc = D.getLocStart();
   2853       SourceRange RemovalRange;
   2854       unsigned I;
   2855       if (D.isFunctionDeclarator(I)) {
   2856         SmallVector<SourceLocation, 4> RemovalLocs;
   2857         const DeclaratorChunk &Chunk = D.getTypeObject(I);
   2858         assert(Chunk.Kind == DeclaratorChunk::Function);
   2859         if (Chunk.Fun.hasRefQualifier())
   2860           RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
   2861         if (Chunk.Fun.TypeQuals & Qualifiers::Const)
   2862           RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
   2863         if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
   2864           RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
   2865         // FIXME: We do not track the location of the __restrict qualifier.
   2866         //if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
   2867         //  RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
   2868         if (!RemovalLocs.empty()) {
   2869           std::sort(RemovalLocs.begin(), RemovalLocs.end(),
   2870                     BeforeThanCompare<SourceLocation>(S.getSourceManager()));
   2871           RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
   2872           Loc = RemovalLocs.front();
   2873         }
   2874       }
   2875 
   2876       S.Diag(Loc, diag::err_invalid_qualified_function_type)
   2877         << FreeFunction << D.isFunctionDeclarator() << T
   2878         << getFunctionQualifiersAsString(FnTy)
   2879         << FixItHint::CreateRemoval(RemovalRange);
   2880 
   2881       // Strip the cv-qualifiers and ref-qualifiers from the type.
   2882       FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
   2883       EPI.TypeQuals = 0;
   2884       EPI.RefQualifier = RQ_None;
   2885 
   2886       T = Context.getFunctionType(FnTy->getResultType(),
   2887                                   ArrayRef<QualType>(FnTy->arg_type_begin(),
   2888                                                      FnTy->getNumArgs()),
   2889                                   EPI);
   2890       // Rebuild any parens around the identifier in the function type.
   2891       for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
   2892         if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
   2893           break;
   2894         T = S.BuildParenType(T);
   2895       }
   2896     }
   2897   }
   2898 
   2899   // Apply any undistributed attributes from the declarator.
   2900   if (!T.isNull())
   2901     if (AttributeList *attrs = D.getAttributes())
   2902       processTypeAttrs(state, T, TAL_DeclName, attrs);
   2903 
   2904   // Diagnose any ignored type attributes.
   2905   if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T);
   2906 
   2907   // C++0x [dcl.constexpr]p9:
   2908   //  A constexpr specifier used in an object declaration declares the object
   2909   //  as const.
   2910   if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
   2911     T.addConst();
   2912   }
   2913 
   2914   // If there was an ellipsis in the declarator, the declaration declares a
   2915   // parameter pack whose type may be a pack expansion type.
   2916   if (D.hasEllipsis() && !T.isNull()) {
   2917     // C++0x [dcl.fct]p13:
   2918     //   A declarator-id or abstract-declarator containing an ellipsis shall
   2919     //   only be used in a parameter-declaration. Such a parameter-declaration
   2920     //   is a parameter pack (14.5.3). [...]
   2921     switch (D.getContext()) {
   2922     case Declarator::PrototypeContext:
   2923       // C++0x [dcl.fct]p13:
   2924       //   [...] When it is part of a parameter-declaration-clause, the
   2925       //   parameter pack is a function parameter pack (14.5.3). The type T
   2926       //   of the declarator-id of the function parameter pack shall contain
   2927       //   a template parameter pack; each template parameter pack in T is
   2928       //   expanded by the function parameter pack.
   2929       //
   2930       // We represent function parameter packs as function parameters whose
   2931       // type is a pack expansion.
   2932       if (!T->containsUnexpandedParameterPack()) {
   2933         S.Diag(D.getEllipsisLoc(),
   2934              diag::err_function_parameter_pack_without_parameter_packs)
   2935           << T <<  D.getSourceRange();
   2936         D.setEllipsisLoc(SourceLocation());
   2937       } else {
   2938         T = Context.getPackExpansionType(T, None);
   2939       }
   2940       break;
   2941 
   2942     case Declarator::TemplateParamContext:
   2943       // C++0x [temp.param]p15:
   2944       //   If a template-parameter is a [...] is a parameter-declaration that
   2945       //   declares a parameter pack (8.3.5), then the template-parameter is a
   2946       //   template parameter pack (14.5.3).
   2947       //
   2948       // Note: core issue 778 clarifies that, if there are any unexpanded
   2949       // parameter packs in the type of the non-type template parameter, then
   2950       // it expands those parameter packs.
   2951       if (T->containsUnexpandedParameterPack())
   2952         T = Context.getPackExpansionType(T, None);
   2953       else
   2954         S.Diag(D.getEllipsisLoc(),
   2955                LangOpts.CPlusPlus11
   2956                  ? diag::warn_cxx98_compat_variadic_templates
   2957                  : diag::ext_variadic_templates);
   2958       break;
   2959 
   2960     case Declarator::FileContext:
   2961     case Declarator::KNRTypeListContext:
   2962     case Declarator::ObjCParameterContext:  // FIXME: special diagnostic here?
   2963     case Declarator::ObjCResultContext:     // FIXME: special diagnostic here?
   2964     case Declarator::TypeNameContext:
   2965     case Declarator::CXXNewContext:
   2966     case Declarator::AliasDeclContext:
   2967     case Declarator::AliasTemplateContext:
   2968     case Declarator::MemberContext:
   2969     case Declarator::BlockContext:
   2970     case Declarator::ForContext:
   2971     case Declarator::ConditionContext:
   2972     case Declarator::CXXCatchContext:
   2973     case Declarator::ObjCCatchContext:
   2974     case Declarator::BlockLiteralContext:
   2975     case Declarator::LambdaExprContext:
   2976     case Declarator::TrailingReturnContext:
   2977     case Declarator::TemplateTypeArgContext:
   2978       // FIXME: We may want to allow parameter packs in block-literal contexts
   2979       // in the future.
   2980       S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter);
   2981       D.setEllipsisLoc(SourceLocation());
   2982       break;
   2983     }
   2984   }
   2985 
   2986   if (T.isNull())
   2987     return Context.getNullTypeSourceInfo();
   2988   else if (D.isInvalidType())
   2989     return Context.getTrivialTypeSourceInfo(T);
   2990 
   2991   return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
   2992 }
   2993 
   2994 /// GetTypeForDeclarator - Convert the type for the specified
   2995 /// declarator to Type instances.
   2996 ///
   2997 /// The result of this call will never be null, but the associated
   2998 /// type may be a null type if there's an unrecoverable error.
   2999 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
   3000   // Determine the type of the declarator. Not all forms of declarator
   3001   // have a type.
   3002 
   3003   TypeProcessingState state(*this, D);
   3004 
   3005   TypeSourceInfo *ReturnTypeInfo = 0;
   3006   QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
   3007   if (T.isNull())
   3008     return Context.getNullTypeSourceInfo();
   3009 
   3010   if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
   3011     inferARCWriteback(state, T);
   3012 
   3013   return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
   3014 }
   3015 
   3016 static void transferARCOwnershipToDeclSpec(Sema &S,
   3017                                            QualType &declSpecTy,
   3018                                            Qualifiers::ObjCLifetime ownership) {
   3019   if (declSpecTy->isObjCRetainableType() &&
   3020       declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
   3021     Qualifiers qs;
   3022     qs.addObjCLifetime(ownership);
   3023     declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
   3024   }
   3025 }
   3026 
   3027 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
   3028                                             Qualifiers::ObjCLifetime ownership,
   3029                                             unsigned chunkIndex) {
   3030   Sema &S = state.getSema();
   3031   Declarator &D = state.getDeclarator();
   3032 
   3033   // Look for an explicit lifetime attribute.
   3034   DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
   3035   for (const AttributeList *attr = chunk.getAttrs(); attr;
   3036          attr = attr->getNext())
   3037     if (attr->getKind() == AttributeList::AT_ObjCOwnership)
   3038       return;
   3039 
   3040   const char *attrStr = 0;
   3041   switch (ownership) {
   3042   case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
   3043   case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
   3044   case Qualifiers::OCL_Strong: attrStr = "strong"; break;
   3045   case Qualifiers::OCL_Weak: attrStr = "weak"; break;
   3046   case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
   3047   }
   3048 
   3049   // If there wasn't one, add one (with an invalid source location
   3050   // so that we don't make an AttributedType for it).
   3051   AttributeList *attr = D.getAttributePool()
   3052     .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
   3053             /*scope*/ 0, SourceLocation(),
   3054             &S.Context.Idents.get(attrStr), SourceLocation(),
   3055             /*args*/ 0, 0, AttributeList::AS_GNU);
   3056   spliceAttrIntoList(*attr, chunk.getAttrListRef());
   3057 
   3058   // TODO: mark whether we did this inference?
   3059 }
   3060 
   3061 /// \brief Used for transferring ownership in casts resulting in l-values.
   3062 static void transferARCOwnership(TypeProcessingState &state,
   3063                                  QualType &declSpecTy,
   3064                                  Qualifiers::ObjCLifetime ownership) {
   3065   Sema &S = state.getSema();
   3066   Declarator &D = state.getDeclarator();
   3067 
   3068   int inner = -1;
   3069   bool hasIndirection = false;
   3070   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
   3071     DeclaratorChunk &chunk = D.getTypeObject(i);
   3072     switch (chunk.Kind) {
   3073     case DeclaratorChunk::Paren:
   3074       // Ignore parens.
   3075       break;
   3076 
   3077     case DeclaratorChunk::Array:
   3078     case DeclaratorChunk::Reference:
   3079     case DeclaratorChunk::Pointer:
   3080       if (inner != -1)
   3081         hasIndirection = true;
   3082       inner = i;
   3083       break;
   3084 
   3085     case DeclaratorChunk::BlockPointer:
   3086       if (inner != -1)
   3087         transferARCOwnershipToDeclaratorChunk(state, ownership, i);
   3088       return;
   3089 
   3090     case DeclaratorChunk::Function:
   3091     case DeclaratorChunk::MemberPointer:
   3092       return;
   3093     }
   3094   }
   3095 
   3096   if (inner == -1)
   3097     return;
   3098 
   3099   DeclaratorChunk &chunk = D.getTypeObject(inner);
   3100   if (chunk.Kind == DeclaratorChunk::Pointer) {
   3101     if (declSpecTy->isObjCRetainableType())
   3102       return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
   3103     if (declSpecTy->isObjCObjectType() && hasIndirection)
   3104       return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
   3105   } else {
   3106     assert(chunk.Kind == DeclaratorChunk::Array ||
   3107            chunk.Kind == DeclaratorChunk::Reference);
   3108     return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
   3109   }
   3110 }
   3111 
   3112 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
   3113   TypeProcessingState state(*this, D);
   3114 
   3115   TypeSourceInfo *ReturnTypeInfo = 0;
   3116   QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
   3117   if (declSpecTy.isNull())
   3118     return Context.getNullTypeSourceInfo();
   3119 
   3120   if (getLangOpts().ObjCAutoRefCount) {
   3121     Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
   3122     if (ownership != Qualifiers::OCL_None)
   3123       transferARCOwnership(state, declSpecTy, ownership);
   3124   }
   3125 
   3126   return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
   3127 }
   3128 
   3129 /// Map an AttributedType::Kind to an AttributeList::Kind.
   3130 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
   3131   switch (kind) {
   3132   case AttributedType::attr_address_space:
   3133     return AttributeList::AT_AddressSpace;
   3134   case AttributedType::attr_regparm:
   3135     return AttributeList::AT_Regparm;
   3136   case AttributedType::attr_vector_size:
   3137     return AttributeList::AT_VectorSize;
   3138   case AttributedType::attr_neon_vector_type:
   3139     return AttributeList::AT_NeonVectorType;
   3140   case AttributedType::attr_neon_polyvector_type:
   3141     return AttributeList::AT_NeonPolyVectorType;
   3142   case AttributedType::attr_objc_gc:
   3143     return AttributeList::AT_ObjCGC;
   3144   case AttributedType::attr_objc_ownership:
   3145     return AttributeList::AT_ObjCOwnership;
   3146   case AttributedType::attr_noreturn:
   3147     return AttributeList::AT_NoReturn;
   3148   case AttributedType::attr_cdecl:
   3149     return AttributeList::AT_CDecl;
   3150   case AttributedType::attr_fastcall:
   3151     return AttributeList::AT_FastCall;
   3152   case AttributedType::attr_stdcall:
   3153     return AttributeList::AT_StdCall;
   3154   case AttributedType::attr_thiscall:
   3155     return AttributeList::AT_ThisCall;
   3156   case AttributedType::attr_pascal:
   3157     return AttributeList::AT_Pascal;
   3158   case AttributedType::attr_pcs:
   3159     return AttributeList::AT_Pcs;
   3160   case AttributedType::attr_pnaclcall:
   3161     return AttributeList::AT_PnaclCall;
   3162   case AttributedType::attr_inteloclbicc:
   3163     return AttributeList::AT_IntelOclBicc;
   3164   }
   3165   llvm_unreachable("unexpected attribute kind!");
   3166 }
   3167 
   3168 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
   3169                                   const AttributeList *attrs) {
   3170   AttributedType::Kind kind = TL.getAttrKind();
   3171 
   3172   assert(attrs && "no type attributes in the expected location!");
   3173   AttributeList::Kind parsedKind = getAttrListKind(kind);
   3174   while (attrs->getKind() != parsedKind) {
   3175     attrs = attrs->getNext();
   3176     assert(attrs && "no matching attribute in expected location!");
   3177   }
   3178 
   3179   TL.setAttrNameLoc(attrs->getLoc());
   3180   if (TL.hasAttrExprOperand())
   3181     TL.setAttrExprOperand(attrs->getArg(0));
   3182   else if (TL.hasAttrEnumOperand())
   3183     TL.setAttrEnumOperandLoc(attrs->getParameterLoc());
   3184 
   3185   // FIXME: preserve this information to here.
   3186   if (TL.hasAttrOperand())
   3187     TL.setAttrOperandParensRange(SourceRange());
   3188 }
   3189 
   3190 namespace {
   3191   class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
   3192     ASTContext &Context;
   3193     const DeclSpec &DS;
   3194 
   3195   public:
   3196     TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
   3197       : Context(Context), DS(DS) {}
   3198 
   3199     void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
   3200       fillAttributedTypeLoc(TL, DS.getAttributes().getList());
   3201       Visit(TL.getModifiedLoc());
   3202     }
   3203     void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
   3204       Visit(TL.getUnqualifiedLoc());
   3205     }
   3206     void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
   3207       TL.setNameLoc(DS.getTypeSpecTypeLoc());
   3208     }
   3209     void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
   3210       TL.setNameLoc(DS.getTypeSpecTypeLoc());
   3211       // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
   3212       // addition field. What we have is good enough for dispay of location
   3213       // of 'fixit' on interface name.
   3214       TL.setNameEndLoc(DS.getLocEnd());
   3215     }
   3216     void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
   3217       // Handle the base type, which might not have been written explicitly.
   3218       if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
   3219         TL.setHasBaseTypeAsWritten(false);
   3220         TL.getBaseLoc().initialize(Context, SourceLocation());
   3221       } else {
   3222         TL.setHasBaseTypeAsWritten(true);
   3223         Visit(TL.getBaseLoc());
   3224       }
   3225 
   3226       // Protocol qualifiers.
   3227       if (DS.getProtocolQualifiers()) {
   3228         assert(TL.getNumProtocols() > 0);
   3229         assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
   3230         TL.setLAngleLoc(DS.getProtocolLAngleLoc());
   3231         TL.setRAngleLoc(DS.getSourceRange().getEnd());
   3232         for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
   3233           TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
   3234       } else {
   3235         assert(TL.getNumProtocols() == 0);
   3236         TL.setLAngleLoc(SourceLocation());
   3237         TL.setRAngleLoc(SourceLocation());
   3238       }
   3239     }
   3240     void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
   3241       TL.setStarLoc(SourceLocation());
   3242       Visit(TL.getPointeeLoc());
   3243     }
   3244     void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
   3245       TypeSourceInfo *TInfo = 0;
   3246       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
   3247 
   3248       // If we got no declarator info from previous Sema routines,
   3249       // just fill with the typespec loc.
   3250       if (!TInfo) {
   3251         TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
   3252         return;
   3253       }
   3254 
   3255       TypeLoc OldTL = TInfo->getTypeLoc();
   3256       if (TInfo->getType()->getAs<ElaboratedType>()) {
   3257         ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
   3258         TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
   3259             .castAs<TemplateSpecializationTypeLoc>();
   3260         TL.copy(NamedTL);
   3261       }
   3262       else
   3263         TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
   3264     }
   3265     void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
   3266       assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
   3267       TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
   3268       TL.setParensRange(DS.getTypeofParensRange());
   3269     }
   3270     void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
   3271       assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
   3272       TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
   3273       TL.setParensRange(DS.getTypeofParensRange());
   3274       assert(DS.getRepAsType());
   3275       TypeSourceInfo *TInfo = 0;
   3276       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
   3277       TL.setUnderlyingTInfo(TInfo);
   3278     }
   3279     void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
   3280       // FIXME: This holds only because we only have one unary transform.
   3281       assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
   3282       TL.setKWLoc(DS.getTypeSpecTypeLoc());
   3283       TL.setParensRange(DS.getTypeofParensRange());
   3284       assert(DS.getRepAsType());
   3285       TypeSourceInfo *TInfo = 0;
   3286       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
   3287       TL.setUnderlyingTInfo(TInfo);
   3288     }
   3289     void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
   3290       // By default, use the source location of the type specifier.
   3291       TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
   3292       if (TL.needsExtraLocalData()) {
   3293         // Set info for the written builtin specifiers.
   3294         TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
   3295         // Try to have a meaningful source location.
   3296         if (TL.getWrittenSignSpec() != TSS_unspecified)
   3297           // Sign spec loc overrides the others (e.g., 'unsigned long').
   3298           TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
   3299         else if (TL.getWrittenWidthSpec() != TSW_unspecified)
   3300           // Width spec loc overrides type spec loc (e.g., 'short int').
   3301           TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
   3302       }
   3303     }
   3304     void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
   3305       ElaboratedTypeKeyword Keyword
   3306         = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
   3307       if (DS.getTypeSpecType() == TST_typename) {
   3308         TypeSourceInfo *TInfo = 0;
   3309         Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
   3310         if (TInfo) {
   3311           TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
   3312           return;
   3313         }
   3314       }
   3315       TL.setElaboratedKeywordLoc(Keyword != ETK_None
   3316                                  ? DS.getTypeSpecTypeLoc()
   3317                                  : SourceLocation());
   3318       const CXXScopeSpec& SS = DS.getTypeSpecScope();
   3319       TL.setQualifierLoc(SS.getWithLocInContext(Context));
   3320       Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
   3321     }
   3322     void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
   3323       assert(DS.getTypeSpecType() == TST_typename);
   3324       TypeSourceInfo *TInfo = 0;
   3325       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
   3326       assert(TInfo);
   3327       TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
   3328     }
   3329     void VisitDependentTemplateSpecializationTypeLoc(
   3330                                  DependentTemplateSpecializationTypeLoc TL) {
   3331       assert(DS.getTypeSpecType() == TST_typename);
   3332       TypeSourceInfo *TInfo = 0;
   3333       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
   3334       assert(TInfo);
   3335       TL.copy(
   3336           TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
   3337     }
   3338     void VisitTagTypeLoc(TagTypeLoc TL) {
   3339       TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
   3340     }
   3341     void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
   3342       TL.setKWLoc(DS.getTypeSpecTypeLoc());
   3343       TL.setParensRange(DS.getTypeofParensRange());
   3344 
   3345       TypeSourceInfo *TInfo = 0;
   3346       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
   3347       assert(TInfo);
   3348       TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
   3349     }
   3350 
   3351     void VisitTypeLoc(TypeLoc TL) {
   3352       // FIXME: add other typespec types and change this to an assert.
   3353       TL.initialize(Context, DS.getTypeSpecTypeLoc());
   3354     }
   3355   };
   3356 
   3357   class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
   3358     ASTContext &Context;
   3359     const DeclaratorChunk &Chunk;
   3360 
   3361   public:
   3362     DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
   3363       : Context(Context), Chunk(Chunk) {}
   3364 
   3365     void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
   3366       llvm_unreachable("qualified type locs not expected here!");
   3367     }
   3368 
   3369     void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
   3370       fillAttributedTypeLoc(TL, Chunk.getAttrs());
   3371     }
   3372     void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
   3373       assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
   3374       TL.setCaretLoc(Chunk.Loc);
   3375     }
   3376     void VisitPointerTypeLoc(PointerTypeLoc TL) {
   3377       assert(Chunk.Kind == DeclaratorChunk::Pointer);
   3378       TL.setStarLoc(Chunk.Loc);
   3379     }
   3380     void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
   3381       assert(Chunk.Kind == DeclaratorChunk::Pointer);
   3382       TL.setStarLoc(Chunk.Loc);
   3383     }
   3384     void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
   3385       assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
   3386       const CXXScopeSpec& SS = Chunk.Mem.Scope();
   3387       NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
   3388 
   3389       const Type* ClsTy = TL.getClass();
   3390       QualType ClsQT = QualType(ClsTy, 0);
   3391       TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
   3392       // Now copy source location info into the type loc component.
   3393       TypeLoc ClsTL = ClsTInfo->getTypeLoc();
   3394       switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
   3395       case NestedNameSpecifier::Identifier:
   3396         assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
   3397         {
   3398           DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
   3399           DNTLoc.setElaboratedKeywordLoc(SourceLocation());
   3400           DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
   3401           DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
   3402         }
   3403         break;
   3404 
   3405       case NestedNameSpecifier::TypeSpec:
   3406       case NestedNameSpecifier::TypeSpecWithTemplate:
   3407         if (isa<ElaboratedType>(ClsTy)) {
   3408           ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
   3409           ETLoc.setElaboratedKeywordLoc(SourceLocation());
   3410           ETLoc.setQualifierLoc(NNSLoc.getPrefix());
   3411           TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
   3412           NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
   3413         } else {
   3414           ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
   3415         }
   3416         break;
   3417 
   3418       case NestedNameSpecifier::Namespace:
   3419       case NestedNameSpecifier::NamespaceAlias:
   3420       case NestedNameSpecifier::Global:
   3421         llvm_unreachable("Nested-name-specifier must name a type");
   3422       }
   3423 
   3424       // Finally fill in MemberPointerLocInfo fields.
   3425       TL.setStarLoc(Chunk.Loc);
   3426       TL.setClassTInfo(ClsTInfo);
   3427     }
   3428     void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
   3429       assert(Chunk.Kind == DeclaratorChunk::Reference);
   3430       // 'Amp' is misleading: this might have been originally
   3431       /// spelled with AmpAmp.
   3432       TL.setAmpLoc(Chunk.Loc);
   3433     }
   3434     void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
   3435       assert(Chunk.Kind == DeclaratorChunk::Reference);
   3436       assert(!Chunk.Ref.LValueRef);
   3437       TL.setAmpAmpLoc(Chunk.Loc);
   3438     }
   3439     void VisitArrayTypeLoc(ArrayTypeLoc TL) {
   3440       assert(Chunk.Kind == DeclaratorChunk::Array);
   3441       TL.setLBracketLoc(Chunk.Loc);
   3442       TL.setRBracketLoc(Chunk.EndLoc);
   3443       TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
   3444     }
   3445     void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
   3446       assert(Chunk.Kind == DeclaratorChunk::Function);
   3447       TL.setLocalRangeBegin(Chunk.Loc);
   3448       TL.setLocalRangeEnd(Chunk.EndLoc);
   3449 
   3450       const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
   3451       TL.setLParenLoc(FTI.getLParenLoc());
   3452       TL.setRParenLoc(FTI.getRParenLoc());
   3453       for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
   3454         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
   3455         TL.setArg(tpi++, Param);
   3456       }
   3457       // FIXME: exception specs
   3458     }
   3459     void VisitParenTypeLoc(ParenTypeLoc TL) {
   3460       assert(Chunk.Kind == DeclaratorChunk::Paren);
   3461       TL.setLParenLoc(Chunk.Loc);
   3462       TL.setRParenLoc(Chunk.EndLoc);
   3463     }
   3464 
   3465     void VisitTypeLoc(TypeLoc TL) {
   3466       llvm_unreachable("unsupported TypeLoc kind in declarator!");
   3467     }
   3468   };
   3469 }
   3470 
   3471 /// \brief Create and instantiate a TypeSourceInfo with type source information.
   3472 ///
   3473 /// \param T QualType referring to the type as written in source code.
   3474 ///
   3475 /// \param ReturnTypeInfo For declarators whose return type does not show
   3476 /// up in the normal place in the declaration specifiers (such as a C++
   3477 /// conversion function), this pointer will refer to a type source information
   3478 /// for that return type.
   3479 TypeSourceInfo *
   3480 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
   3481                                      TypeSourceInfo *ReturnTypeInfo) {
   3482   TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
   3483   UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
   3484 
   3485   // Handle parameter packs whose type is a pack expansion.
   3486   if (isa<PackExpansionType>(T)) {
   3487     CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
   3488     CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
   3489   }
   3490 
   3491   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
   3492     while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
   3493       fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs());
   3494       CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
   3495     }
   3496 
   3497     DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
   3498     CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
   3499   }
   3500 
   3501   // If we have different source information for the return type, use
   3502   // that.  This really only applies to C++ conversion functions.
   3503   if (ReturnTypeInfo) {
   3504     TypeLoc TL = ReturnTypeInfo->getTypeLoc();
   3505     assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
   3506     memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
   3507   } else {
   3508     TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
   3509   }
   3510 
   3511   return TInfo;
   3512 }
   3513 
   3514 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
   3515 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
   3516   // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
   3517   // and Sema during declaration parsing. Try deallocating/caching them when
   3518   // it's appropriate, instead of allocating them and keeping them around.
   3519   LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
   3520                                                        TypeAlignment);
   3521   new (LocT) LocInfoType(T, TInfo);
   3522   assert(LocT->getTypeClass() != T->getTypeClass() &&
   3523          "LocInfoType's TypeClass conflicts with an existing Type class");
   3524   return ParsedType::make(QualType(LocT, 0));
   3525 }
   3526 
   3527 void LocInfoType::getAsStringInternal(std::string &Str,
   3528                                       const PrintingPolicy &Policy) const {
   3529   llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
   3530          " was used directly instead of getting the QualType through"
   3531          " GetTypeFromParser");
   3532 }
   3533 
   3534 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
   3535   // C99 6.7.6: Type names have no identifier.  This is already validated by
   3536   // the parser.
   3537   assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
   3538 
   3539   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
   3540   QualType T = TInfo->getType();
   3541   if (D.isInvalidType())
   3542     return true;
   3543 
   3544   // Make sure there are no unused decl attributes on the declarator.
   3545   // We don't want to do this for ObjC parameters because we're going
   3546   // to apply them to the actual parameter declaration.
   3547   // Likewise, we don't want to do this for alias declarations, because
   3548   // we are actually going to build a declaration from this eventually.
   3549   if (D.getContext() != Declarator::ObjCParameterContext &&
   3550       D.getContext() != Declarator::AliasDeclContext &&
   3551       D.getContext() != Declarator::AliasTemplateContext)
   3552     checkUnusedDeclAttributes(D);
   3553 
   3554   if (getLangOpts().CPlusPlus) {
   3555     // Check that there are no default arguments (C++ only).
   3556     CheckExtraCXXDefaultArguments(D);
   3557   }
   3558 
   3559   return CreateParsedType(T, TInfo);
   3560 }
   3561 
   3562 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
   3563   QualType T = Context.getObjCInstanceType();
   3564   TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
   3565   return CreateParsedType(T, TInfo);
   3566 }
   3567 
   3568 
   3569 //===----------------------------------------------------------------------===//
   3570 // Type Attribute Processing
   3571 //===----------------------------------------------------------------------===//
   3572 
   3573 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
   3574 /// specified type.  The attribute contains 1 argument, the id of the address
   3575 /// space for the type.
   3576 static void HandleAddressSpaceTypeAttribute(QualType &Type,
   3577                                             const AttributeList &Attr, Sema &S){
   3578 
   3579   // If this type is already address space qualified, reject it.
   3580   // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
   3581   // qualifiers for two or more different address spaces."
   3582   if (Type.getAddressSpace()) {
   3583     S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
   3584     Attr.setInvalid();
   3585     return;
   3586   }
   3587 
   3588   // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
   3589   // qualified by an address-space qualifier."
   3590   if (Type->isFunctionType()) {
   3591     S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
   3592     Attr.setInvalid();
   3593     return;
   3594   }
   3595 
   3596   // Check the attribute arguments.
   3597   if (Attr.getNumArgs() != 1) {
   3598     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
   3599     Attr.setInvalid();
   3600     return;
   3601   }
   3602   Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
   3603   llvm::APSInt addrSpace(32);
   3604   if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
   3605       !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
   3606     S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
   3607       << ASArgExpr->getSourceRange();
   3608     Attr.setInvalid();
   3609     return;
   3610   }
   3611 
   3612   // Bounds checking.
   3613   if (addrSpace.isSigned()) {
   3614     if (addrSpace.isNegative()) {
   3615       S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
   3616         << ASArgExpr->getSourceRange();
   3617       Attr.setInvalid();
   3618       return;
   3619     }
   3620     addrSpace.setIsSigned(false);
   3621   }
   3622   llvm::APSInt max(addrSpace.getBitWidth());
   3623   max = Qualifiers::MaxAddressSpace;
   3624   if (addrSpace > max) {
   3625     S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
   3626       << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
   3627     Attr.setInvalid();
   3628     return;
   3629   }
   3630 
   3631   unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
   3632   Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
   3633 }
   3634 
   3635 /// Does this type have a "direct" ownership qualifier?  That is,
   3636 /// is it written like "__strong id", as opposed to something like
   3637 /// "typeof(foo)", where that happens to be strong?
   3638 static bool hasDirectOwnershipQualifier(QualType type) {
   3639   // Fast path: no qualifier at all.
   3640   assert(type.getQualifiers().hasObjCLifetime());
   3641 
   3642   while (true) {
   3643     // __strong id
   3644     if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
   3645       if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
   3646         return true;
   3647 
   3648       type = attr->getModifiedType();
   3649 
   3650     // X *__strong (...)
   3651     } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
   3652       type = paren->getInnerType();
   3653 
   3654     // That's it for things we want to complain about.  In particular,
   3655     // we do not want to look through typedefs, typeof(expr),
   3656     // typeof(type), or any other way that the type is somehow
   3657     // abstracted.
   3658     } else {
   3659 
   3660       return false;
   3661     }
   3662   }
   3663 }
   3664 
   3665 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
   3666 /// attribute on the specified type.
   3667 ///
   3668 /// Returns 'true' if the attribute was handled.
   3669 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
   3670                                        AttributeList &attr,
   3671                                        QualType &type) {
   3672   bool NonObjCPointer = false;
   3673 
   3674   if (!type->isDependentType()) {
   3675     if (const PointerType *ptr = type->getAs<PointerType>()) {
   3676       QualType pointee = ptr->getPointeeType();
   3677       if (pointee->isObjCRetainableType() || pointee->isPointerType())
   3678         return false;
   3679       // It is important not to lose the source info that there was an attribute
   3680       // applied to non-objc pointer. We will create an attributed type but
   3681       // its type will be the same as the original type.
   3682       NonObjCPointer = true;
   3683     } else if (!type->isObjCRetainableType()) {
   3684       return false;
   3685     }
   3686 
   3687     // Don't accept an ownership attribute in the declspec if it would
   3688     // just be the return type of a block pointer.
   3689     if (state.isProcessingDeclSpec()) {
   3690       Declarator &D = state.getDeclarator();
   3691       if (maybeMovePastReturnType(D, D.getNumTypeObjects()))
   3692         return false;
   3693     }
   3694   }
   3695 
   3696   Sema &S = state.getSema();
   3697   SourceLocation AttrLoc = attr.getLoc();
   3698   if (AttrLoc.isMacroID())
   3699     AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
   3700 
   3701   if (!attr.getParameterName()) {
   3702     S.Diag(AttrLoc, diag::err_attribute_argument_n_not_string)
   3703       << "objc_ownership" << 1;
   3704     attr.setInvalid();
   3705     return true;
   3706   }
   3707 
   3708   // Consume lifetime attributes without further comment outside of
   3709   // ARC mode.
   3710   if (!S.getLangOpts().ObjCAutoRefCount)
   3711     return true;
   3712 
   3713   Qualifiers::ObjCLifetime lifetime;
   3714   if (attr.getParameterName()->isStr("none"))
   3715     lifetime = Qualifiers::OCL_ExplicitNone;
   3716   else if (attr.getParameterName()->isStr("strong"))
   3717     lifetime = Qualifiers::OCL_Strong;
   3718   else if (attr.getParameterName()->isStr("weak"))
   3719     lifetime = Qualifiers::OCL_Weak;
   3720   else if (attr.getParameterName()->isStr("autoreleasing"))
   3721     lifetime = Qualifiers::OCL_Autoreleasing;
   3722   else {
   3723     S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
   3724       << "objc_ownership" << attr.getParameterName();
   3725     attr.setInvalid();
   3726     return true;
   3727   }
   3728 
   3729   SplitQualType underlyingType = type.split();
   3730 
   3731   // Check for redundant/conflicting ownership qualifiers.
   3732   if (Qualifiers::ObjCLifetime previousLifetime
   3733         = type.getQualifiers().getObjCLifetime()) {
   3734     // If it's written directly, that's an error.
   3735     if (hasDirectOwnershipQualifier(type)) {
   3736       S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
   3737         << type;
   3738       return true;
   3739     }
   3740 
   3741     // Otherwise, if the qualifiers actually conflict, pull sugar off
   3742     // until we reach a type that is directly qualified.
   3743     if (previousLifetime != lifetime) {
   3744       // This should always terminate: the canonical type is
   3745       // qualified, so some bit of sugar must be hiding it.
   3746       while (!underlyingType.Quals.hasObjCLifetime()) {
   3747         underlyingType = underlyingType.getSingleStepDesugaredType();
   3748       }
   3749       underlyingType.Quals.removeObjCLifetime();
   3750     }
   3751   }
   3752 
   3753   underlyingType.Quals.addObjCLifetime(lifetime);
   3754 
   3755   if (NonObjCPointer) {
   3756     StringRef name = attr.getName()->getName();
   3757     switch (lifetime) {
   3758     case Qualifiers::OCL_None:
   3759     case Qualifiers::OCL_ExplicitNone:
   3760       break;
   3761     case Qualifiers::OCL_Strong: name = "__strong"; break;
   3762     case Qualifiers::OCL_Weak: name = "__weak"; break;
   3763     case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
   3764     }
   3765     S.Diag(AttrLoc, diag::warn_objc_object_attribute_wrong_type)
   3766       << name << type;
   3767   }
   3768 
   3769   QualType origType = type;
   3770   if (!NonObjCPointer)
   3771     type = S.Context.getQualifiedType(underlyingType);
   3772 
   3773   // If we have a valid source location for the attribute, use an
   3774   // AttributedType instead.
   3775   if (AttrLoc.isValid())
   3776     type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
   3777                                        origType, type);
   3778 
   3779   // Forbid __weak if the runtime doesn't support it.
   3780   if (lifetime == Qualifiers::OCL_Weak &&
   3781       !S.getLangOpts().ObjCARCWeak && !NonObjCPointer) {
   3782 
   3783     // Actually, delay this until we know what we're parsing.
   3784     if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
   3785       S.DelayedDiagnostics.add(
   3786           sema::DelayedDiagnostic::makeForbiddenType(
   3787               S.getSourceManager().getExpansionLoc(AttrLoc),
   3788               diag::err_arc_weak_no_runtime, type, /*ignored*/ 0));
   3789     } else {
   3790       S.Diag(AttrLoc, diag::err_arc_weak_no_runtime);
   3791     }
   3792 
   3793     attr.setInvalid();
   3794     return true;
   3795   }
   3796 
   3797   // Forbid __weak for class objects marked as
   3798   // objc_arc_weak_reference_unavailable
   3799   if (lifetime == Qualifiers::OCL_Weak) {
   3800     if (const ObjCObjectPointerType *ObjT =
   3801           type->getAs<ObjCObjectPointerType>()) {
   3802       if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
   3803         if (Class->isArcWeakrefUnavailable()) {
   3804             S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
   3805             S.Diag(ObjT->getInterfaceDecl()->getLocation(),
   3806                    diag::note_class_declared);
   3807         }
   3808       }
   3809     }
   3810   }
   3811 
   3812   return true;
   3813 }
   3814 
   3815 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
   3816 /// attribute on the specified type.  Returns true to indicate that
   3817 /// the attribute was handled, false to indicate that the type does
   3818 /// not permit the attribute.
   3819 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
   3820                                  AttributeList &attr,
   3821                                  QualType &type) {
   3822   Sema &S = state.getSema();
   3823 
   3824   // Delay if this isn't some kind of pointer.
   3825   if (!type->isPointerType() &&
   3826       !type->isObjCObjectPointerType() &&
   3827       !type->isBlockPointerType())
   3828     return false;
   3829 
   3830   if (type.getObjCGCAttr() != Qualifiers::GCNone) {
   3831     S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
   3832     attr.setInvalid();
   3833     return true;
   3834   }
   3835 
   3836   // Check the attribute arguments.
   3837   if (!attr.getParameterName()) {
   3838     S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
   3839       << "objc_gc" << 1;
   3840     attr.setInvalid();
   3841     return true;
   3842   }
   3843   Qualifiers::GC GCAttr;
   3844   if (attr.getNumArgs() != 0) {
   3845     S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
   3846     attr.setInvalid();
   3847     return true;
   3848   }
   3849   if (attr.getParameterName()->isStr("weak"))
   3850     GCAttr = Qualifiers::Weak;
   3851   else if (attr.getParameterName()->isStr("strong"))
   3852     GCAttr = Qualifiers::Strong;
   3853   else {
   3854     S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
   3855       << "objc_gc" << attr.getParameterName();
   3856     attr.setInvalid();
   3857     return true;
   3858   }
   3859 
   3860   QualType origType = type;
   3861   type = S.Context.getObjCGCQualType(origType, GCAttr);
   3862 
   3863   // Make an attributed type to preserve the source information.
   3864   if (attr.getLoc().isValid())
   3865     type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
   3866                                        origType, type);
   3867 
   3868   return true;
   3869 }
   3870 
   3871 namespace {
   3872   /// A helper class to unwrap a type down to a function for the
   3873   /// purposes of applying attributes there.
   3874   ///
   3875   /// Use:
   3876   ///   FunctionTypeUnwrapper unwrapped(SemaRef, T);
   3877   ///   if (unwrapped.isFunctionType()) {
   3878   ///     const FunctionType *fn = unwrapped.get();
   3879   ///     // change fn somehow
   3880   ///     T = unwrapped.wrap(fn);
   3881   ///   }
   3882   struct FunctionTypeUnwrapper {
   3883     enum WrapKind {
   3884       Desugar,
   3885       Parens,
   3886       Pointer,
   3887       BlockPointer,
   3888       Reference,
   3889       MemberPointer
   3890     };
   3891 
   3892     QualType Original;
   3893     const FunctionType *Fn;
   3894     SmallVector<unsigned char /*WrapKind*/, 8> Stack;
   3895 
   3896     FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
   3897       while (true) {
   3898         const Type *Ty = T.getTypePtr();
   3899         if (isa<FunctionType>(Ty)) {
   3900           Fn = cast<FunctionType>(Ty);
   3901           return;
   3902         } else if (isa<ParenType>(Ty)) {
   3903           T = cast<ParenType>(Ty)->getInnerType();
   3904           Stack.push_back(Parens);
   3905         } else if (isa<PointerType>(Ty)) {
   3906           T = cast<PointerType>(Ty)->getPointeeType();
   3907           Stack.push_back(Pointer);
   3908         } else if (isa<BlockPointerType>(Ty)) {
   3909           T = cast<BlockPointerType>(Ty)->getPointeeType();
   3910           Stack.push_back(BlockPointer);
   3911         } else if (isa<MemberPointerType>(Ty)) {
   3912           T = cast<MemberPointerType>(Ty)->getPointeeType();
   3913           Stack.push_back(MemberPointer);
   3914         } else if (isa<ReferenceType>(Ty)) {
   3915           T = cast<ReferenceType>(Ty)->getPointeeType();
   3916           Stack.push_back(Reference);
   3917         } else {
   3918           const Type *DTy = Ty->getUnqualifiedDesugaredType();
   3919           if (Ty == DTy) {
   3920             Fn = 0;
   3921             return;
   3922           }
   3923 
   3924           T = QualType(DTy, 0);
   3925           Stack.push_back(Desugar);
   3926         }
   3927       }
   3928     }
   3929 
   3930     bool isFunctionType() const { return (Fn != 0); }
   3931     const FunctionType *get() const { return Fn; }
   3932 
   3933     QualType wrap(Sema &S, const FunctionType *New) {
   3934       // If T wasn't modified from the unwrapped type, do nothing.
   3935       if (New == get()) return Original;
   3936 
   3937       Fn = New;
   3938       return wrap(S.Context, Original, 0);
   3939     }
   3940 
   3941   private:
   3942     QualType wrap(ASTContext &C, QualType Old, unsigned I) {
   3943       if (I == Stack.size())
   3944         return C.getQualifiedType(Fn, Old.getQualifiers());
   3945 
   3946       // Build up the inner type, applying the qualifiers from the old
   3947       // type to the new type.
   3948       SplitQualType SplitOld = Old.split();
   3949 
   3950       // As a special case, tail-recurse if there are no qualifiers.
   3951       if (SplitOld.Quals.empty())
   3952         return wrap(C, SplitOld.Ty, I);
   3953       return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
   3954     }
   3955 
   3956     QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
   3957       if (I == Stack.size()) return QualType(Fn, 0);
   3958 
   3959       switch (static_cast<WrapKind>(Stack[I++])) {
   3960       case Desugar:
   3961         // This is the point at which we potentially lose source
   3962         // information.
   3963         return wrap(C, Old->getUnqualifiedDesugaredType(), I);
   3964 
   3965       case Parens: {
   3966         QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
   3967         return C.getParenType(New);
   3968       }
   3969 
   3970       case Pointer: {
   3971         QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
   3972         return C.getPointerType(New);
   3973       }
   3974 
   3975       case BlockPointer: {
   3976         QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
   3977         return C.getBlockPointerType(New);
   3978       }
   3979 
   3980       case MemberPointer: {
   3981         const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
   3982         QualType New = wrap(C, OldMPT->getPointeeType(), I);
   3983         return C.getMemberPointerType(New, OldMPT->getClass());
   3984       }
   3985 
   3986       case Reference: {
   3987         const ReferenceType *OldRef = cast<ReferenceType>(Old);
   3988         QualType New = wrap(C, OldRef->getPointeeType(), I);
   3989         if (isa<LValueReferenceType>(OldRef))
   3990           return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
   3991         else
   3992           return C.getRValueReferenceType(New);
   3993       }
   3994       }
   3995 
   3996       llvm_unreachable("unknown wrapping kind");
   3997     }
   3998   };
   3999 }
   4000 
   4001 /// Process an individual function attribute.  Returns true to
   4002 /// indicate that the attribute was handled, false if it wasn't.
   4003 static bool handleFunctionTypeAttr(TypeProcessingState &state,
   4004                                    AttributeList &attr,
   4005                                    QualType &type) {
   4006   Sema &S = state.getSema();
   4007 
   4008   FunctionTypeUnwrapper unwrapped(S, type);
   4009 
   4010   if (attr.getKind() == AttributeList::AT_NoReturn) {
   4011     if (S.CheckNoReturnAttr(attr))
   4012       return true;
   4013 
   4014     // Delay if this is not a function type.
   4015     if (!unwrapped.isFunctionType())
   4016       return false;
   4017 
   4018     // Otherwise we can process right away.
   4019     FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
   4020     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
   4021     return true;
   4022   }
   4023 
   4024   // ns_returns_retained is not always a type attribute, but if we got
   4025   // here, we're treating it as one right now.
   4026   if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
   4027     assert(S.getLangOpts().ObjCAutoRefCount &&
   4028            "ns_returns_retained treated as type attribute in non-ARC");
   4029     if (attr.getNumArgs()) return true;
   4030 
   4031     // Delay if this is not a function type.
   4032     if (!unwrapped.isFunctionType())
   4033       return false;
   4034 
   4035     FunctionType::ExtInfo EI
   4036       = unwrapped.get()->getExtInfo().withProducesResult(true);
   4037     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
   4038     return true;
   4039   }
   4040 
   4041   if (attr.getKind() == AttributeList::AT_Regparm) {
   4042     unsigned value;
   4043     if (S.CheckRegparmAttr(attr, value))
   4044       return true;
   4045 
   4046     // Delay if this is not a function type.
   4047     if (!unwrapped.isFunctionType())
   4048       return false;
   4049 
   4050     // Diagnose regparm with fastcall.
   4051     const FunctionType *fn = unwrapped.get();
   4052     CallingConv CC = fn->getCallConv();
   4053     if (CC == CC_X86FastCall) {
   4054       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
   4055         << FunctionType::getNameForCallConv(CC)
   4056         << "regparm";
   4057       attr.setInvalid();
   4058       return true;
   4059     }
   4060 
   4061     FunctionType::ExtInfo EI =
   4062       unwrapped.get()->getExtInfo().withRegParm(value);
   4063     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
   4064     return true;
   4065   }
   4066 
   4067   // Delay if the type didn't work out to a function.
   4068   if (!unwrapped.isFunctionType()) return false;
   4069 
   4070   // Otherwise, a calling convention.
   4071   CallingConv CC;
   4072   if (S.CheckCallingConvAttr(attr, CC))
   4073     return true;
   4074 
   4075   const FunctionType *fn = unwrapped.get();
   4076   CallingConv CCOld = fn->getCallConv();
   4077   if (S.Context.getCanonicalCallConv(CC) ==
   4078       S.Context.getCanonicalCallConv(CCOld)) {
   4079     FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC);
   4080     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
   4081     return true;
   4082   }
   4083 
   4084   if (CCOld != (S.LangOpts.MRTD ? CC_X86StdCall : CC_Default)) {
   4085     // Should we diagnose reapplications of the same convention?
   4086     S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
   4087       << FunctionType::getNameForCallConv(CC)
   4088       << FunctionType::getNameForCallConv(CCOld);
   4089     attr.setInvalid();
   4090     return true;
   4091   }
   4092 
   4093   // Diagnose the use of X86 fastcall on varargs or unprototyped functions.
   4094   if (CC == CC_X86FastCall) {
   4095     if (isa<FunctionNoProtoType>(fn)) {
   4096       S.Diag(attr.getLoc(), diag::err_cconv_knr)
   4097         << FunctionType::getNameForCallConv(CC);
   4098       attr.setInvalid();
   4099       return true;
   4100     }
   4101 
   4102     const FunctionProtoType *FnP = cast<FunctionProtoType>(fn);
   4103     if (FnP->isVariadic()) {
   4104       S.Diag(attr.getLoc(), diag::err_cconv_varargs)
   4105         << FunctionType::getNameForCallConv(CC);
   4106       attr.setInvalid();
   4107       return true;
   4108     }
   4109 
   4110     // Also diagnose fastcall with regparm.
   4111     if (fn->getHasRegParm()) {
   4112       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
   4113         << "regparm"
   4114         << FunctionType::getNameForCallConv(CC);
   4115       attr.setInvalid();
   4116       return true;
   4117     }
   4118   }
   4119 
   4120   FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
   4121   type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
   4122   return true;
   4123 }
   4124 
   4125 /// Handle OpenCL image access qualifiers: read_only, write_only, read_write
   4126 static void HandleOpenCLImageAccessAttribute(QualType& CurType,
   4127                                              const AttributeList &Attr,
   4128                                              Sema &S) {
   4129   // Check the attribute arguments.
   4130   if (Attr.getNumArgs() != 1) {
   4131     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
   4132     Attr.setInvalid();
   4133     return;
   4134   }
   4135   Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
   4136   llvm::APSInt arg(32);
   4137   if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
   4138       !sizeExpr->isIntegerConstantExpr(arg, S.Context)) {
   4139     S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
   4140       << "opencl_image_access" << sizeExpr->getSourceRange();
   4141     Attr.setInvalid();
   4142     return;
   4143   }
   4144   unsigned iarg = static_cast<unsigned>(arg.getZExtValue());
   4145   switch (iarg) {
   4146   case CLIA_read_only:
   4147   case CLIA_write_only:
   4148   case CLIA_read_write:
   4149     // Implemented in a separate patch
   4150     break;
   4151   default:
   4152     // Implemented in a separate patch
   4153     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
   4154       << sizeExpr->getSourceRange();
   4155     Attr.setInvalid();
   4156     break;
   4157   }
   4158 }
   4159 
   4160 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
   4161 /// and float scalars, although arrays, pointers, and function return values are
   4162 /// allowed in conjunction with this construct. Aggregates with this attribute
   4163 /// are invalid, even if they are of the same size as a corresponding scalar.
   4164 /// The raw attribute should contain precisely 1 argument, the vector size for
   4165 /// the variable, measured in bytes. If curType and rawAttr are well formed,
   4166 /// this routine will return a new vector type.
   4167 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
   4168                                  Sema &S) {
   4169   // Check the attribute arguments.
   4170   if (Attr.getNumArgs() != 1) {
   4171     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
   4172     Attr.setInvalid();
   4173     return;
   4174   }
   4175   Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
   4176   llvm::APSInt vecSize(32);
   4177   if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
   4178       !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
   4179     S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
   4180       << "vector_size" << sizeExpr->getSourceRange();
   4181     Attr.setInvalid();
   4182     return;
   4183   }
   4184   // the base type must be integer or float, and can't already be a vector.
   4185   if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) {
   4186     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
   4187     Attr.setInvalid();
   4188     return;
   4189   }
   4190   unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
   4191   // vecSize is specified in bytes - convert to bits.
   4192   unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
   4193 
   4194   // the vector size needs to be an integral multiple of the type size.
   4195   if (vectorSize % typeSize) {
   4196     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
   4197       << sizeExpr->getSourceRange();
   4198     Attr.setInvalid();
   4199     return;
   4200   }
   4201   if (vectorSize == 0) {
   4202     S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
   4203       << sizeExpr->getSourceRange();
   4204     Attr.setInvalid();
   4205     return;
   4206   }
   4207 
   4208   // Success! Instantiate the vector type, the number of elements is > 0, and
   4209   // not required to be a power of 2, unlike GCC.
   4210   CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
   4211                                     VectorType::GenericVector);
   4212 }
   4213 
   4214 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
   4215 /// a type.
   4216 static void HandleExtVectorTypeAttr(QualType &CurType,
   4217                                     const AttributeList &Attr,
   4218                                     Sema &S) {
   4219   Expr *sizeExpr;
   4220 
   4221   // Special case where the argument is a template id.
   4222   if (Attr.getParameterName()) {
   4223     CXXScopeSpec SS;
   4224     SourceLocation TemplateKWLoc;
   4225     UnqualifiedId id;
   4226     id.setIdentifier(Attr.getParameterName(), Attr.getLoc());
   4227 
   4228     ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
   4229                                           id, false, false);
   4230     if (Size.isInvalid())
   4231       return;
   4232 
   4233     sizeExpr = Size.get();
   4234   } else {
   4235     // check the attribute arguments.
   4236     if (Attr.getNumArgs() != 1) {
   4237       S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
   4238       return;
   4239     }
   4240     sizeExpr = Attr.getArg(0);
   4241   }
   4242 
   4243   // Create the vector type.
   4244   QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
   4245   if (!T.isNull())
   4246     CurType = T;
   4247 }
   4248 
   4249 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
   4250 /// "neon_polyvector_type" attributes are used to create vector types that
   4251 /// are mangled according to ARM's ABI.  Otherwise, these types are identical
   4252 /// to those created with the "vector_size" attribute.  Unlike "vector_size"
   4253 /// the argument to these Neon attributes is the number of vector elements,
   4254 /// not the vector size in bytes.  The vector width and element type must
   4255 /// match one of the standard Neon vector types.
   4256 static void HandleNeonVectorTypeAttr(QualType& CurType,
   4257                                      const AttributeList &Attr, Sema &S,
   4258                                      VectorType::VectorKind VecKind,
   4259                                      const char *AttrName) {
   4260   // Check the attribute arguments.
   4261   if (Attr.getNumArgs() != 1) {
   4262     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
   4263     Attr.setInvalid();
   4264     return;
   4265   }
   4266   // The number of elements must be an ICE.
   4267   Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0));
   4268   llvm::APSInt numEltsInt(32);
   4269   if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
   4270       !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
   4271     S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
   4272       << AttrName << numEltsExpr->getSourceRange();
   4273     Attr.setInvalid();
   4274     return;
   4275   }
   4276   // Only certain element types are supported for Neon vectors.
   4277   const BuiltinType* BTy = CurType->getAs<BuiltinType>();
   4278   if (!BTy ||
   4279       (VecKind == VectorType::NeonPolyVector &&
   4280        BTy->getKind() != BuiltinType::SChar &&
   4281        BTy->getKind() != BuiltinType::Short) ||
   4282       (BTy->getKind() != BuiltinType::SChar &&
   4283        BTy->getKind() != BuiltinType::UChar &&
   4284        BTy->getKind() != BuiltinType::Short &&
   4285        BTy->getKind() != BuiltinType::UShort &&
   4286        BTy->getKind() != BuiltinType::Int &&
   4287        BTy->getKind() != BuiltinType::UInt &&
   4288        BTy->getKind() != BuiltinType::LongLong &&
   4289        BTy->getKind() != BuiltinType::ULongLong &&
   4290        BTy->getKind() != BuiltinType::Float)) {
   4291     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType;
   4292     Attr.setInvalid();
   4293     return;
   4294   }
   4295   // The total size of the vector must be 64 or 128 bits.
   4296   unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
   4297   unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
   4298   unsigned vecSize = typeSize * numElts;
   4299   if (vecSize != 64 && vecSize != 128) {
   4300     S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
   4301     Attr.setInvalid();
   4302     return;
   4303   }
   4304 
   4305   CurType = S.Context.getVectorType(CurType, numElts, VecKind);
   4306 }
   4307 
   4308 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
   4309                              TypeAttrLocation TAL, AttributeList *attrs) {
   4310   // Scan through and apply attributes to this type where it makes sense.  Some
   4311   // attributes (such as __address_space__, __vector_size__, etc) apply to the
   4312   // type, but others can be present in the type specifiers even though they
   4313   // apply to the decl.  Here we apply type attributes and ignore the rest.
   4314 
   4315   AttributeList *next;
   4316   do {
   4317     AttributeList &attr = *attrs;
   4318     next = attr.getNext();
   4319 
   4320     // Skip attributes that were marked to be invalid.
   4321     if (attr.isInvalid())
   4322       continue;
   4323 
   4324     if (attr.isCXX11Attribute()) {
   4325       // [[gnu::...]] attributes are treated as declaration attributes, so may
   4326       // not appertain to a DeclaratorChunk, even if we handle them as type
   4327       // attributes.
   4328       if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
   4329         if (TAL == TAL_DeclChunk) {
   4330           state.getSema().Diag(attr.getLoc(),
   4331                                diag::warn_cxx11_gnu_attribute_on_type)
   4332               << attr.getName();
   4333           continue;
   4334         }
   4335       } else if (TAL != TAL_DeclChunk) {
   4336         // Otherwise, only consider type processing for a C++11 attribute if
   4337         // it's actually been applied to a type.
   4338         continue;
   4339       }
   4340     }
   4341 
   4342     // If this is an attribute we can handle, do so now,
   4343     // otherwise, add it to the FnAttrs list for rechaining.
   4344     switch (attr.getKind()) {
   4345     default:
   4346       // A C++11 attribute on a declarator chunk must appertain to a type.
   4347       if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
   4348         state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
   4349           << attr.getName();
   4350         attr.setUsedAsTypeAttr();
   4351       }
   4352       break;
   4353 
   4354     case AttributeList::UnknownAttribute:
   4355       if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
   4356         state.getSema().Diag(attr.getLoc(),
   4357                              diag::warn_unknown_attribute_ignored)
   4358           << attr.getName();
   4359       break;
   4360 
   4361     case AttributeList::IgnoredAttribute:
   4362       break;
   4363 
   4364     case AttributeList::AT_MayAlias:
   4365       // FIXME: This attribute needs to actually be handled, but if we ignore
   4366       // it it breaks large amounts of Linux software.
   4367       attr.setUsedAsTypeAttr();
   4368       break;
   4369     case AttributeList::AT_AddressSpace:
   4370       HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
   4371       attr.setUsedAsTypeAttr();
   4372       break;
   4373     OBJC_POINTER_TYPE_ATTRS_CASELIST:
   4374       if (!handleObjCPointerTypeAttr(state, attr, type))
   4375         distributeObjCPointerTypeAttr(state, attr, type);
   4376       attr.setUsedAsTypeAttr();
   4377       break;
   4378     case AttributeList::AT_VectorSize:
   4379       HandleVectorSizeAttr(type, attr, state.getSema());
   4380       attr.setUsedAsTypeAttr();
   4381       break;
   4382     case AttributeList::AT_ExtVectorType:
   4383       HandleExtVectorTypeAttr(type, attr, state.getSema());
   4384       attr.setUsedAsTypeAttr();
   4385       break;
   4386     case AttributeList::AT_NeonVectorType:
   4387       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
   4388                                VectorType::NeonVector, "neon_vector_type");
   4389       attr.setUsedAsTypeAttr();
   4390       break;
   4391     case AttributeList::AT_NeonPolyVectorType:
   4392       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
   4393                                VectorType::NeonPolyVector,
   4394                                "neon_polyvector_type");
   4395       attr.setUsedAsTypeAttr();
   4396       break;
   4397     case AttributeList::AT_OpenCLImageAccess:
   4398       HandleOpenCLImageAccessAttribute(type, attr, state.getSema());
   4399       attr.setUsedAsTypeAttr();
   4400       break;
   4401 
   4402     case AttributeList::AT_Win64:
   4403     case AttributeList::AT_Ptr32:
   4404     case AttributeList::AT_Ptr64:
   4405       // FIXME: Don't ignore these. We have partial handling for them as
   4406       // declaration attributes in SemaDeclAttr.cpp; that should be moved here.
   4407       attr.setUsedAsTypeAttr();
   4408       break;
   4409 
   4410     case AttributeList::AT_NSReturnsRetained:
   4411       if (!state.getSema().getLangOpts().ObjCAutoRefCount)
   4412         break;
   4413       // fallthrough into the function attrs
   4414 
   4415     FUNCTION_TYPE_ATTRS_CASELIST:
   4416       attr.setUsedAsTypeAttr();
   4417 
   4418       // Never process function type attributes as part of the
   4419       // declaration-specifiers.
   4420       if (TAL == TAL_DeclSpec)
   4421         distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
   4422 
   4423       // Otherwise, handle the possible delays.
   4424       else if (!handleFunctionTypeAttr(state, attr, type))
   4425         distributeFunctionTypeAttr(state, attr, type);
   4426       break;
   4427     }
   4428   } while ((attrs = next));
   4429 }
   4430 
   4431 /// \brief Ensure that the type of the given expression is complete.
   4432 ///
   4433 /// This routine checks whether the expression \p E has a complete type. If the
   4434 /// expression refers to an instantiable construct, that instantiation is
   4435 /// performed as needed to complete its type. Furthermore
   4436 /// Sema::RequireCompleteType is called for the expression's type (or in the
   4437 /// case of a reference type, the referred-to type).
   4438 ///
   4439 /// \param E The expression whose type is required to be complete.
   4440 /// \param Diagnoser The object that will emit a diagnostic if the type is
   4441 /// incomplete.
   4442 ///
   4443 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
   4444 /// otherwise.
   4445 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser){
   4446   QualType T = E->getType();
   4447 
   4448   // Fast path the case where the type is already complete.
   4449   if (!T->isIncompleteType())
   4450     return false;
   4451 
   4452   // Incomplete array types may be completed by the initializer attached to
   4453   // their definitions. For static data members of class templates we need to
   4454   // instantiate the definition to get this initializer and complete the type.
   4455   if (T->isIncompleteArrayType()) {
   4456     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
   4457       if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
   4458         if (Var->isStaticDataMember() &&
   4459             Var->getInstantiatedFromStaticDataMember()) {
   4460 
   4461           MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
   4462           assert(MSInfo && "Missing member specialization information?");
   4463           if (MSInfo->getTemplateSpecializationKind()
   4464                 != TSK_ExplicitSpecialization) {
   4465             // If we don't already have a point of instantiation, this is it.
   4466             if (MSInfo->getPointOfInstantiation().isInvalid()) {
   4467               MSInfo->setPointOfInstantiation(E->getLocStart());
   4468 
   4469               // This is a modification of an existing AST node. Notify
   4470               // listeners.
   4471               if (ASTMutationListener *L = getASTMutationListener())
   4472                 L->StaticDataMemberInstantiated(Var);
   4473             }
   4474 
   4475             InstantiateStaticDataMemberDefinition(E->getExprLoc(), Var);
   4476 
   4477             // Update the type to the newly instantiated definition's type both
   4478             // here and within the expression.
   4479             if (VarDecl *Def = Var->getDefinition()) {
   4480               DRE->setDecl(Def);
   4481               T = Def->getType();
   4482               DRE->setType(T);
   4483               E->setType(T);
   4484             }
   4485           }
   4486 
   4487           // We still go on to try to complete the type independently, as it
   4488           // may also require instantiations or diagnostics if it remains
   4489           // incomplete.
   4490         }
   4491       }
   4492     }
   4493   }
   4494 
   4495   // FIXME: Are there other cases which require instantiating something other
   4496   // than the type to complete the type of an expression?
   4497 
   4498   // Look through reference types and complete the referred type.
   4499   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
   4500     T = Ref->getPointeeType();
   4501 
   4502   return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
   4503 }
   4504 
   4505 namespace {
   4506   struct TypeDiagnoserDiag : Sema::TypeDiagnoser {
   4507     unsigned DiagID;
   4508 
   4509     TypeDiagnoserDiag(unsigned DiagID)
   4510       : Sema::TypeDiagnoser(DiagID == 0), DiagID(DiagID) {}
   4511 
   4512     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
   4513       if (Suppressed) return;
   4514       S.Diag(Loc, DiagID) << T;
   4515     }
   4516   };
   4517 }
   4518 
   4519 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
   4520   TypeDiagnoserDiag Diagnoser(DiagID);
   4521   return RequireCompleteExprType(E, Diagnoser);
   4522 }
   4523 
   4524 /// @brief Ensure that the type T is a complete type.
   4525 ///
   4526 /// This routine checks whether the type @p T is complete in any
   4527 /// context where a complete type is required. If @p T is a complete
   4528 /// type, returns false. If @p T is a class template specialization,
   4529 /// this routine then attempts to perform class template
   4530 /// instantiation. If instantiation fails, or if @p T is incomplete
   4531 /// and cannot be completed, issues the diagnostic @p diag (giving it
   4532 /// the type @p T) and returns true.
   4533 ///
   4534 /// @param Loc  The location in the source that the incomplete type
   4535 /// diagnostic should refer to.
   4536 ///
   4537 /// @param T  The type that this routine is examining for completeness.
   4538 ///
   4539 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
   4540 /// @c false otherwise.
   4541 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
   4542                                TypeDiagnoser &Diagnoser) {
   4543   // FIXME: Add this assertion to make sure we always get instantiation points.
   4544   //  assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
   4545   // FIXME: Add this assertion to help us flush out problems with
   4546   // checking for dependent types and type-dependent expressions.
   4547   //
   4548   //  assert(!T->isDependentType() &&
   4549   //         "Can't ask whether a dependent type is complete");
   4550 
   4551   // If we have a complete type, we're done.
   4552   NamedDecl *Def = 0;
   4553   if (!T->isIncompleteType(&Def)) {
   4554     // If we know about the definition but it is not visible, complain.
   4555     if (!Diagnoser.Suppressed && Def && !LookupResult::isVisible(Def)) {
   4556       // Suppress this error outside of a SFINAE context if we've already
   4557       // emitted the error once for this type. There's no usefulness in
   4558       // repeating the diagnostic.
   4559       // FIXME: Add a Fix-It that imports the corresponding module or includes
   4560       // the header.
   4561       Module *Owner = Def->getOwningModule();
   4562       Diag(Loc, diag::err_module_private_definition)
   4563         << T << Owner->getFullModuleName();
   4564       Diag(Def->getLocation(), diag::note_previous_definition);
   4565 
   4566       if (!isSFINAEContext()) {
   4567         // Recover by implicitly importing this module.
   4568         createImplicitModuleImport(Loc, Owner);
   4569       }
   4570     }
   4571 
   4572     return false;
   4573   }
   4574 
   4575   const TagType *Tag = T->getAs<TagType>();
   4576   const ObjCInterfaceType *IFace = 0;
   4577 
   4578   if (Tag) {
   4579     // Avoid diagnosing invalid decls as incomplete.
   4580     if (Tag->getDecl()->isInvalidDecl())
   4581       return true;
   4582 
   4583     // Give the external AST source a chance to complete the type.
   4584     if (Tag->getDecl()->hasExternalLexicalStorage()) {
   4585       Context.getExternalSource()->CompleteType(Tag->getDecl());
   4586       if (!Tag->isIncompleteType())
   4587         return false;
   4588     }
   4589   }
   4590   else if ((IFace = T->getAs<ObjCInterfaceType>())) {
   4591     // Avoid diagnosing invalid decls as incomplete.
   4592     if (IFace->getDecl()->isInvalidDecl())
   4593       return true;
   4594 
   4595     // Give the external AST source a chance to complete the type.
   4596     if (IFace->getDecl()->hasExternalLexicalStorage()) {
   4597       Context.getExternalSource()->CompleteType(IFace->getDecl());
   4598       if (!IFace->isIncompleteType())
   4599         return false;
   4600     }
   4601   }
   4602 
   4603   // If we have a class template specialization or a class member of a
   4604   // class template specialization, or an array with known size of such,
   4605   // try to instantiate it.
   4606   QualType MaybeTemplate = T;
   4607   while (const ConstantArrayType *Array
   4608            = Context.getAsConstantArrayType(MaybeTemplate))
   4609     MaybeTemplate = Array->getElementType();
   4610   if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
   4611     if (ClassTemplateSpecializationDecl *ClassTemplateSpec
   4612           = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
   4613       if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
   4614         return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
   4615                                                       TSK_ImplicitInstantiation,
   4616                                             /*Complain=*/!Diagnoser.Suppressed);
   4617     } else if (CXXRecordDecl *Rec
   4618                  = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
   4619       CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
   4620       if (!Rec->isBeingDefined() && Pattern) {
   4621         MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
   4622         assert(MSI && "Missing member specialization information?");
   4623         // This record was instantiated from a class within a template.
   4624         if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
   4625           return InstantiateClass(Loc, Rec, Pattern,
   4626                                   getTemplateInstantiationArgs(Rec),
   4627                                   TSK_ImplicitInstantiation,
   4628                                   /*Complain=*/!Diagnoser.Suppressed);
   4629       }
   4630     }
   4631   }
   4632 
   4633   if (Diagnoser.Suppressed)
   4634     return true;
   4635 
   4636   // We have an incomplete type. Produce a diagnostic.
   4637   Diagnoser.diagnose(*this, Loc, T);
   4638 
   4639   // If the type was a forward declaration of a class/struct/union
   4640   // type, produce a note.
   4641   if (Tag && !Tag->getDecl()->isInvalidDecl())
   4642     Diag(Tag->getDecl()->getLocation(),
   4643          Tag->isBeingDefined() ? diag::note_type_being_defined
   4644                                : diag::note_forward_declaration)
   4645       << QualType(Tag, 0);
   4646 
   4647   // If the Objective-C class was a forward declaration, produce a note.
   4648   if (IFace && !IFace->getDecl()->isInvalidDecl())
   4649     Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
   4650 
   4651   return true;
   4652 }
   4653 
   4654 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
   4655                                unsigned DiagID) {
   4656   TypeDiagnoserDiag Diagnoser(DiagID);
   4657   return RequireCompleteType(Loc, T, Diagnoser);
   4658 }
   4659 
   4660 /// \brief Get diagnostic %select index for tag kind for
   4661 /// literal type diagnostic message.
   4662 /// WARNING: Indexes apply to particular diagnostics only!
   4663 ///
   4664 /// \returns diagnostic %select index.
   4665 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
   4666   switch (Tag) {
   4667   case TTK_Struct: return 0;
   4668   case TTK_Interface: return 1;
   4669   case TTK_Class:  return 2;
   4670   default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
   4671   }
   4672 }
   4673 
   4674 /// @brief Ensure that the type T is a literal type.
   4675 ///
   4676 /// This routine checks whether the type @p T is a literal type. If @p T is an
   4677 /// incomplete type, an attempt is made to complete it. If @p T is a literal
   4678 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
   4679 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
   4680 /// it the type @p T), along with notes explaining why the type is not a
   4681 /// literal type, and returns true.
   4682 ///
   4683 /// @param Loc  The location in the source that the non-literal type
   4684 /// diagnostic should refer to.
   4685 ///
   4686 /// @param T  The type that this routine is examining for literalness.
   4687 ///
   4688 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
   4689 ///
   4690 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
   4691 /// @c false otherwise.
   4692 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
   4693                               TypeDiagnoser &Diagnoser) {
   4694   assert(!T->isDependentType() && "type should not be dependent");
   4695 
   4696   QualType ElemType = Context.getBaseElementType(T);
   4697   RequireCompleteType(Loc, ElemType, 0);
   4698 
   4699   if (T->isLiteralType())
   4700     return false;
   4701 
   4702   if (Diagnoser.Suppressed)
   4703     return true;
   4704 
   4705   Diagnoser.diagnose(*this, Loc, T);
   4706 
   4707   if (T->isVariableArrayType())
   4708     return true;
   4709 
   4710   const RecordType *RT = ElemType->getAs<RecordType>();
   4711   if (!RT)
   4712     return true;
   4713 
   4714   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
   4715 
   4716   // A partially-defined class type can't be a literal type, because a literal
   4717   // class type must have a trivial destructor (which can't be checked until
   4718   // the class definition is complete).
   4719   if (!RD->isCompleteDefinition()) {
   4720     RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T);
   4721     return true;
   4722   }
   4723 
   4724   // If the class has virtual base classes, then it's not an aggregate, and
   4725   // cannot have any constexpr constructors or a trivial default constructor,
   4726   // so is non-literal. This is better to diagnose than the resulting absence
   4727   // of constexpr constructors.
   4728   if (RD->getNumVBases()) {
   4729     Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
   4730       << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
   4731     for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
   4732            E = RD->vbases_end(); I != E; ++I)
   4733       Diag(I->getLocStart(),
   4734            diag::note_constexpr_virtual_base_here) << I->getSourceRange();
   4735   } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
   4736              !RD->hasTrivialDefaultConstructor()) {
   4737     Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
   4738   } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
   4739     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
   4740          E = RD->bases_end(); I != E; ++I) {
   4741       if (!I->getType()->isLiteralType()) {
   4742         Diag(I->getLocStart(),
   4743              diag::note_non_literal_base_class)
   4744           << RD << I->getType() << I->getSourceRange();
   4745         return true;
   4746       }
   4747     }
   4748     for (CXXRecordDecl::field_iterator I = RD->field_begin(),
   4749          E = RD->field_end(); I != E; ++I) {
   4750       if (!I->getType()->isLiteralType() ||
   4751           I->getType().isVolatileQualified()) {
   4752         Diag(I->getLocation(), diag::note_non_literal_field)
   4753           << RD << *I << I->getType()
   4754           << I->getType().isVolatileQualified();
   4755         return true;
   4756       }
   4757     }
   4758   } else if (!RD->hasTrivialDestructor()) {
   4759     // All fields and bases are of literal types, so have trivial destructors.
   4760     // If this class's destructor is non-trivial it must be user-declared.
   4761     CXXDestructorDecl *Dtor = RD->getDestructor();
   4762     assert(Dtor && "class has literal fields and bases but no dtor?");
   4763     if (!Dtor)
   4764       return true;
   4765 
   4766     Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
   4767          diag::note_non_literal_user_provided_dtor :
   4768          diag::note_non_literal_nontrivial_dtor) << RD;
   4769     if (!Dtor->isUserProvided())
   4770       SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true);
   4771   }
   4772 
   4773   return true;
   4774 }
   4775 
   4776 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
   4777   TypeDiagnoserDiag Diagnoser(DiagID);
   4778   return RequireLiteralType(Loc, T, Diagnoser);
   4779 }
   4780 
   4781 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
   4782 /// and qualified by the nested-name-specifier contained in SS.
   4783 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
   4784                                  const CXXScopeSpec &SS, QualType T) {
   4785   if (T.isNull())
   4786     return T;
   4787   NestedNameSpecifier *NNS;
   4788   if (SS.isValid())
   4789     NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
   4790   else {
   4791     if (Keyword == ETK_None)
   4792       return T;
   4793     NNS = 0;
   4794   }
   4795   return Context.getElaboratedType(Keyword, NNS, T);
   4796 }
   4797 
   4798 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
   4799   ExprResult ER = CheckPlaceholderExpr(E);
   4800   if (ER.isInvalid()) return QualType();
   4801   E = ER.take();
   4802 
   4803   if (!E->isTypeDependent()) {
   4804     QualType T = E->getType();
   4805     if (const TagType *TT = T->getAs<TagType>())
   4806       DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
   4807   }
   4808   return Context.getTypeOfExprType(E);
   4809 }
   4810 
   4811 /// getDecltypeForExpr - Given an expr, will return the decltype for
   4812 /// that expression, according to the rules in C++11
   4813 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
   4814 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
   4815   if (E->isTypeDependent())
   4816     return S.Context.DependentTy;
   4817 
   4818   // C++11 [dcl.type.simple]p4:
   4819   //   The type denoted by decltype(e) is defined as follows:
   4820   //
   4821   //     - if e is an unparenthesized id-expression or an unparenthesized class
   4822   //       member access (5.2.5), decltype(e) is the type of the entity named
   4823   //       by e. If there is no such entity, or if e names a set of overloaded
   4824   //       functions, the program is ill-formed;
   4825   //
   4826   // We apply the same rules for Objective-C ivar and property references.
   4827   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
   4828     if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
   4829       return VD->getType();
   4830   } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
   4831     if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
   4832       return FD->getType();
   4833   } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
   4834     return IR->getDecl()->getType();
   4835   } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
   4836     if (PR->isExplicitProperty())
   4837       return PR->getExplicitProperty()->getType();
   4838   }
   4839 
   4840   // C++11 [expr.lambda.prim]p18:
   4841   //   Every occurrence of decltype((x)) where x is a possibly
   4842   //   parenthesized id-expression that names an entity of automatic
   4843   //   storage duration is treated as if x were transformed into an
   4844   //   access to a corresponding data member of the closure type that
   4845   //   would have been declared if x were an odr-use of the denoted
   4846   //   entity.
   4847   using namespace sema;
   4848   if (S.getCurLambda()) {
   4849     if (isa<ParenExpr>(E)) {
   4850       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
   4851         if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
   4852           QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
   4853           if (!T.isNull())
   4854             return S.Context.getLValueReferenceType(T);
   4855         }
   4856       }
   4857     }
   4858   }
   4859 
   4860 
   4861   // C++11 [dcl.type.simple]p4:
   4862   //   [...]
   4863   QualType T = E->getType();
   4864   switch (E->getValueKind()) {
   4865   //     - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
   4866   //       type of e;
   4867   case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
   4868   //     - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
   4869   //       type of e;
   4870   case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
   4871   //  - otherwise, decltype(e) is the type of e.
   4872   case VK_RValue: break;
   4873   }
   4874 
   4875   return T;
   4876 }
   4877 
   4878 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) {
   4879   ExprResult ER = CheckPlaceholderExpr(E);
   4880   if (ER.isInvalid()) return QualType();
   4881   E = ER.take();
   4882 
   4883   return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
   4884 }
   4885 
   4886 QualType Sema::BuildUnaryTransformType(QualType BaseType,
   4887                                        UnaryTransformType::UTTKind UKind,
   4888                                        SourceLocation Loc) {
   4889   switch (UKind) {
   4890   case UnaryTransformType::EnumUnderlyingType:
   4891     if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
   4892       Diag(Loc, diag::err_only_enums_have_underlying_types);
   4893       return QualType();
   4894     } else {
   4895       QualType Underlying = BaseType;
   4896       if (!BaseType->isDependentType()) {
   4897         EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
   4898         assert(ED && "EnumType has no EnumDecl");
   4899         DiagnoseUseOfDecl(ED, Loc);
   4900         Underlying = ED->getIntegerType();
   4901       }
   4902       assert(!Underlying.isNull());
   4903       return Context.getUnaryTransformType(BaseType, Underlying,
   4904                                         UnaryTransformType::EnumUnderlyingType);
   4905     }
   4906   }
   4907   llvm_unreachable("unknown unary transform type");
   4908 }
   4909 
   4910 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
   4911   if (!T->isDependentType()) {
   4912     // FIXME: It isn't entirely clear whether incomplete atomic types
   4913     // are allowed or not; for simplicity, ban them for the moment.
   4914     if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
   4915       return QualType();
   4916 
   4917     int DisallowedKind = -1;
   4918     if (T->isArrayType())
   4919       DisallowedKind = 1;
   4920     else if (T->isFunctionType())
   4921       DisallowedKind = 2;
   4922     else if (T->isReferenceType())
   4923       DisallowedKind = 3;
   4924     else if (T->isAtomicType())
   4925       DisallowedKind = 4;
   4926     else if (T.hasQualifiers())
   4927       DisallowedKind = 5;
   4928     else if (!T.isTriviallyCopyableType(Context))
   4929       // Some other non-trivially-copyable type (probably a C++ class)
   4930       DisallowedKind = 6;
   4931 
   4932     if (DisallowedKind != -1) {
   4933       Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
   4934       return QualType();
   4935     }
   4936 
   4937     // FIXME: Do we need any handling for ARC here?
   4938   }
   4939 
   4940   // Build the pointer type.
   4941   return Context.getAtomicType(T);
   4942 }
   4943