ASTContext.cpp revision 708a86690469474f0a8149abca71aa4c62bf9710
15821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
25821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
35821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//                     The LLVM Compiler Infrastructure
45821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
55821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// This file is distributed under the University of Illinois Open Source
65821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// License. See LICENSE.TXT for details.
75821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
82a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)//===----------------------------------------------------------------------===//
92a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)//
102a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)//  This file implements the ASTContext interface.
112a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)//
125821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===----------------------------------------------------------------------===//
135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
142a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/AST/ASTContext.h"
152a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/AST/CharUnits.h"
162a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/AST/DeclCXX.h"
172a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/AST/DeclObjC.h"
182a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/AST/DeclTemplate.h"
192a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/AST/TypeLoc.h"
202a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/AST/Expr.h"
212a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/AST/ExprCXX.h"
222a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/AST/ExternalASTSource.h"
232a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/AST/ASTMutationListener.h"
242a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/AST/RecordLayout.h"
252a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/AST/Mangle.h"
262a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/Basic/Builtins.h"
272a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/Basic/SourceManager.h"
282a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/Basic/TargetInfo.h"
292a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "llvm/ADT/SmallString.h"
302a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "llvm/ADT/StringExtras.h"
312a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "llvm/Support/MathExtras.h"
322a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "llvm/Support/raw_ostream.h"
332a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "CXXABI.h"
342a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
352a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)using namespace clang;
362a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
372a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)unsigned ASTContext::NumImplicitDefaultConstructors;
382a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
392a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)unsigned ASTContext::NumImplicitCopyConstructors;
402a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
412a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)unsigned ASTContext::NumImplicitCopyAssignmentOperators;
422a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
432a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)unsigned ASTContext::NumImplicitDestructors;
442a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)unsigned ASTContext::NumImplicitDestructorsDeclared;
452a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
462a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)enum FloatingRank {
472a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  FloatRank, DoubleRank, LongDoubleRank
482a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)};
492a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
502a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)void
512a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
522a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                               TemplateTemplateParmDecl *Parm) {
532a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  ID.AddInteger(Parm->getDepth());
542a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  ID.AddInteger(Parm->getPosition());
552a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  ID.AddBoolean(Parm->isParameterPack());
562a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
572a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  TemplateParameterList *Params = Parm->getTemplateParameters();
582a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  ID.AddInteger(Params->size());
592a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  for (TemplateParameterList::const_iterator P = Params->begin(),
602a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                          PEnd = Params->end();
612a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)       P != PEnd; ++P) {
622a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
632a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      ID.AddInteger(0);
642a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      ID.AddBoolean(TTP->isParameterPack());
652a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      continue;
662a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    }
672a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
682a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
692a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      ID.AddInteger(1);
702a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      ID.AddBoolean(NTTP->isParameterPack());
712a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      ID.AddPointer(NTTP->getType().getAsOpaquePtr());
722a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      if (NTTP->isExpandedParameterPack()) {
732a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        ID.AddBoolean(true);
742a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        ID.AddInteger(NTTP->getNumExpansionTypes());
752a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
762a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
772a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      } else
782a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        ID.AddBoolean(false);
792a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      continue;
802a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    }
812a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
822a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
832a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    ID.AddInteger(2);
842a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Profile(ID, TTP);
852a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
862a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
872a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
882a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)TemplateTemplateParmDecl *
892a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)ASTContext::getCanonicalTemplateTemplateParmDecl(
902a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                          TemplateTemplateParmDecl *TTP) const {
912a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Check if we already have a canonical template template parameter.
922a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  llvm::FoldingSetNodeID ID;
932a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  CanonicalTemplateTemplateParm::Profile(ID, TTP);
942a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  void *InsertPos = 0;
952a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  CanonicalTemplateTemplateParm *Canonical
962a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
972a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (Canonical)
982a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return Canonical->getParam();
992a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1002a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Build a canonical template parameter list.
1012a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  TemplateParameterList *Params = TTP->getTemplateParameters();
1022a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  llvm::SmallVector<NamedDecl *, 4> CanonParams;
1032a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  CanonParams.reserve(Params->size());
1045821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  for (TemplateParameterList::const_iterator P = Params->begin(),
1055821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                          PEnd = Params->end();
1062a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)       P != PEnd; ++P) {
1072a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
1082a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      CanonParams.push_back(
1092a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                  TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
1102a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                               SourceLocation(), TTP->getDepth(),
1112a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                               TTP->getIndex(), 0, false,
1122a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                               TTP->isParameterPack()));
1132a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    else if (NonTypeTemplateParmDecl *NTTP
1142a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)             = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
1152a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      QualType T = getCanonicalType(NTTP->getType());
1162a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1172a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      NonTypeTemplateParmDecl *Param;
1182a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      if (NTTP->isExpandedParameterPack()) {
1192a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        llvm::SmallVector<QualType, 2> ExpandedTypes;
1202a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        llvm::SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
1212a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
1222a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
1232a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          ExpandedTInfos.push_back(
1242a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                getTrivialTypeSourceInfo(ExpandedTypes.back()));
1252a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        }
1262a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1272a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
1282a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                                SourceLocation(),
1295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                                NTTP->getDepth(),
1305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                                NTTP->getPosition(), 0,
1315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                                T,
1322a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                                TInfo,
1335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                                ExpandedTypes.data(),
1342a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                                ExpandedTypes.size(),
1355821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                                ExpandedTInfos.data());
1365821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      } else {
1375821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
1385821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                                SourceLocation(),
1395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                                NTTP->getDepth(),
1405821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                                NTTP->getPosition(), 0,
1415821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                                T,
1425821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                                NTTP->isParameterPack(),
1435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                                TInfo);
1445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      }
1455821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      CanonParams.push_back(Param);
1465821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1475821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    } else
1482a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
1495821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                           cast<TemplateTemplateParmDecl>(*P)));
1502a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
1512a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1522a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  TemplateTemplateParmDecl *CanonTTP
1532a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
1545821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                       SourceLocation(), TTP->getDepth(),
1555821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                       TTP->getPosition(),
1565821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                       TTP->isParameterPack(),
1572a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                       0,
1582a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                         TemplateParameterList::Create(*this, SourceLocation(),
1595821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                                       SourceLocation(),
1602a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                                       CanonParams.data(),
1615821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                                       CanonParams.size(),
1622a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                                       SourceLocation()));
1632a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1642a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Get the new insert position for the node we care about.
1652a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
1662a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  assert(Canonical == 0 && "Shouldn't be in the map!");
1672a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  (void)Canonical;
1682a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1692a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Create the canonical template template parameter entry.
1702a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
1715821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
1722a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  return CanonTTP;
1732a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
1745821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1755821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
1762a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (!LangOpts.CPlusPlus) return 0;
1772a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1782a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  switch (T.getCXXABI()) {
1792a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case CXXABI_ARM:
1802a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return CreateARMCXXABI(*this);
1812a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case CXXABI_Itanium:
1822a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return CreateItaniumCXXABI(*this);
1832a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case CXXABI_Microsoft:
1842a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return CreateMicrosoftCXXABI(*this);
1852a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
1862a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  return 0;
1872a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
1882a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1892a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
1902a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                       const TargetInfo &t,
1912a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                       IdentifierTable &idents, SelectorTable &sels,
1922a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                       Builtin::Context &builtins,
1932a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                       unsigned size_reserve) :
1942a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  TemplateSpecializationTypes(this_()),
1952a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  DependentTemplateSpecializationTypes(this_()),
1962a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  GlobalNestedNameSpecifier(0), IsInt128Installed(false),
1972a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
1982a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
1992a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
2002a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  cudaConfigureCallDecl(0),
2012a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  NullTypeSourceInfo(QualType()),
2022a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)), Target(t),
2032a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  Idents(idents), Selectors(sels),
2042a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  BuiltinInfo(builtins),
2055821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  DeclarationNames(*this),
2065821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
2075821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  LastSDM(0, 0),
2082a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  UniqueBlockByRefTypeID(0) {
2092a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  ObjCIdRedefinitionType = QualType();
2105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  ObjCClassRedefinitionType = QualType();
2112a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  ObjCSelRedefinitionType = QualType();
2125821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (size_reserve > 0) Types.reserve(size_reserve);
2132a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  TUDecl = TranslationUnitDecl::Create(*this);
2145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  InitBuiltinTypes();
2155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
2162a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2172a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)ASTContext::~ASTContext() {
2182a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Release the DenseMaps associated with DeclContext objects.
2192a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // FIXME: Is this the ideal solution?
2202a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  ReleaseDeclContextMaps();
2212a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2222a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Call all of the deallocation functions.
2232a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
2245821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Deallocations[I].first(Deallocations[I].second);
2255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
2265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // Release all of the memory associated with overridden C++ methods.
2272a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
2285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)         OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
2295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)       OM != OMEnd; ++OM)
2302a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    OM->second.Destroy();
2315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
2325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
2332a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // because they can contain DenseMaps.
2342a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  for (llvm::DenseMap<const ObjCContainerDecl*,
2352a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)       const ASTRecordLayout*>::iterator
2362a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)       I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
2372a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // Increment in loop to prevent using deallocated memory.
2385821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
2395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      R->Destroy(*this);
2402a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2412a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
2422a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)       I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
2432a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // Increment in loop to prevent using deallocated memory.
2442a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
2452a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      R->Destroy(*this);
2462a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
2472a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2482a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
2492a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                                    AEnd = DeclAttrs.end();
2502a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)       A != AEnd; ++A)
2512a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    A->second->~AttrVec();
2522a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
2535821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
2542a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
2552a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  Deallocations.push_back(std::make_pair(Callback, Data));
2562a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
2572a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2582a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)void
2592a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
2602a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  ExternalSource.reset(Source.take());
2615821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
2625821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
2635821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)void ASTContext::PrintStats() const {
2645821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  fprintf(stderr, "*** AST Context Stats:\n");
2655821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  fprintf(stderr, "  %d types total.\n", (int)Types.size());
2662a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2672a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  unsigned counts[] = {
2682a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#define TYPE(Name, Parent) 0,
2692a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#define ABSTRACT_TYPE(Name, Parent)
2702a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/AST/TypeNodes.def"
2712a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    0 // Extra
2722a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  };
2732a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2742a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  for (unsigned i = 0, e = Types.size(); i != e; ++i) {
2752a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Type *T = Types[i];
2762a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    counts[(unsigned)T->getTypeClass()]++;
2772a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
2782a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2792a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  unsigned Idx = 0;
2802a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  unsigned TotalBytes = 0;
2812a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#define TYPE(Name, Parent)                                              \
2822a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (counts[Idx])                                                      \
2832a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    fprintf(stderr, "    %d %s types\n", (int)counts[Idx], #Name);      \
2842a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
2852a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  ++Idx;
2862a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#define ABSTRACT_TYPE(Name, Parent)
2872a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/AST/TypeNodes.def"
2882a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2892a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
2902a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2912a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Implicit special member functions.
2922a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  fprintf(stderr, "  %u/%u implicit default constructors created\n",
2932a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          NumImplicitDefaultConstructorsDeclared,
2942a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          NumImplicitDefaultConstructors);
2952a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  fprintf(stderr, "  %u/%u implicit copy constructors created\n",
2962a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          NumImplicitCopyConstructorsDeclared,
2972a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          NumImplicitCopyConstructors);
2982a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  fprintf(stderr, "  %u/%u implicit copy assignment operators created\n",
2992a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          NumImplicitCopyAssignmentOperatorsDeclared,
3002a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          NumImplicitCopyAssignmentOperators);
3012a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  fprintf(stderr, "  %u/%u implicit destructors created\n",
3022a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          NumImplicitDestructorsDeclared, NumImplicitDestructors);
3032a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3042a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (ExternalSource.get()) {
3052a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    fprintf(stderr, "\n");
3062a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    ExternalSource->PrintStats();
3072a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
3082a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3092a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  BumpAlloc.PrintStats();
3102a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
3112a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3122a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3132a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
3142a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
3152a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  R = CanQualType::CreateUnsafe(QualType(Ty, 0));
3162a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  Types.push_back(Ty);
3172a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
3182a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3192a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)void ASTContext::InitBuiltinTypes() {
3202a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  assert(VoidTy.isNull() && "Context reinitialized?");
3212a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3222a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // C99 6.2.5p19.
3232a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InitBuiltinType(VoidTy,              BuiltinType::Void);
3242a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3252a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // C99 6.2.5p2.
3262a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InitBuiltinType(BoolTy,              BuiltinType::Bool);
3272a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // C99 6.2.5p3.
3282a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (LangOpts.CharIsSigned)
3292a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    InitBuiltinType(CharTy,            BuiltinType::Char_S);
3302a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  else
3312a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    InitBuiltinType(CharTy,            BuiltinType::Char_U);
3322a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // C99 6.2.5p4.
3332a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
3342a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InitBuiltinType(ShortTy,             BuiltinType::Short);
3352a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InitBuiltinType(IntTy,               BuiltinType::Int);
3362a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InitBuiltinType(LongTy,              BuiltinType::Long);
3372a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
3382a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3392a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // C99 6.2.5p6.
3402a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
3412a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
3422a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
3432a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
3442a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
3452a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3462a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // C99 6.2.5p10.
3472a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InitBuiltinType(FloatTy,             BuiltinType::Float);
3482a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InitBuiltinType(DoubleTy,            BuiltinType::Double);
3492a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
3502a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3512a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // GNU extension, 128-bit integers.
3522a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InitBuiltinType(Int128Ty,            BuiltinType::Int128);
3532a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
3542a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3552a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
3562a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (!LangOpts.ShortWChar)
3572a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      InitBuiltinType(WCharTy,           BuiltinType::WChar_S);
3582a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    else  // -fshort-wchar makes wchar_t be unsigned.
3592a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      InitBuiltinType(WCharTy,           BuiltinType::WChar_U);
3602a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  } else // C99
3612a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    WCharTy = getFromTargetType(Target.getWCharType());
3622a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3632a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
3642a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    InitBuiltinType(Char16Ty,           BuiltinType::Char16);
3652a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  else // C99
3662a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Char16Ty = getFromTargetType(Target.getChar16Type());
3672a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3682a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
3692a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    InitBuiltinType(Char32Ty,           BuiltinType::Char32);
3702a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  else // C99
3712a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Char32Ty = getFromTargetType(Target.getChar32Type());
3722a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3732a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Placeholder type for type-dependent expressions whose type is
3742a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // completely unknown. No code should ever check a type against
3752a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // DependentTy and users should never see it; however, it is here to
3765821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // help diagnose failures to properly check for type-dependent
3772a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // expressions.
3782a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InitBuiltinType(DependentTy,         BuiltinType::Dependent);
3792a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3802a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Placeholder type for functions.
3812a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InitBuiltinType(OverloadTy,          BuiltinType::Overload);
3822a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3832a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // C99 6.2.5p11.
3842a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  FloatComplexTy      = getComplexType(FloatTy);
3852a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  DoubleComplexTy     = getComplexType(DoubleTy);
3862a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  LongDoubleComplexTy = getComplexType(LongDoubleTy);
3872a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3882a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  BuiltinVaListType = QualType();
3892a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3902a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
3912a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  ObjCIdTypedefType = QualType();
3922a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  ObjCClassTypedefType = QualType();
3932a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  ObjCSelTypedefType = QualType();
3942a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3952a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // Builtin types for 'id', 'Class', and 'SEL'.
3962a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
3972a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
3982a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
3992a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
4005821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  ObjCConstantStringType = QualType();
4015821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
4022a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // void * type
4032a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  VoidPtrTy = getPointerType(VoidTy);
4042a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
4052a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // nullptr type (C++0x 2.14.7)
4062a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
4072a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
4082a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
4095821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)Diagnostic &ASTContext::getDiagnostics() const {
4105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  return SourceMgr.getDiagnostics();
4112a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
4122a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
4132a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
4142a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  AttrVec *&Result = DeclAttrs[D];
4152a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (!Result) {
4165821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    void *Mem = Allocate(sizeof(AttrVec));
4172a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Result = new (Mem) AttrVec;
4182a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
4192a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
4202a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  return *Result;
4212a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
4222a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
4232a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)/// \brief Erase the attributes corresponding to the given declaration.
4242a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)void ASTContext::eraseDeclAttrs(const Decl *D) {
4252a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
4262a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (Pos != DeclAttrs.end()) {
4272a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Pos->second->~AttrVec();
4282a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    DeclAttrs.erase(Pos);
4292a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
4302a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
4312a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
4322a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
4335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)MemberSpecializationInfo *
4345821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
4352a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  assert(Var->isStaticDataMember() && "Not a static data member");
4362a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
4372a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    = InstantiatedFromStaticDataMember.find(Var);
4382a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (Pos == InstantiatedFromStaticDataMember.end())
4392a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return 0;
4402a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
4412a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  return Pos->second;
4422a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
4432a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
4442a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)void
4452a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
4465821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                                TemplateSpecializationKind TSK,
4472a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                          SourceLocation PointOfInstantiation) {
4482a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  assert(Inst->isStaticDataMember() && "Not a static data member");
4492a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  assert(Tmpl->isStaticDataMember() && "Not a static data member");
4502a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  assert(!InstantiatedFromStaticDataMember[Inst] &&
4512a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)         "Already noted what static data member was instantiated from");
4522a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InstantiatedFromStaticDataMember[Inst]
4532a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
4542a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
4552a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
4562a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)NamedDecl *
4572a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
4582a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
4592a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    = InstantiatedFromUsingDecl.find(UUD);
4602a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (Pos == InstantiatedFromUsingDecl.end())
4612a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return 0;
4622a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
4632a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  return Pos->second;
4642a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
465c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)
4662a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)void
4672a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
4682a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  assert((isa<UsingDecl>(Pattern) ||
4692a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          isa<UnresolvedUsingValueDecl>(Pattern) ||
4702a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
4712a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)         "pattern decl is not a using decl");
4722a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
4732a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InstantiatedFromUsingDecl[Inst] = Pattern;
474c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)}
4752a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
476c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)UsingShadowDecl *
4772a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
4782a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
4792a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    = InstantiatedFromUsingShadowDecl.find(Inst);
4802a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (Pos == InstantiatedFromUsingShadowDecl.end())
4812a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return 0;
4822a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
4832a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  return Pos->second;
484c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)}
4852a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
486c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)void
4872a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
4882a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                               UsingShadowDecl *Pattern) {
4892a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
4902a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  InstantiatedFromUsingShadowDecl[Inst] = Pattern;
4912a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
4922a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
4932a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
4942a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
4952a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    = InstantiatedFromUnnamedFieldDecl.find(Field);
4962a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (Pos == InstantiatedFromUnnamedFieldDecl.end())
4972a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return 0;
4982a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
4992a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  return Pos->second;
5002a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
5012a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
5022a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
5032a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                                     FieldDecl *Tmpl) {
5042a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
5052a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
5062a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
5072a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)         "Already noted what unnamed field was instantiated from");
5082a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
509c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
5105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
5115821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
5125821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)ASTContext::overridden_cxx_method_iterator
5135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
5142a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
5152a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    = OverriddenMethods.find(Method);
5162a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (Pos == OverriddenMethods.end())
5172a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return 0;
5182a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
5192a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  return Pos->second.begin();
5202a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
5212a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
5225821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)ASTContext::overridden_cxx_method_iterator
5235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
5242a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
5252a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    = OverriddenMethods.find(Method);
5265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (Pos == OverriddenMethods.end())
5275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return 0;
5282a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
5295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  return Pos->second.end();
5302a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
5315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
5322a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)unsigned
5332a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
5342a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
5352a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    = OverriddenMethods.find(Method);
5362a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (Pos == OverriddenMethods.end())
5372a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return 0;
5382a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
5392a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  return Pos->second.size();
5405821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
5412a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
5422a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
5432a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                     const CXXMethodDecl *Overridden) {
5442a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  OverriddenMethods[Method].push_back(Overridden);
5452a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
5462a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
5472a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)//===----------------------------------------------------------------------===//
5482a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)//                         Type Sizing and Analysis
5492a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)//===----------------------------------------------------------------------===//
5502a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
5512a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
5522a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)/// scalar floating point type.
553c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
5542a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  const BuiltinType *BT = T->getAs<BuiltinType>();
5552a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  assert(BT && "Not a floating point type!");
5562a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  switch (BT->getKind()) {
5572a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  default: assert(0 && "Not a floating point type!");
5582a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case BuiltinType::Float:      return Target.getFloatFormat();
5592a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case BuiltinType::Double:     return Target.getDoubleFormat();
5602a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
5612a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
5622a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
5632a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
5642a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)/// getDeclAlign - Return a conservative estimate of the alignment of the
565c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)/// specified decl.  Note that bitfields do not have a valid alignment, so
5662a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)/// this method will assert on them.
5672a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)/// If @p RefAsPointee, references are treated like their underlying type
5682a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)/// (for alignof), else they're treated like pointers (for CodeGen).
5692a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
5702a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  unsigned Align = Target.getCharWidth();
5712a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
5722a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  bool UseAlignAttrOnly = false;
5732a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (unsigned AlignFromAttr = D->getMaxAlignment()) {
5742a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Align = AlignFromAttr;
5752a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
576c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)    // __attribute__((aligned)) can increase or decrease alignment
5772a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // *except* on a struct or struct member, where it only increases
5782a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // alignment unless 'packed' is also specified.
5792a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    //
5802a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // It is an error for [[align]] to decrease alignment, so we can
5812a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // ignore that possibility;  Sema should diagnose it.
5822a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (isa<FieldDecl>(D)) {
5832a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
5842a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
5852a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    } else {
5862a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      UseAlignAttrOnly = true;
5872a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    }
5882a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
589c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)
5905821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // If we're using the align attribute only, just ignore everything
5915821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // else about the declaration and its type.
5925821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (UseAlignAttrOnly) {
5935821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // do nothing
5942a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
5952a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
5962a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    QualType T = VD->getType();
5975821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
5985821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      if (RefAsPointee)
5992a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        T = RT->getPointeeType();
6002a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      else
6012a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        T = getPointerType(RT->getPointeeType());
6022a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    }
6032a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (!T->isIncompleteType() && !T->isFunctionType()) {
6042a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      // Adjust alignments of declarations with array type by the
6052a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      // large-array alignment on the target.
6062a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      unsigned MinWidth = Target.getLargeArrayMinWidth();
6072a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      const ArrayType *arrayType;
6082a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      if (MinWidth && (arrayType = getAsArrayType(T))) {
6092a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        if (isa<VariableArrayType>(arrayType))
6102a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          Align = std::max(Align, Target.getLargeArrayAlign());
6112a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        else if (isa<ConstantArrayType>(arrayType) &&
6122a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
6132a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          Align = std::max(Align, Target.getLargeArrayAlign());
6142a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
6152a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        // Walk through any array types while we're at it.
6162a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        T = getBaseElementType(arrayType);
6172a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      }
6182a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
6192a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    }
6202a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
6212a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // Fields can be subject to extra alignment constraints, like if
6222a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // the field is packed, the struct is packed, or the struct has a
6232a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // a max-field-alignment constraint (#pragma pack).  So calculate
6242a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // the actual alignment of the field within the struct, and then
6255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // (as we're expected to) constrain that by the alignment of the type.
6262a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
6272a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      // So calculate the alignment of the field.
6282a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
6292a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
6302a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      // Start with the record's overall alignment.
6312a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      unsigned fieldAlign = toBits(layout.getAlignment());
6322a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
6332a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      // Use the GCD of that and the offset within the record.
6342a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
6352a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      if (offset > 0) {
6362a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        // Alignment is always a power of 2, so the GCD will be a power of 2,
6372a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        // which means we get to do this crazy thing instead of Euclid's.
6382a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        uint64_t lowBitOfOffset = offset & (~offset + 1);
6392a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        if (lowBitOfOffset < fieldAlign)
6402a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          fieldAlign = static_cast<unsigned>(lowBitOfOffset);
6412a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      }
6422a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
6432a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Align = std::min(Align, fieldAlign);
6442a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    }
6452a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
6462a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
6472a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  return toCharUnitsFromBits(Align);
6482a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
6492a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
6502a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)std::pair<CharUnits, CharUnits>
6512a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)ASTContext::getTypeInfoInChars(const Type *T) const {
6522a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
6532a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  return std::make_pair(toCharUnitsFromBits(Info.first),
6542a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                        toCharUnitsFromBits(Info.second));
6552a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
6562a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
6572a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)std::pair<CharUnits, CharUnits>
6582a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)ASTContext::getTypeInfoInChars(QualType T) const {
6592a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  return getTypeInfoInChars(T.getTypePtr());
6602a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
6612a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
6622a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)/// getTypeSize - Return the size of the specified type, in bits.  This method
6632a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)/// does not work on incomplete types.
6642a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)///
6652a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)/// FIXME: Pointers into different addr spaces could have different sizes and
6662a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)/// alignment requirements: getPointerInfo should take an AddrSpace, this
6672a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)/// should take a QualType, &c.
6682a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)std::pair<uint64_t, unsigned>
6692a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)ASTContext::getTypeInfo(const Type *T) const {
6702a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  uint64_t Width=0;
6712a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  unsigned Align=8;
6722a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  switch (T->getTypeClass()) {
6732a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#define TYPE(Class, Base)
6742a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#define ABSTRACT_TYPE(Class, Base)
6752a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#define NON_CANONICAL_TYPE(Class, Base)
6762a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6772a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "clang/AST/TypeNodes.def"
6782a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    assert(false && "Should not see dependent types");
6792a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    break;
6802a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
6812a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case Type::FunctionNoProto:
6822a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case Type::FunctionProto:
6832a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // GCC extension: alignof(function) = 32 bits
6842a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Width = 0;
6852a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Align = 32;
6862a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    break;
6872a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
6882a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case Type::IncompleteArray:
6892a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case Type::VariableArray:
6902a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Width = 0;
6912a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
6922a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    break;
6932a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
6942a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case Type::ConstantArray: {
6952a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
6962a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
6972a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
6982a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Width = EltInfo.first*CAT->getSize().getZExtValue();
6992a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Align = EltInfo.second;
7002a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    break;
7012a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
7022a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case Type::ExtVector:
7032a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case Type::Vector: {
7042a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    const VectorType *VT = cast<VectorType>(T);
7052a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
7062a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Width = EltInfo.first*VT->getNumElements();
7072a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Align = Width;
7082a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // If the alignment is not a power of 2, round up to the next power of 2.
7092a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // This happens for non-power-of-2 length vectors.
7102a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (Align & (Align-1)) {
7112a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Align = llvm::NextPowerOf2(Align);
7122a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Width = llvm::RoundUpToAlignment(Width, Align);
7132a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    }
7142a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    break;
7152a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
7162a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
7172a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case Type::Builtin:
7182a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    switch (cast<BuiltinType>(T)->getKind()) {
7192a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    default: assert(0 && "Unknown builtin type!");
7202a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case BuiltinType::Void:
7212a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      // GCC extension: alignof(void) = 8 bits.
7222a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Width = 0;
7232a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Align = 8;
7242a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      break;
7252a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
7262a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case BuiltinType::Bool:
7272a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Width = Target.getBoolWidth();
7282a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Align = Target.getBoolAlign();
7292a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      break;
7302a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case BuiltinType::Char_S:
7312a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case BuiltinType::Char_U:
7322a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case BuiltinType::UChar:
7332a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case BuiltinType::SChar:
7342a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Width = Target.getCharWidth();
7352a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Align = Target.getCharAlign();
7362a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      break;
7372a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case BuiltinType::WChar_S:
7382a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case BuiltinType::WChar_U:
7392a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Width = Target.getWCharWidth();
7402a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Align = Target.getWCharAlign();
7412a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      break;
7422a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case BuiltinType::Char16:
7432a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Width = Target.getChar16Width();
7442a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Align = Target.getChar16Align();
7452a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      break;
7462a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case BuiltinType::Char32:
7472a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Width = Target.getChar32Width();
7482a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Align = Target.getChar32Align();
7492a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      break;
7502a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case BuiltinType::UShort:
7512a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case BuiltinType::Short:
7522a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Width = Target.getShortWidth();
7532a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Align = Target.getShortAlign();
7542a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      break;
7552a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case BuiltinType::UInt:
7562a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case BuiltinType::Int:
7572a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Width = Target.getIntWidth();
7582a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Align = Target.getIntAlign();
7592a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      break;
7602a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case BuiltinType::ULong:
7615821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    case BuiltinType::Long:
7622a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Width = Target.getLongWidth();
7632a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Align = Target.getLongAlign();
7642a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      break;
7652a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case BuiltinType::ULongLong:
7662a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case BuiltinType::LongLong:
7672a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Width = Target.getLongLongWidth();
7682a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Align = Target.getLongLongAlign();
7692a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      break;
7702a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case BuiltinType::Int128:
7712a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case BuiltinType::UInt128:
7722a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Width = 128;
7732a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Align = 128; // int128_t is 128-bit aligned on all targets.
7742a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      break;
7752a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case BuiltinType::Float:
7762a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Width = Target.getFloatWidth();
7772a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Align = Target.getFloatAlign();
7782a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      break;
7792a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case BuiltinType::Double:
7802a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Width = Target.getDoubleWidth();
7812a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Align = Target.getDoubleAlign();
7822a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      break;
7832a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case BuiltinType::LongDouble:
7842a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Width = Target.getLongDoubleWidth();
7852a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Align = Target.getLongDoubleAlign();
7862a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      break;
7872a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case BuiltinType::NullPtr:
7882a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
7892a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Align = Target.getPointerAlign(0); //   == sizeof(void*)
7902a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      break;
7912a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case BuiltinType::ObjCId:
7922a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case BuiltinType::ObjCClass:
7932a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    case BuiltinType::ObjCSel:
7942a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Width = Target.getPointerWidth(0);
7952a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Align = Target.getPointerAlign(0);
7962a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      break;
7972a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    }
7982a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    break;
7992a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case Type::ObjCObjectPointer:
8002a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Width = Target.getPointerWidth(0);
8012a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Align = Target.getPointerAlign(0);
8022a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    break;
8032a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case Type::BlockPointer: {
8042a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
8052a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Width = Target.getPointerWidth(AS);
8062a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Align = Target.getPointerAlign(AS);
8072a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    break;
8082a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
8092a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case Type::LValueReference:
8102a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case Type::RValueReference: {
8112a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // alignof and sizeof should never enter this code path here, so we go
8122a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // the pointer route.
8135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
8145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Width = Target.getPointerWidth(AS);
815    Align = Target.getPointerAlign(AS);
816    break;
817  }
818  case Type::Pointer: {
819    unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
820    Width = Target.getPointerWidth(AS);
821    Align = Target.getPointerAlign(AS);
822    break;
823  }
824  case Type::MemberPointer: {
825    const MemberPointerType *MPT = cast<MemberPointerType>(T);
826    std::pair<uint64_t, unsigned> PtrDiffInfo =
827      getTypeInfo(getPointerDiffType());
828    Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
829    Align = PtrDiffInfo.second;
830    break;
831  }
832  case Type::Complex: {
833    // Complex types have the same alignment as their elements, but twice the
834    // size.
835    std::pair<uint64_t, unsigned> EltInfo =
836      getTypeInfo(cast<ComplexType>(T)->getElementType());
837    Width = EltInfo.first*2;
838    Align = EltInfo.second;
839    break;
840  }
841  case Type::ObjCObject:
842    return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
843  case Type::ObjCInterface: {
844    const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
845    const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
846    Width = toBits(Layout.getSize());
847    Align = toBits(Layout.getAlignment());
848    break;
849  }
850  case Type::Record:
851  case Type::Enum: {
852    const TagType *TT = cast<TagType>(T);
853
854    if (TT->getDecl()->isInvalidDecl()) {
855      Width = 1;
856      Align = 1;
857      break;
858    }
859
860    if (const EnumType *ET = dyn_cast<EnumType>(TT))
861      return getTypeInfo(ET->getDecl()->getIntegerType());
862
863    const RecordType *RT = cast<RecordType>(TT);
864    const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
865    Width = toBits(Layout.getSize());
866    Align = toBits(Layout.getAlignment());
867    break;
868  }
869
870  case Type::SubstTemplateTypeParm:
871    return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
872                       getReplacementType().getTypePtr());
873
874  case Type::Auto: {
875    const AutoType *A = cast<AutoType>(T);
876    assert(A->isDeduced() && "Cannot request the size of a dependent type");
877    return getTypeInfo(A->getDeducedType().getTypePtr());
878  }
879
880  case Type::Paren:
881    return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
882
883  case Type::Typedef: {
884    const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
885    std::pair<uint64_t, unsigned> Info
886      = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
887    // If the typedef has an aligned attribute on it, it overrides any computed
888    // alignment we have.  This violates the GCC documentation (which says that
889    // attribute(aligned) can only round up) but matches its implementation.
890    if (unsigned AttrAlign = Typedef->getMaxAlignment())
891      Align = AttrAlign;
892    else
893      Align = Info.second;
894    Width = Info.first;
895    break;
896  }
897
898  case Type::TypeOfExpr:
899    return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
900                         .getTypePtr());
901
902  case Type::TypeOf:
903    return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
904
905  case Type::Decltype:
906    return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
907                        .getTypePtr());
908
909  case Type::Elaborated:
910    return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
911
912  case Type::Attributed:
913    return getTypeInfo(
914                  cast<AttributedType>(T)->getEquivalentType().getTypePtr());
915
916  case Type::TemplateSpecialization:
917    assert(getCanonicalType(T) != T &&
918           "Cannot request the size of a dependent type");
919    // FIXME: this is likely to be wrong once we support template
920    // aliases, since a template alias could refer to a typedef that
921    // has an __aligned__ attribute on it.
922    return getTypeInfo(getCanonicalType(T));
923  }
924
925  assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
926  return std::make_pair(Width, Align);
927}
928
929/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
930CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
931  return CharUnits::fromQuantity(BitSize / getCharWidth());
932}
933
934/// toBits - Convert a size in characters to a size in characters.
935int64_t ASTContext::toBits(CharUnits CharSize) const {
936  return CharSize.getQuantity() * getCharWidth();
937}
938
939/// getTypeSizeInChars - Return the size of the specified type, in characters.
940/// This method does not work on incomplete types.
941CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
942  return toCharUnitsFromBits(getTypeSize(T));
943}
944CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
945  return toCharUnitsFromBits(getTypeSize(T));
946}
947
948/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
949/// characters. This method does not work on incomplete types.
950CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
951  return toCharUnitsFromBits(getTypeAlign(T));
952}
953CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
954  return toCharUnitsFromBits(getTypeAlign(T));
955}
956
957/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
958/// type for the current target in bits.  This can be different than the ABI
959/// alignment in cases where it is beneficial for performance to overalign
960/// a data type.
961unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
962  unsigned ABIAlign = getTypeAlign(T);
963
964  // Double and long long should be naturally aligned if possible.
965  if (const ComplexType* CT = T->getAs<ComplexType>())
966    T = CT->getElementType().getTypePtr();
967  if (T->isSpecificBuiltinType(BuiltinType::Double) ||
968      T->isSpecificBuiltinType(BuiltinType::LongLong))
969    return std::max(ABIAlign, (unsigned)getTypeSize(T));
970
971  return ABIAlign;
972}
973
974/// ShallowCollectObjCIvars -
975/// Collect all ivars, including those synthesized, in the current class.
976///
977void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
978                            llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
979  // FIXME. This need be removed but there are two many places which
980  // assume const-ness of ObjCInterfaceDecl
981  ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
982  for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
983        Iv= Iv->getNextIvar())
984    Ivars.push_back(Iv);
985}
986
987/// DeepCollectObjCIvars -
988/// This routine first collects all declared, but not synthesized, ivars in
989/// super class and then collects all ivars, including those synthesized for
990/// current class. This routine is used for implementation of current class
991/// when all ivars, declared and synthesized are known.
992///
993void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
994                                      bool leafClass,
995                            llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
996  if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
997    DeepCollectObjCIvars(SuperClass, false, Ivars);
998  if (!leafClass) {
999    for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1000         E = OI->ivar_end(); I != E; ++I)
1001      Ivars.push_back(*I);
1002  }
1003  else
1004    ShallowCollectObjCIvars(OI, Ivars);
1005}
1006
1007/// CollectInheritedProtocols - Collect all protocols in current class and
1008/// those inherited by it.
1009void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
1010                          llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
1011  if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1012    // We can use protocol_iterator here instead of
1013    // all_referenced_protocol_iterator since we are walking all categories.
1014    for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1015         PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
1016      ObjCProtocolDecl *Proto = (*P);
1017      Protocols.insert(Proto);
1018      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1019           PE = Proto->protocol_end(); P != PE; ++P) {
1020        Protocols.insert(*P);
1021        CollectInheritedProtocols(*P, Protocols);
1022      }
1023    }
1024
1025    // Categories of this Interface.
1026    for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1027         CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1028      CollectInheritedProtocols(CDeclChain, Protocols);
1029    if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1030      while (SD) {
1031        CollectInheritedProtocols(SD, Protocols);
1032        SD = SD->getSuperClass();
1033      }
1034  } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1035    for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
1036         PE = OC->protocol_end(); P != PE; ++P) {
1037      ObjCProtocolDecl *Proto = (*P);
1038      Protocols.insert(Proto);
1039      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1040           PE = Proto->protocol_end(); P != PE; ++P)
1041        CollectInheritedProtocols(*P, Protocols);
1042    }
1043  } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1044    for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1045         PE = OP->protocol_end(); P != PE; ++P) {
1046      ObjCProtocolDecl *Proto = (*P);
1047      Protocols.insert(Proto);
1048      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1049           PE = Proto->protocol_end(); P != PE; ++P)
1050        CollectInheritedProtocols(*P, Protocols);
1051    }
1052  }
1053}
1054
1055unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
1056  unsigned count = 0;
1057  // Count ivars declared in class extension.
1058  for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1059       CDecl = CDecl->getNextClassExtension())
1060    count += CDecl->ivar_size();
1061
1062  // Count ivar defined in this class's implementation.  This
1063  // includes synthesized ivars.
1064  if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
1065    count += ImplDecl->ivar_size();
1066
1067  return count;
1068}
1069
1070/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1071ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1072  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1073    I = ObjCImpls.find(D);
1074  if (I != ObjCImpls.end())
1075    return cast<ObjCImplementationDecl>(I->second);
1076  return 0;
1077}
1078/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1079ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1080  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1081    I = ObjCImpls.find(D);
1082  if (I != ObjCImpls.end())
1083    return cast<ObjCCategoryImplDecl>(I->second);
1084  return 0;
1085}
1086
1087/// \brief Set the implementation of ObjCInterfaceDecl.
1088void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1089                           ObjCImplementationDecl *ImplD) {
1090  assert(IFaceD && ImplD && "Passed null params");
1091  ObjCImpls[IFaceD] = ImplD;
1092}
1093/// \brief Set the implementation of ObjCCategoryDecl.
1094void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1095                           ObjCCategoryImplDecl *ImplD) {
1096  assert(CatD && ImplD && "Passed null params");
1097  ObjCImpls[CatD] = ImplD;
1098}
1099
1100/// \brief Get the copy initialization expression of VarDecl,or NULL if
1101/// none exists.
1102Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
1103  assert(VD && "Passed null params");
1104  assert(VD->hasAttr<BlocksAttr>() &&
1105         "getBlockVarCopyInits - not __block var");
1106  llvm::DenseMap<const VarDecl*, Expr*>::iterator
1107    I = BlockVarCopyInits.find(VD);
1108  return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1109}
1110
1111/// \brief Set the copy inialization expression of a block var decl.
1112void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1113  assert(VD && Init && "Passed null params");
1114  assert(VD->hasAttr<BlocksAttr>() &&
1115         "setBlockVarCopyInits - not __block var");
1116  BlockVarCopyInits[VD] = Init;
1117}
1118
1119/// \brief Allocate an uninitialized TypeSourceInfo.
1120///
1121/// The caller should initialize the memory held by TypeSourceInfo using
1122/// the TypeLoc wrappers.
1123///
1124/// \param T the type that will be the basis for type source info. This type
1125/// should refer to how the declarator was written in source code, not to
1126/// what type semantic analysis resolved the declarator to.
1127TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
1128                                                 unsigned DataSize) const {
1129  if (!DataSize)
1130    DataSize = TypeLoc::getFullDataSizeForType(T);
1131  else
1132    assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
1133           "incorrect data size provided to CreateTypeSourceInfo!");
1134
1135  TypeSourceInfo *TInfo =
1136    (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1137  new (TInfo) TypeSourceInfo(T);
1138  return TInfo;
1139}
1140
1141TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
1142                                                     SourceLocation L) const {
1143  TypeSourceInfo *DI = CreateTypeSourceInfo(T);
1144  DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
1145  return DI;
1146}
1147
1148const ASTRecordLayout &
1149ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
1150  return getObjCLayout(D, 0);
1151}
1152
1153const ASTRecordLayout &
1154ASTContext::getASTObjCImplementationLayout(
1155                                        const ObjCImplementationDecl *D) const {
1156  return getObjCLayout(D->getClassInterface(), D);
1157}
1158
1159//===----------------------------------------------------------------------===//
1160//                   Type creation/memoization methods
1161//===----------------------------------------------------------------------===//
1162
1163QualType
1164ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1165  unsigned fastQuals = quals.getFastQualifiers();
1166  quals.removeFastQualifiers();
1167
1168  // Check if we've already instantiated this type.
1169  llvm::FoldingSetNodeID ID;
1170  ExtQuals::Profile(ID, baseType, quals);
1171  void *insertPos = 0;
1172  if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1173    assert(eq->getQualifiers() == quals);
1174    return QualType(eq, fastQuals);
1175  }
1176
1177  // If the base type is not canonical, make the appropriate canonical type.
1178  QualType canon;
1179  if (!baseType->isCanonicalUnqualified()) {
1180    SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1181    canonSplit.second.addConsistentQualifiers(quals);
1182    canon = getExtQualType(canonSplit.first, canonSplit.second);
1183
1184    // Re-find the insert position.
1185    (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1186  }
1187
1188  ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1189  ExtQualNodes.InsertNode(eq, insertPos);
1190  return QualType(eq, fastQuals);
1191}
1192
1193QualType
1194ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
1195  QualType CanT = getCanonicalType(T);
1196  if (CanT.getAddressSpace() == AddressSpace)
1197    return T;
1198
1199  // If we are composing extended qualifiers together, merge together
1200  // into one ExtQuals node.
1201  QualifierCollector Quals;
1202  const Type *TypeNode = Quals.strip(T);
1203
1204  // If this type already has an address space specified, it cannot get
1205  // another one.
1206  assert(!Quals.hasAddressSpace() &&
1207         "Type cannot be in multiple addr spaces!");
1208  Quals.addAddressSpace(AddressSpace);
1209
1210  return getExtQualType(TypeNode, Quals);
1211}
1212
1213QualType ASTContext::getObjCGCQualType(QualType T,
1214                                       Qualifiers::GC GCAttr) const {
1215  QualType CanT = getCanonicalType(T);
1216  if (CanT.getObjCGCAttr() == GCAttr)
1217    return T;
1218
1219  if (const PointerType *ptr = T->getAs<PointerType>()) {
1220    QualType Pointee = ptr->getPointeeType();
1221    if (Pointee->isAnyPointerType()) {
1222      QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1223      return getPointerType(ResultType);
1224    }
1225  }
1226
1227  // If we are composing extended qualifiers together, merge together
1228  // into one ExtQuals node.
1229  QualifierCollector Quals;
1230  const Type *TypeNode = Quals.strip(T);
1231
1232  // If this type already has an ObjCGC specified, it cannot get
1233  // another one.
1234  assert(!Quals.hasObjCGCAttr() &&
1235         "Type cannot have multiple ObjCGCs!");
1236  Quals.addObjCGCAttr(GCAttr);
1237
1238  return getExtQualType(TypeNode, Quals);
1239}
1240
1241const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1242                                                   FunctionType::ExtInfo Info) {
1243  if (T->getExtInfo() == Info)
1244    return T;
1245
1246  QualType Result;
1247  if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1248    Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1249  } else {
1250    const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1251    FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1252    EPI.ExtInfo = Info;
1253    Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1254                             FPT->getNumArgs(), EPI);
1255  }
1256
1257  return cast<FunctionType>(Result.getTypePtr());
1258}
1259
1260/// getComplexType - Return the uniqued reference to the type for a complex
1261/// number with the specified element type.
1262QualType ASTContext::getComplexType(QualType T) const {
1263  // Unique pointers, to guarantee there is only one pointer of a particular
1264  // structure.
1265  llvm::FoldingSetNodeID ID;
1266  ComplexType::Profile(ID, T);
1267
1268  void *InsertPos = 0;
1269  if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1270    return QualType(CT, 0);
1271
1272  // If the pointee type isn't canonical, this won't be a canonical type either,
1273  // so fill in the canonical type field.
1274  QualType Canonical;
1275  if (!T.isCanonical()) {
1276    Canonical = getComplexType(getCanonicalType(T));
1277
1278    // Get the new insert position for the node we care about.
1279    ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
1280    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1281  }
1282  ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
1283  Types.push_back(New);
1284  ComplexTypes.InsertNode(New, InsertPos);
1285  return QualType(New, 0);
1286}
1287
1288/// getPointerType - Return the uniqued reference to the type for a pointer to
1289/// the specified type.
1290QualType ASTContext::getPointerType(QualType T) const {
1291  // Unique pointers, to guarantee there is only one pointer of a particular
1292  // structure.
1293  llvm::FoldingSetNodeID ID;
1294  PointerType::Profile(ID, T);
1295
1296  void *InsertPos = 0;
1297  if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1298    return QualType(PT, 0);
1299
1300  // If the pointee type isn't canonical, this won't be a canonical type either,
1301  // so fill in the canonical type field.
1302  QualType Canonical;
1303  if (!T.isCanonical()) {
1304    Canonical = getPointerType(getCanonicalType(T));
1305
1306    // Get the new insert position for the node we care about.
1307    PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1308    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1309  }
1310  PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
1311  Types.push_back(New);
1312  PointerTypes.InsertNode(New, InsertPos);
1313  return QualType(New, 0);
1314}
1315
1316/// getBlockPointerType - Return the uniqued reference to the type for
1317/// a pointer to the specified block.
1318QualType ASTContext::getBlockPointerType(QualType T) const {
1319  assert(T->isFunctionType() && "block of function types only");
1320  // Unique pointers, to guarantee there is only one block of a particular
1321  // structure.
1322  llvm::FoldingSetNodeID ID;
1323  BlockPointerType::Profile(ID, T);
1324
1325  void *InsertPos = 0;
1326  if (BlockPointerType *PT =
1327        BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1328    return QualType(PT, 0);
1329
1330  // If the block pointee type isn't canonical, this won't be a canonical
1331  // type either so fill in the canonical type field.
1332  QualType Canonical;
1333  if (!T.isCanonical()) {
1334    Canonical = getBlockPointerType(getCanonicalType(T));
1335
1336    // Get the new insert position for the node we care about.
1337    BlockPointerType *NewIP =
1338      BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1339    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1340  }
1341  BlockPointerType *New
1342    = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
1343  Types.push_back(New);
1344  BlockPointerTypes.InsertNode(New, InsertPos);
1345  return QualType(New, 0);
1346}
1347
1348/// getLValueReferenceType - Return the uniqued reference to the type for an
1349/// lvalue reference to the specified type.
1350QualType
1351ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
1352  // Unique pointers, to guarantee there is only one pointer of a particular
1353  // structure.
1354  llvm::FoldingSetNodeID ID;
1355  ReferenceType::Profile(ID, T, SpelledAsLValue);
1356
1357  void *InsertPos = 0;
1358  if (LValueReferenceType *RT =
1359        LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1360    return QualType(RT, 0);
1361
1362  const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1363
1364  // If the referencee type isn't canonical, this won't be a canonical type
1365  // either, so fill in the canonical type field.
1366  QualType Canonical;
1367  if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1368    QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1369    Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
1370
1371    // Get the new insert position for the node we care about.
1372    LValueReferenceType *NewIP =
1373      LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1374    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1375  }
1376
1377  LValueReferenceType *New
1378    = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1379                                                     SpelledAsLValue);
1380  Types.push_back(New);
1381  LValueReferenceTypes.InsertNode(New, InsertPos);
1382
1383  return QualType(New, 0);
1384}
1385
1386/// getRValueReferenceType - Return the uniqued reference to the type for an
1387/// rvalue reference to the specified type.
1388QualType ASTContext::getRValueReferenceType(QualType T) const {
1389  // Unique pointers, to guarantee there is only one pointer of a particular
1390  // structure.
1391  llvm::FoldingSetNodeID ID;
1392  ReferenceType::Profile(ID, T, false);
1393
1394  void *InsertPos = 0;
1395  if (RValueReferenceType *RT =
1396        RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1397    return QualType(RT, 0);
1398
1399  const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1400
1401  // If the referencee type isn't canonical, this won't be a canonical type
1402  // either, so fill in the canonical type field.
1403  QualType Canonical;
1404  if (InnerRef || !T.isCanonical()) {
1405    QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1406    Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
1407
1408    // Get the new insert position for the node we care about.
1409    RValueReferenceType *NewIP =
1410      RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1411    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1412  }
1413
1414  RValueReferenceType *New
1415    = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
1416  Types.push_back(New);
1417  RValueReferenceTypes.InsertNode(New, InsertPos);
1418  return QualType(New, 0);
1419}
1420
1421/// getMemberPointerType - Return the uniqued reference to the type for a
1422/// member pointer to the specified type, in the specified class.
1423QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
1424  // Unique pointers, to guarantee there is only one pointer of a particular
1425  // structure.
1426  llvm::FoldingSetNodeID ID;
1427  MemberPointerType::Profile(ID, T, Cls);
1428
1429  void *InsertPos = 0;
1430  if (MemberPointerType *PT =
1431      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1432    return QualType(PT, 0);
1433
1434  // If the pointee or class type isn't canonical, this won't be a canonical
1435  // type either, so fill in the canonical type field.
1436  QualType Canonical;
1437  if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
1438    Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1439
1440    // Get the new insert position for the node we care about.
1441    MemberPointerType *NewIP =
1442      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1443    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1444  }
1445  MemberPointerType *New
1446    = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
1447  Types.push_back(New);
1448  MemberPointerTypes.InsertNode(New, InsertPos);
1449  return QualType(New, 0);
1450}
1451
1452/// getConstantArrayType - Return the unique reference to the type for an
1453/// array of the specified element type.
1454QualType ASTContext::getConstantArrayType(QualType EltTy,
1455                                          const llvm::APInt &ArySizeIn,
1456                                          ArrayType::ArraySizeModifier ASM,
1457                                          unsigned IndexTypeQuals) const {
1458  assert((EltTy->isDependentType() ||
1459          EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
1460         "Constant array of VLAs is illegal!");
1461
1462  // Convert the array size into a canonical width matching the pointer size for
1463  // the target.
1464  llvm::APInt ArySize(ArySizeIn);
1465  ArySize =
1466    ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1467
1468  llvm::FoldingSetNodeID ID;
1469  ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
1470
1471  void *InsertPos = 0;
1472  if (ConstantArrayType *ATP =
1473      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1474    return QualType(ATP, 0);
1475
1476  // If the element type isn't canonical or has qualifiers, this won't
1477  // be a canonical type either, so fill in the canonical type field.
1478  QualType Canon;
1479  if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1480    SplitQualType canonSplit = getCanonicalType(EltTy).split();
1481    Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
1482                                 ASM, IndexTypeQuals);
1483    Canon = getQualifiedType(Canon, canonSplit.second);
1484
1485    // Get the new insert position for the node we care about.
1486    ConstantArrayType *NewIP =
1487      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1488    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1489  }
1490
1491  ConstantArrayType *New = new(*this,TypeAlignment)
1492    ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
1493  ConstantArrayTypes.InsertNode(New, InsertPos);
1494  Types.push_back(New);
1495  return QualType(New, 0);
1496}
1497
1498/// getVariableArrayDecayedType - Turns the given type, which may be
1499/// variably-modified, into the corresponding type with all the known
1500/// sizes replaced with [*].
1501QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1502  // Vastly most common case.
1503  if (!type->isVariablyModifiedType()) return type;
1504
1505  QualType result;
1506
1507  SplitQualType split = type.getSplitDesugaredType();
1508  const Type *ty = split.first;
1509  switch (ty->getTypeClass()) {
1510#define TYPE(Class, Base)
1511#define ABSTRACT_TYPE(Class, Base)
1512#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1513#include "clang/AST/TypeNodes.def"
1514    llvm_unreachable("didn't desugar past all non-canonical types?");
1515
1516  // These types should never be variably-modified.
1517  case Type::Builtin:
1518  case Type::Complex:
1519  case Type::Vector:
1520  case Type::ExtVector:
1521  case Type::DependentSizedExtVector:
1522  case Type::ObjCObject:
1523  case Type::ObjCInterface:
1524  case Type::ObjCObjectPointer:
1525  case Type::Record:
1526  case Type::Enum:
1527  case Type::UnresolvedUsing:
1528  case Type::TypeOfExpr:
1529  case Type::TypeOf:
1530  case Type::Decltype:
1531  case Type::DependentName:
1532  case Type::InjectedClassName:
1533  case Type::TemplateSpecialization:
1534  case Type::DependentTemplateSpecialization:
1535  case Type::TemplateTypeParm:
1536  case Type::SubstTemplateTypeParmPack:
1537  case Type::Auto:
1538  case Type::PackExpansion:
1539    llvm_unreachable("type should never be variably-modified");
1540
1541  // These types can be variably-modified but should never need to
1542  // further decay.
1543  case Type::FunctionNoProto:
1544  case Type::FunctionProto:
1545  case Type::BlockPointer:
1546  case Type::MemberPointer:
1547    return type;
1548
1549  // These types can be variably-modified.  All these modifications
1550  // preserve structure except as noted by comments.
1551  // TODO: if we ever care about optimizing VLAs, there are no-op
1552  // optimizations available here.
1553  case Type::Pointer:
1554    result = getPointerType(getVariableArrayDecayedType(
1555                              cast<PointerType>(ty)->getPointeeType()));
1556    break;
1557
1558  case Type::LValueReference: {
1559    const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1560    result = getLValueReferenceType(
1561                 getVariableArrayDecayedType(lv->getPointeeType()),
1562                                    lv->isSpelledAsLValue());
1563    break;
1564  }
1565
1566  case Type::RValueReference: {
1567    const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1568    result = getRValueReferenceType(
1569                 getVariableArrayDecayedType(lv->getPointeeType()));
1570    break;
1571  }
1572
1573  case Type::ConstantArray: {
1574    const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1575    result = getConstantArrayType(
1576                 getVariableArrayDecayedType(cat->getElementType()),
1577                                  cat->getSize(),
1578                                  cat->getSizeModifier(),
1579                                  cat->getIndexTypeCVRQualifiers());
1580    break;
1581  }
1582
1583  case Type::DependentSizedArray: {
1584    const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1585    result = getDependentSizedArrayType(
1586                 getVariableArrayDecayedType(dat->getElementType()),
1587                                        dat->getSizeExpr(),
1588                                        dat->getSizeModifier(),
1589                                        dat->getIndexTypeCVRQualifiers(),
1590                                        dat->getBracketsRange());
1591    break;
1592  }
1593
1594  // Turn incomplete types into [*] types.
1595  case Type::IncompleteArray: {
1596    const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1597    result = getVariableArrayType(
1598                 getVariableArrayDecayedType(iat->getElementType()),
1599                                  /*size*/ 0,
1600                                  ArrayType::Normal,
1601                                  iat->getIndexTypeCVRQualifiers(),
1602                                  SourceRange());
1603    break;
1604  }
1605
1606  // Turn VLA types into [*] types.
1607  case Type::VariableArray: {
1608    const VariableArrayType *vat = cast<VariableArrayType>(ty);
1609    result = getVariableArrayType(
1610                 getVariableArrayDecayedType(vat->getElementType()),
1611                                  /*size*/ 0,
1612                                  ArrayType::Star,
1613                                  vat->getIndexTypeCVRQualifiers(),
1614                                  vat->getBracketsRange());
1615    break;
1616  }
1617  }
1618
1619  // Apply the top-level qualifiers from the original.
1620  return getQualifiedType(result, split.second);
1621}
1622
1623/// getVariableArrayType - Returns a non-unique reference to the type for a
1624/// variable array of the specified element type.
1625QualType ASTContext::getVariableArrayType(QualType EltTy,
1626                                          Expr *NumElts,
1627                                          ArrayType::ArraySizeModifier ASM,
1628                                          unsigned IndexTypeQuals,
1629                                          SourceRange Brackets) const {
1630  // Since we don't unique expressions, it isn't possible to unique VLA's
1631  // that have an expression provided for their size.
1632  QualType Canon;
1633
1634  // Be sure to pull qualifiers off the element type.
1635  if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1636    SplitQualType canonSplit = getCanonicalType(EltTy).split();
1637    Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
1638                                 IndexTypeQuals, Brackets);
1639    Canon = getQualifiedType(Canon, canonSplit.second);
1640  }
1641
1642  VariableArrayType *New = new(*this, TypeAlignment)
1643    VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
1644
1645  VariableArrayTypes.push_back(New);
1646  Types.push_back(New);
1647  return QualType(New, 0);
1648}
1649
1650/// getDependentSizedArrayType - Returns a non-unique reference to
1651/// the type for a dependently-sized array of the specified element
1652/// type.
1653QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1654                                                Expr *numElements,
1655                                                ArrayType::ArraySizeModifier ASM,
1656                                                unsigned elementTypeQuals,
1657                                                SourceRange brackets) const {
1658  assert((!numElements || numElements->isTypeDependent() ||
1659          numElements->isValueDependent()) &&
1660         "Size must be type- or value-dependent!");
1661
1662  // Dependently-sized array types that do not have a specified number
1663  // of elements will have their sizes deduced from a dependent
1664  // initializer.  We do no canonicalization here at all, which is okay
1665  // because they can't be used in most locations.
1666  if (!numElements) {
1667    DependentSizedArrayType *newType
1668      = new (*this, TypeAlignment)
1669          DependentSizedArrayType(*this, elementType, QualType(),
1670                                  numElements, ASM, elementTypeQuals,
1671                                  brackets);
1672    Types.push_back(newType);
1673    return QualType(newType, 0);
1674  }
1675
1676  // Otherwise, we actually build a new type every time, but we
1677  // also build a canonical type.
1678
1679  SplitQualType canonElementType = getCanonicalType(elementType).split();
1680
1681  void *insertPos = 0;
1682  llvm::FoldingSetNodeID ID;
1683  DependentSizedArrayType::Profile(ID, *this,
1684                                   QualType(canonElementType.first, 0),
1685                                   ASM, elementTypeQuals, numElements);
1686
1687  // Look for an existing type with these properties.
1688  DependentSizedArrayType *canonTy =
1689    DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1690
1691  // If we don't have one, build one.
1692  if (!canonTy) {
1693    canonTy = new (*this, TypeAlignment)
1694      DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1695                              QualType(), numElements, ASM, elementTypeQuals,
1696                              brackets);
1697    DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1698    Types.push_back(canonTy);
1699  }
1700
1701  // Apply qualifiers from the element type to the array.
1702  QualType canon = getQualifiedType(QualType(canonTy,0),
1703                                    canonElementType.second);
1704
1705  // If we didn't need extra canonicalization for the element type,
1706  // then just use that as our result.
1707  if (QualType(canonElementType.first, 0) == elementType)
1708    return canon;
1709
1710  // Otherwise, we need to build a type which follows the spelling
1711  // of the element type.
1712  DependentSizedArrayType *sugaredType
1713    = new (*this, TypeAlignment)
1714        DependentSizedArrayType(*this, elementType, canon, numElements,
1715                                ASM, elementTypeQuals, brackets);
1716  Types.push_back(sugaredType);
1717  return QualType(sugaredType, 0);
1718}
1719
1720QualType ASTContext::getIncompleteArrayType(QualType elementType,
1721                                            ArrayType::ArraySizeModifier ASM,
1722                                            unsigned elementTypeQuals) const {
1723  llvm::FoldingSetNodeID ID;
1724  IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
1725
1726  void *insertPos = 0;
1727  if (IncompleteArrayType *iat =
1728       IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1729    return QualType(iat, 0);
1730
1731  // If the element type isn't canonical, this won't be a canonical type
1732  // either, so fill in the canonical type field.  We also have to pull
1733  // qualifiers off the element type.
1734  QualType canon;
1735
1736  if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1737    SplitQualType canonSplit = getCanonicalType(elementType).split();
1738    canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1739                                   ASM, elementTypeQuals);
1740    canon = getQualifiedType(canon, canonSplit.second);
1741
1742    // Get the new insert position for the node we care about.
1743    IncompleteArrayType *existing =
1744      IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1745    assert(!existing && "Shouldn't be in the map!"); (void) existing;
1746  }
1747
1748  IncompleteArrayType *newType = new (*this, TypeAlignment)
1749    IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
1750
1751  IncompleteArrayTypes.InsertNode(newType, insertPos);
1752  Types.push_back(newType);
1753  return QualType(newType, 0);
1754}
1755
1756/// getVectorType - Return the unique reference to a vector type of
1757/// the specified element type and size. VectorType must be a built-in type.
1758QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1759                                   VectorType::VectorKind VecKind) const {
1760  assert(vecType->isBuiltinType());
1761
1762  // Check if we've already instantiated a vector of this type.
1763  llvm::FoldingSetNodeID ID;
1764  VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
1765
1766  void *InsertPos = 0;
1767  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1768    return QualType(VTP, 0);
1769
1770  // If the element type isn't canonical, this won't be a canonical type either,
1771  // so fill in the canonical type field.
1772  QualType Canonical;
1773  if (!vecType.isCanonical()) {
1774    Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
1775
1776    // Get the new insert position for the node we care about.
1777    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1778    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1779  }
1780  VectorType *New = new (*this, TypeAlignment)
1781    VectorType(vecType, NumElts, Canonical, VecKind);
1782  VectorTypes.InsertNode(New, InsertPos);
1783  Types.push_back(New);
1784  return QualType(New, 0);
1785}
1786
1787/// getExtVectorType - Return the unique reference to an extended vector type of
1788/// the specified element type and size. VectorType must be a built-in type.
1789QualType
1790ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
1791  assert(vecType->isBuiltinType());
1792
1793  // Check if we've already instantiated a vector of this type.
1794  llvm::FoldingSetNodeID ID;
1795  VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
1796                      VectorType::GenericVector);
1797  void *InsertPos = 0;
1798  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1799    return QualType(VTP, 0);
1800
1801  // If the element type isn't canonical, this won't be a canonical type either,
1802  // so fill in the canonical type field.
1803  QualType Canonical;
1804  if (!vecType.isCanonical()) {
1805    Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
1806
1807    // Get the new insert position for the node we care about.
1808    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1809    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1810  }
1811  ExtVectorType *New = new (*this, TypeAlignment)
1812    ExtVectorType(vecType, NumElts, Canonical);
1813  VectorTypes.InsertNode(New, InsertPos);
1814  Types.push_back(New);
1815  return QualType(New, 0);
1816}
1817
1818QualType
1819ASTContext::getDependentSizedExtVectorType(QualType vecType,
1820                                           Expr *SizeExpr,
1821                                           SourceLocation AttrLoc) const {
1822  llvm::FoldingSetNodeID ID;
1823  DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
1824                                       SizeExpr);
1825
1826  void *InsertPos = 0;
1827  DependentSizedExtVectorType *Canon
1828    = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1829  DependentSizedExtVectorType *New;
1830  if (Canon) {
1831    // We already have a canonical version of this array type; use it as
1832    // the canonical type for a newly-built type.
1833    New = new (*this, TypeAlignment)
1834      DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1835                                  SizeExpr, AttrLoc);
1836  } else {
1837    QualType CanonVecTy = getCanonicalType(vecType);
1838    if (CanonVecTy == vecType) {
1839      New = new (*this, TypeAlignment)
1840        DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1841                                    AttrLoc);
1842
1843      DependentSizedExtVectorType *CanonCheck
1844        = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1845      assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1846      (void)CanonCheck;
1847      DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1848    } else {
1849      QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1850                                                      SourceLocation());
1851      New = new (*this, TypeAlignment)
1852        DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
1853    }
1854  }
1855
1856  Types.push_back(New);
1857  return QualType(New, 0);
1858}
1859
1860/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
1861///
1862QualType
1863ASTContext::getFunctionNoProtoType(QualType ResultTy,
1864                                   const FunctionType::ExtInfo &Info) const {
1865  const CallingConv DefaultCC = Info.getCC();
1866  const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1867                               CC_X86StdCall : DefaultCC;
1868  // Unique functions, to guarantee there is only one function of a particular
1869  // structure.
1870  llvm::FoldingSetNodeID ID;
1871  FunctionNoProtoType::Profile(ID, ResultTy, Info);
1872
1873  void *InsertPos = 0;
1874  if (FunctionNoProtoType *FT =
1875        FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1876    return QualType(FT, 0);
1877
1878  QualType Canonical;
1879  if (!ResultTy.isCanonical() ||
1880      getCanonicalCallConv(CallConv) != CallConv) {
1881    Canonical =
1882      getFunctionNoProtoType(getCanonicalType(ResultTy),
1883                     Info.withCallingConv(getCanonicalCallConv(CallConv)));
1884
1885    // Get the new insert position for the node we care about.
1886    FunctionNoProtoType *NewIP =
1887      FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1888    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1889  }
1890
1891  FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
1892  FunctionNoProtoType *New = new (*this, TypeAlignment)
1893    FunctionNoProtoType(ResultTy, Canonical, newInfo);
1894  Types.push_back(New);
1895  FunctionNoProtoTypes.InsertNode(New, InsertPos);
1896  return QualType(New, 0);
1897}
1898
1899/// getFunctionType - Return a normal function type with a typed argument
1900/// list.  isVariadic indicates whether the argument list includes '...'.
1901QualType
1902ASTContext::getFunctionType(QualType ResultTy,
1903                            const QualType *ArgArray, unsigned NumArgs,
1904                            const FunctionProtoType::ExtProtoInfo &EPI) const {
1905  // Unique functions, to guarantee there is only one function of a particular
1906  // structure.
1907  llvm::FoldingSetNodeID ID;
1908  FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI);
1909
1910  void *InsertPos = 0;
1911  if (FunctionProtoType *FTP =
1912        FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1913    return QualType(FTP, 0);
1914
1915  // Determine whether the type being created is already canonical or not.
1916  bool isCanonical = !EPI.HasExceptionSpec && ResultTy.isCanonical();
1917  for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1918    if (!ArgArray[i].isCanonicalAsParam())
1919      isCanonical = false;
1920
1921  const CallingConv DefaultCC = EPI.ExtInfo.getCC();
1922  const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1923                               CC_X86StdCall : DefaultCC;
1924
1925  // If this type isn't canonical, get the canonical version of it.
1926  // The exception spec is not part of the canonical type.
1927  QualType Canonical;
1928  if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
1929    llvm::SmallVector<QualType, 16> CanonicalArgs;
1930    CanonicalArgs.reserve(NumArgs);
1931    for (unsigned i = 0; i != NumArgs; ++i)
1932      CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
1933
1934    FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
1935    if (CanonicalEPI.HasExceptionSpec) {
1936      CanonicalEPI.HasExceptionSpec = false;
1937      CanonicalEPI.HasAnyExceptionSpec = false;
1938      CanonicalEPI.NumExceptions = 0;
1939    }
1940    CanonicalEPI.ExtInfo
1941      = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
1942
1943    Canonical = getFunctionType(getCanonicalType(ResultTy),
1944                                CanonicalArgs.data(), NumArgs,
1945                                CanonicalEPI);
1946
1947    // Get the new insert position for the node we care about.
1948    FunctionProtoType *NewIP =
1949      FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1950    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1951  }
1952
1953  // FunctionProtoType objects are allocated with extra bytes after them
1954  // for two variable size arrays (for parameter and exception types) at the
1955  // end of them.
1956  size_t Size = sizeof(FunctionProtoType) +
1957                NumArgs * sizeof(QualType) +
1958                EPI.NumExceptions * sizeof(QualType);
1959  FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
1960  FunctionProtoType::ExtProtoInfo newEPI = EPI;
1961  newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
1962  new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
1963  Types.push_back(FTP);
1964  FunctionProtoTypes.InsertNode(FTP, InsertPos);
1965  return QualType(FTP, 0);
1966}
1967
1968#ifndef NDEBUG
1969static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1970  if (!isa<CXXRecordDecl>(D)) return false;
1971  const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1972  if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1973    return true;
1974  if (RD->getDescribedClassTemplate() &&
1975      !isa<ClassTemplateSpecializationDecl>(RD))
1976    return true;
1977  return false;
1978}
1979#endif
1980
1981/// getInjectedClassNameType - Return the unique reference to the
1982/// injected class name type for the specified templated declaration.
1983QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1984                                              QualType TST) const {
1985  assert(NeedsInjectedClassNameType(Decl));
1986  if (Decl->TypeForDecl) {
1987    assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1988  } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
1989    assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1990    Decl->TypeForDecl = PrevDecl->TypeForDecl;
1991    assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1992  } else {
1993    Type *newType =
1994      new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
1995    Decl->TypeForDecl = newType;
1996    Types.push_back(newType);
1997  }
1998  return QualType(Decl->TypeForDecl, 0);
1999}
2000
2001/// getTypeDeclType - Return the unique reference to the type for the
2002/// specified type declaration.
2003QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
2004  assert(Decl && "Passed null for Decl param");
2005  assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
2006
2007  if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
2008    return getTypedefType(Typedef);
2009
2010  assert(!isa<TemplateTypeParmDecl>(Decl) &&
2011         "Template type parameter types are always available.");
2012
2013  if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
2014    assert(!Record->getPreviousDeclaration() &&
2015           "struct/union has previous declaration");
2016    assert(!NeedsInjectedClassNameType(Record));
2017    return getRecordType(Record);
2018  } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
2019    assert(!Enum->getPreviousDeclaration() &&
2020           "enum has previous declaration");
2021    return getEnumType(Enum);
2022  } else if (const UnresolvedUsingTypenameDecl *Using =
2023               dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
2024    Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2025    Decl->TypeForDecl = newType;
2026    Types.push_back(newType);
2027  } else
2028    llvm_unreachable("TypeDecl without a type?");
2029
2030  return QualType(Decl->TypeForDecl, 0);
2031}
2032
2033/// getTypedefType - Return the unique reference to the type for the
2034/// specified typename decl.
2035QualType
2036ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) const {
2037  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2038
2039  if (Canonical.isNull())
2040    Canonical = getCanonicalType(Decl->getUnderlyingType());
2041  TypedefType *newType = new(*this, TypeAlignment)
2042    TypedefType(Type::Typedef, Decl, Canonical);
2043  Decl->TypeForDecl = newType;
2044  Types.push_back(newType);
2045  return QualType(newType, 0);
2046}
2047
2048QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
2049  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2050
2051  if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2052    if (PrevDecl->TypeForDecl)
2053      return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2054
2055  RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2056  Decl->TypeForDecl = newType;
2057  Types.push_back(newType);
2058  return QualType(newType, 0);
2059}
2060
2061QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
2062  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2063
2064  if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2065    if (PrevDecl->TypeForDecl)
2066      return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2067
2068  EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2069  Decl->TypeForDecl = newType;
2070  Types.push_back(newType);
2071  return QualType(newType, 0);
2072}
2073
2074QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2075                                       QualType modifiedType,
2076                                       QualType equivalentType) {
2077  llvm::FoldingSetNodeID id;
2078  AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2079
2080  void *insertPos = 0;
2081  AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2082  if (type) return QualType(type, 0);
2083
2084  QualType canon = getCanonicalType(equivalentType);
2085  type = new (*this, TypeAlignment)
2086           AttributedType(canon, attrKind, modifiedType, equivalentType);
2087
2088  Types.push_back(type);
2089  AttributedTypes.InsertNode(type, insertPos);
2090
2091  return QualType(type, 0);
2092}
2093
2094
2095/// \brief Retrieve a substitution-result type.
2096QualType
2097ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
2098                                         QualType Replacement) const {
2099  assert(Replacement.isCanonical()
2100         && "replacement types must always be canonical");
2101
2102  llvm::FoldingSetNodeID ID;
2103  SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2104  void *InsertPos = 0;
2105  SubstTemplateTypeParmType *SubstParm
2106    = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2107
2108  if (!SubstParm) {
2109    SubstParm = new (*this, TypeAlignment)
2110      SubstTemplateTypeParmType(Parm, Replacement);
2111    Types.push_back(SubstParm);
2112    SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2113  }
2114
2115  return QualType(SubstParm, 0);
2116}
2117
2118/// \brief Retrieve a
2119QualType ASTContext::getSubstTemplateTypeParmPackType(
2120                                          const TemplateTypeParmType *Parm,
2121                                              const TemplateArgument &ArgPack) {
2122#ifndef NDEBUG
2123  for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2124                                    PEnd = ArgPack.pack_end();
2125       P != PEnd; ++P) {
2126    assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2127    assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2128  }
2129#endif
2130
2131  llvm::FoldingSetNodeID ID;
2132  SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2133  void *InsertPos = 0;
2134  if (SubstTemplateTypeParmPackType *SubstParm
2135        = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2136    return QualType(SubstParm, 0);
2137
2138  QualType Canon;
2139  if (!Parm->isCanonicalUnqualified()) {
2140    Canon = getCanonicalType(QualType(Parm, 0));
2141    Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2142                                             ArgPack);
2143    SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2144  }
2145
2146  SubstTemplateTypeParmPackType *SubstParm
2147    = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2148                                                               ArgPack);
2149  Types.push_back(SubstParm);
2150  SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2151  return QualType(SubstParm, 0);
2152}
2153
2154/// \brief Retrieve the template type parameter type for a template
2155/// parameter or parameter pack with the given depth, index, and (optionally)
2156/// name.
2157QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
2158                                             bool ParameterPack,
2159                                             IdentifierInfo *Name) const {
2160  llvm::FoldingSetNodeID ID;
2161  TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
2162  void *InsertPos = 0;
2163  TemplateTypeParmType *TypeParm
2164    = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2165
2166  if (TypeParm)
2167    return QualType(TypeParm, 0);
2168
2169  if (Name) {
2170    QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
2171    TypeParm = new (*this, TypeAlignment)
2172      TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
2173
2174    TemplateTypeParmType *TypeCheck
2175      = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2176    assert(!TypeCheck && "Template type parameter canonical type broken");
2177    (void)TypeCheck;
2178  } else
2179    TypeParm = new (*this, TypeAlignment)
2180      TemplateTypeParmType(Depth, Index, ParameterPack);
2181
2182  Types.push_back(TypeParm);
2183  TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2184
2185  return QualType(TypeParm, 0);
2186}
2187
2188TypeSourceInfo *
2189ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2190                                              SourceLocation NameLoc,
2191                                        const TemplateArgumentListInfo &Args,
2192                                              QualType CanonType) const {
2193  assert(!Name.getAsDependentTemplateName() &&
2194         "No dependent template names here!");
2195  QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
2196
2197  TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2198  TemplateSpecializationTypeLoc TL
2199    = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2200  TL.setTemplateNameLoc(NameLoc);
2201  TL.setLAngleLoc(Args.getLAngleLoc());
2202  TL.setRAngleLoc(Args.getRAngleLoc());
2203  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2204    TL.setArgLocInfo(i, Args[i].getLocInfo());
2205  return DI;
2206}
2207
2208QualType
2209ASTContext::getTemplateSpecializationType(TemplateName Template,
2210                                          const TemplateArgumentListInfo &Args,
2211                                          QualType Canon) const {
2212  assert(!Template.getAsDependentTemplateName() &&
2213         "No dependent template names here!");
2214
2215  unsigned NumArgs = Args.size();
2216
2217  llvm::SmallVector<TemplateArgument, 4> ArgVec;
2218  ArgVec.reserve(NumArgs);
2219  for (unsigned i = 0; i != NumArgs; ++i)
2220    ArgVec.push_back(Args[i].getArgument());
2221
2222  return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
2223                                       Canon);
2224}
2225
2226QualType
2227ASTContext::getTemplateSpecializationType(TemplateName Template,
2228                                          const TemplateArgument *Args,
2229                                          unsigned NumArgs,
2230                                          QualType Canon) const {
2231  assert(!Template.getAsDependentTemplateName() &&
2232         "No dependent template names here!");
2233  // Look through qualified template names.
2234  if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2235    Template = TemplateName(QTN->getTemplateDecl());
2236
2237  if (!Canon.isNull())
2238    Canon = getCanonicalType(Canon);
2239  else
2240    Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
2241
2242  // Allocate the (non-canonical) template specialization type, but don't
2243  // try to unique it: these types typically have location information that
2244  // we don't unique and don't want to lose.
2245  void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2246                        sizeof(TemplateArgument) * NumArgs),
2247                       TypeAlignment);
2248  TemplateSpecializationType *Spec
2249    = new (Mem) TemplateSpecializationType(Template,
2250                                           Args, NumArgs,
2251                                           Canon);
2252
2253  Types.push_back(Spec);
2254  return QualType(Spec, 0);
2255}
2256
2257QualType
2258ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2259                                                   const TemplateArgument *Args,
2260                                                   unsigned NumArgs) const {
2261  assert(!Template.getAsDependentTemplateName() &&
2262         "No dependent template names here!");
2263  // Look through qualified template names.
2264  if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2265    Template = TemplateName(QTN->getTemplateDecl());
2266
2267  // Build the canonical template specialization type.
2268  TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2269  llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2270  CanonArgs.reserve(NumArgs);
2271  for (unsigned I = 0; I != NumArgs; ++I)
2272    CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2273
2274  // Determine whether this canonical template specialization type already
2275  // exists.
2276  llvm::FoldingSetNodeID ID;
2277  TemplateSpecializationType::Profile(ID, CanonTemplate,
2278                                      CanonArgs.data(), NumArgs, *this);
2279
2280  void *InsertPos = 0;
2281  TemplateSpecializationType *Spec
2282    = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2283
2284  if (!Spec) {
2285    // Allocate a new canonical template specialization type.
2286    void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2287                          sizeof(TemplateArgument) * NumArgs),
2288                         TypeAlignment);
2289    Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2290                                                CanonArgs.data(), NumArgs,
2291                                                QualType());
2292    Types.push_back(Spec);
2293    TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2294  }
2295
2296  assert(Spec->isDependentType() &&
2297         "Non-dependent template-id type must have a canonical type");
2298  return QualType(Spec, 0);
2299}
2300
2301QualType
2302ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2303                              NestedNameSpecifier *NNS,
2304                              QualType NamedType) const {
2305  llvm::FoldingSetNodeID ID;
2306  ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
2307
2308  void *InsertPos = 0;
2309  ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2310  if (T)
2311    return QualType(T, 0);
2312
2313  QualType Canon = NamedType;
2314  if (!Canon.isCanonical()) {
2315    Canon = getCanonicalType(NamedType);
2316    ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2317    assert(!CheckT && "Elaborated canonical type broken");
2318    (void)CheckT;
2319  }
2320
2321  T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
2322  Types.push_back(T);
2323  ElaboratedTypes.InsertNode(T, InsertPos);
2324  return QualType(T, 0);
2325}
2326
2327QualType
2328ASTContext::getParenType(QualType InnerType) const {
2329  llvm::FoldingSetNodeID ID;
2330  ParenType::Profile(ID, InnerType);
2331
2332  void *InsertPos = 0;
2333  ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2334  if (T)
2335    return QualType(T, 0);
2336
2337  QualType Canon = InnerType;
2338  if (!Canon.isCanonical()) {
2339    Canon = getCanonicalType(InnerType);
2340    ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2341    assert(!CheckT && "Paren canonical type broken");
2342    (void)CheckT;
2343  }
2344
2345  T = new (*this) ParenType(InnerType, Canon);
2346  Types.push_back(T);
2347  ParenTypes.InsertNode(T, InsertPos);
2348  return QualType(T, 0);
2349}
2350
2351QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2352                                          NestedNameSpecifier *NNS,
2353                                          const IdentifierInfo *Name,
2354                                          QualType Canon) const {
2355  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2356
2357  if (Canon.isNull()) {
2358    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2359    ElaboratedTypeKeyword CanonKeyword = Keyword;
2360    if (Keyword == ETK_None)
2361      CanonKeyword = ETK_Typename;
2362
2363    if (CanonNNS != NNS || CanonKeyword != Keyword)
2364      Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
2365  }
2366
2367  llvm::FoldingSetNodeID ID;
2368  DependentNameType::Profile(ID, Keyword, NNS, Name);
2369
2370  void *InsertPos = 0;
2371  DependentNameType *T
2372    = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2373  if (T)
2374    return QualType(T, 0);
2375
2376  T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
2377  Types.push_back(T);
2378  DependentNameTypes.InsertNode(T, InsertPos);
2379  return QualType(T, 0);
2380}
2381
2382QualType
2383ASTContext::getDependentTemplateSpecializationType(
2384                                 ElaboratedTypeKeyword Keyword,
2385                                 NestedNameSpecifier *NNS,
2386                                 const IdentifierInfo *Name,
2387                                 const TemplateArgumentListInfo &Args) const {
2388  // TODO: avoid this copy
2389  llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2390  for (unsigned I = 0, E = Args.size(); I != E; ++I)
2391    ArgCopy.push_back(Args[I].getArgument());
2392  return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2393                                                ArgCopy.size(),
2394                                                ArgCopy.data());
2395}
2396
2397QualType
2398ASTContext::getDependentTemplateSpecializationType(
2399                                 ElaboratedTypeKeyword Keyword,
2400                                 NestedNameSpecifier *NNS,
2401                                 const IdentifierInfo *Name,
2402                                 unsigned NumArgs,
2403                                 const TemplateArgument *Args) const {
2404  assert((!NNS || NNS->isDependent()) &&
2405         "nested-name-specifier must be dependent");
2406
2407  llvm::FoldingSetNodeID ID;
2408  DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2409                                               Name, NumArgs, Args);
2410
2411  void *InsertPos = 0;
2412  DependentTemplateSpecializationType *T
2413    = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2414  if (T)
2415    return QualType(T, 0);
2416
2417  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2418
2419  ElaboratedTypeKeyword CanonKeyword = Keyword;
2420  if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2421
2422  bool AnyNonCanonArgs = false;
2423  llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2424  for (unsigned I = 0; I != NumArgs; ++I) {
2425    CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2426    if (!CanonArgs[I].structurallyEquals(Args[I]))
2427      AnyNonCanonArgs = true;
2428  }
2429
2430  QualType Canon;
2431  if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2432    Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2433                                                   Name, NumArgs,
2434                                                   CanonArgs.data());
2435
2436    // Find the insert position again.
2437    DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2438  }
2439
2440  void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2441                        sizeof(TemplateArgument) * NumArgs),
2442                       TypeAlignment);
2443  T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
2444                                                    Name, NumArgs, Args, Canon);
2445  Types.push_back(T);
2446  DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
2447  return QualType(T, 0);
2448}
2449
2450QualType ASTContext::getPackExpansionType(QualType Pattern,
2451                                      llvm::Optional<unsigned> NumExpansions) {
2452  llvm::FoldingSetNodeID ID;
2453  PackExpansionType::Profile(ID, Pattern, NumExpansions);
2454
2455  assert(Pattern->containsUnexpandedParameterPack() &&
2456         "Pack expansions must expand one or more parameter packs");
2457  void *InsertPos = 0;
2458  PackExpansionType *T
2459    = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2460  if (T)
2461    return QualType(T, 0);
2462
2463  QualType Canon;
2464  if (!Pattern.isCanonical()) {
2465    Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
2466
2467    // Find the insert position again.
2468    PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2469  }
2470
2471  T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
2472  Types.push_back(T);
2473  PackExpansionTypes.InsertNode(T, InsertPos);
2474  return QualType(T, 0);
2475}
2476
2477/// CmpProtocolNames - Comparison predicate for sorting protocols
2478/// alphabetically.
2479static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2480                            const ObjCProtocolDecl *RHS) {
2481  return LHS->getDeclName() < RHS->getDeclName();
2482}
2483
2484static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
2485                                unsigned NumProtocols) {
2486  if (NumProtocols == 0) return true;
2487
2488  for (unsigned i = 1; i != NumProtocols; ++i)
2489    if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2490      return false;
2491  return true;
2492}
2493
2494static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
2495                                   unsigned &NumProtocols) {
2496  ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
2497
2498  // Sort protocols, keyed by name.
2499  std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2500
2501  // Remove duplicates.
2502  ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2503  NumProtocols = ProtocolsEnd-Protocols;
2504}
2505
2506QualType ASTContext::getObjCObjectType(QualType BaseType,
2507                                       ObjCProtocolDecl * const *Protocols,
2508                                       unsigned NumProtocols) const {
2509  // If the base type is an interface and there aren't any protocols
2510  // to add, then the interface type will do just fine.
2511  if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2512    return BaseType;
2513
2514  // Look in the folding set for an existing type.
2515  llvm::FoldingSetNodeID ID;
2516  ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
2517  void *InsertPos = 0;
2518  if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2519    return QualType(QT, 0);
2520
2521  // Build the canonical type, which has the canonical base type and
2522  // a sorted-and-uniqued list of protocols.
2523  QualType Canonical;
2524  bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2525  if (!ProtocolsSorted || !BaseType.isCanonical()) {
2526    if (!ProtocolsSorted) {
2527      llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2528                                                     Protocols + NumProtocols);
2529      unsigned UniqueCount = NumProtocols;
2530
2531      SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2532      Canonical = getObjCObjectType(getCanonicalType(BaseType),
2533                                    &Sorted[0], UniqueCount);
2534    } else {
2535      Canonical = getObjCObjectType(getCanonicalType(BaseType),
2536                                    Protocols, NumProtocols);
2537    }
2538
2539    // Regenerate InsertPos.
2540    ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2541  }
2542
2543  unsigned Size = sizeof(ObjCObjectTypeImpl);
2544  Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2545  void *Mem = Allocate(Size, TypeAlignment);
2546  ObjCObjectTypeImpl *T =
2547    new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2548
2549  Types.push_back(T);
2550  ObjCObjectTypes.InsertNode(T, InsertPos);
2551  return QualType(T, 0);
2552}
2553
2554/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2555/// the given object type.
2556QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
2557  llvm::FoldingSetNodeID ID;
2558  ObjCObjectPointerType::Profile(ID, ObjectT);
2559
2560  void *InsertPos = 0;
2561  if (ObjCObjectPointerType *QT =
2562              ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2563    return QualType(QT, 0);
2564
2565  // Find the canonical object type.
2566  QualType Canonical;
2567  if (!ObjectT.isCanonical()) {
2568    Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2569
2570    // Regenerate InsertPos.
2571    ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2572  }
2573
2574  // No match.
2575  void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2576  ObjCObjectPointerType *QType =
2577    new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
2578
2579  Types.push_back(QType);
2580  ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2581  return QualType(QType, 0);
2582}
2583
2584/// getObjCInterfaceType - Return the unique reference to the type for the
2585/// specified ObjC interface decl. The list of protocols is optional.
2586QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
2587  if (Decl->TypeForDecl)
2588    return QualType(Decl->TypeForDecl, 0);
2589
2590  // FIXME: redeclarations?
2591  void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2592  ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2593  Decl->TypeForDecl = T;
2594  Types.push_back(T);
2595  return QualType(T, 0);
2596}
2597
2598/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2599/// TypeOfExprType AST's (since expression's are never shared). For example,
2600/// multiple declarations that refer to "typeof(x)" all contain different
2601/// DeclRefExpr's. This doesn't effect the type checker, since it operates
2602/// on canonical type's (which are always unique).
2603QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
2604  TypeOfExprType *toe;
2605  if (tofExpr->isTypeDependent()) {
2606    llvm::FoldingSetNodeID ID;
2607    DependentTypeOfExprType::Profile(ID, *this, tofExpr);
2608
2609    void *InsertPos = 0;
2610    DependentTypeOfExprType *Canon
2611      = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2612    if (Canon) {
2613      // We already have a "canonical" version of an identical, dependent
2614      // typeof(expr) type. Use that as our canonical type.
2615      toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
2616                                          QualType((TypeOfExprType*)Canon, 0));
2617    }
2618    else {
2619      // Build a new, canonical typeof(expr) type.
2620      Canon
2621        = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
2622      DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2623      toe = Canon;
2624    }
2625  } else {
2626    QualType Canonical = getCanonicalType(tofExpr->getType());
2627    toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
2628  }
2629  Types.push_back(toe);
2630  return QualType(toe, 0);
2631}
2632
2633/// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
2634/// TypeOfType AST's. The only motivation to unique these nodes would be
2635/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
2636/// an issue. This doesn't effect the type checker, since it operates
2637/// on canonical type's (which are always unique).
2638QualType ASTContext::getTypeOfType(QualType tofType) const {
2639  QualType Canonical = getCanonicalType(tofType);
2640  TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
2641  Types.push_back(tot);
2642  return QualType(tot, 0);
2643}
2644
2645/// getDecltypeForExpr - Given an expr, will return the decltype for that
2646/// expression, according to the rules in C++0x [dcl.type.simple]p4
2647static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
2648  if (e->isTypeDependent())
2649    return Context.DependentTy;
2650
2651  // If e is an id expression or a class member access, decltype(e) is defined
2652  // as the type of the entity named by e.
2653  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2654    if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2655      return VD->getType();
2656  }
2657  if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2658    if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2659      return FD->getType();
2660  }
2661  // If e is a function call or an invocation of an overloaded operator,
2662  // (parentheses around e are ignored), decltype(e) is defined as the
2663  // return type of that function.
2664  if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2665    return CE->getCallReturnType();
2666
2667  QualType T = e->getType();
2668
2669  // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
2670  // defined as T&, otherwise decltype(e) is defined as T.
2671  if (e->isLValue())
2672    T = Context.getLValueReferenceType(T);
2673
2674  return T;
2675}
2676
2677/// getDecltypeType -  Unlike many "get<Type>" functions, we don't unique
2678/// DecltypeType AST's. The only motivation to unique these nodes would be
2679/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
2680/// an issue. This doesn't effect the type checker, since it operates
2681/// on canonical type's (which are always unique).
2682QualType ASTContext::getDecltypeType(Expr *e) const {
2683  DecltypeType *dt;
2684  if (e->isTypeDependent()) {
2685    llvm::FoldingSetNodeID ID;
2686    DependentDecltypeType::Profile(ID, *this, e);
2687
2688    void *InsertPos = 0;
2689    DependentDecltypeType *Canon
2690      = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2691    if (Canon) {
2692      // We already have a "canonical" version of an equivalent, dependent
2693      // decltype type. Use that as our canonical type.
2694      dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
2695                                       QualType((DecltypeType*)Canon, 0));
2696    }
2697    else {
2698      // Build a new, canonical typeof(expr) type.
2699      Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
2700      DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2701      dt = Canon;
2702    }
2703  } else {
2704    QualType T = getDecltypeForExpr(e, *this);
2705    dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
2706  }
2707  Types.push_back(dt);
2708  return QualType(dt, 0);
2709}
2710
2711/// getAutoType - We only unique auto types after they've been deduced.
2712QualType ASTContext::getAutoType(QualType DeducedType) const {
2713  void *InsertPos = 0;
2714  if (!DeducedType.isNull()) {
2715    // Look in the folding set for an existing type.
2716    llvm::FoldingSetNodeID ID;
2717    AutoType::Profile(ID, DeducedType);
2718    if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2719      return QualType(AT, 0);
2720  }
2721
2722  AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2723  Types.push_back(AT);
2724  if (InsertPos)
2725    AutoTypes.InsertNode(AT, InsertPos);
2726  return QualType(AT, 0);
2727}
2728
2729/// getTagDeclType - Return the unique reference to the type for the
2730/// specified TagDecl (struct/union/class/enum) decl.
2731QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
2732  assert (Decl);
2733  // FIXME: What is the design on getTagDeclType when it requires casting
2734  // away const?  mutable?
2735  return getTypeDeclType(const_cast<TagDecl*>(Decl));
2736}
2737
2738/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2739/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2740/// needs to agree with the definition in <stddef.h>.
2741CanQualType ASTContext::getSizeType() const {
2742  return getFromTargetType(Target.getSizeType());
2743}
2744
2745/// getSignedWCharType - Return the type of "signed wchar_t".
2746/// Used when in C++, as a GCC extension.
2747QualType ASTContext::getSignedWCharType() const {
2748  // FIXME: derive from "Target" ?
2749  return WCharTy;
2750}
2751
2752/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2753/// Used when in C++, as a GCC extension.
2754QualType ASTContext::getUnsignedWCharType() const {
2755  // FIXME: derive from "Target" ?
2756  return UnsignedIntTy;
2757}
2758
2759/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2760/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2761QualType ASTContext::getPointerDiffType() const {
2762  return getFromTargetType(Target.getPtrDiffType(0));
2763}
2764
2765//===----------------------------------------------------------------------===//
2766//                              Type Operators
2767//===----------------------------------------------------------------------===//
2768
2769CanQualType ASTContext::getCanonicalParamType(QualType T) const {
2770  // Push qualifiers into arrays, and then discard any remaining
2771  // qualifiers.
2772  T = getCanonicalType(T);
2773  T = getVariableArrayDecayedType(T);
2774  const Type *Ty = T.getTypePtr();
2775  QualType Result;
2776  if (isa<ArrayType>(Ty)) {
2777    Result = getArrayDecayedType(QualType(Ty,0));
2778  } else if (isa<FunctionType>(Ty)) {
2779    Result = getPointerType(QualType(Ty, 0));
2780  } else {
2781    Result = QualType(Ty, 0);
2782  }
2783
2784  return CanQualType::CreateUnsafe(Result);
2785}
2786
2787
2788QualType ASTContext::getUnqualifiedArrayType(QualType type,
2789                                             Qualifiers &quals) {
2790  SplitQualType splitType = type.getSplitUnqualifiedType();
2791
2792  // FIXME: getSplitUnqualifiedType() actually walks all the way to
2793  // the unqualified desugared type and then drops it on the floor.
2794  // We then have to strip that sugar back off with
2795  // getUnqualifiedDesugaredType(), which is silly.
2796  const ArrayType *AT =
2797    dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2798
2799  // If we don't have an array, just use the results in splitType.
2800  if (!AT) {
2801    quals = splitType.second;
2802    return QualType(splitType.first, 0);
2803  }
2804
2805  // Otherwise, recurse on the array's element type.
2806  QualType elementType = AT->getElementType();
2807  QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2808
2809  // If that didn't change the element type, AT has no qualifiers, so we
2810  // can just use the results in splitType.
2811  if (elementType == unqualElementType) {
2812    assert(quals.empty()); // from the recursive call
2813    quals = splitType.second;
2814    return QualType(splitType.first, 0);
2815  }
2816
2817  // Otherwise, add in the qualifiers from the outermost type, then
2818  // build the type back up.
2819  quals.addConsistentQualifiers(splitType.second);
2820
2821  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
2822    return getConstantArrayType(unqualElementType, CAT->getSize(),
2823                                CAT->getSizeModifier(), 0);
2824  }
2825
2826  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
2827    return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
2828  }
2829
2830  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2831    return getVariableArrayType(unqualElementType,
2832                                VAT->getSizeExpr(),
2833                                VAT->getSizeModifier(),
2834                                VAT->getIndexTypeCVRQualifiers(),
2835                                VAT->getBracketsRange());
2836  }
2837
2838  const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
2839  return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
2840                                    DSAT->getSizeModifier(), 0,
2841                                    SourceRange());
2842}
2843
2844/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
2845/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2846/// they point to and return true. If T1 and T2 aren't pointer types
2847/// or pointer-to-member types, or if they are not similar at this
2848/// level, returns false and leaves T1 and T2 unchanged. Top-level
2849/// qualifiers on T1 and T2 are ignored. This function will typically
2850/// be called in a loop that successively "unwraps" pointer and
2851/// pointer-to-member types to compare them at each level.
2852bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2853  const PointerType *T1PtrType = T1->getAs<PointerType>(),
2854                    *T2PtrType = T2->getAs<PointerType>();
2855  if (T1PtrType && T2PtrType) {
2856    T1 = T1PtrType->getPointeeType();
2857    T2 = T2PtrType->getPointeeType();
2858    return true;
2859  }
2860
2861  const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2862                          *T2MPType = T2->getAs<MemberPointerType>();
2863  if (T1MPType && T2MPType &&
2864      hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2865                             QualType(T2MPType->getClass(), 0))) {
2866    T1 = T1MPType->getPointeeType();
2867    T2 = T2MPType->getPointeeType();
2868    return true;
2869  }
2870
2871  if (getLangOptions().ObjC1) {
2872    const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2873                                *T2OPType = T2->getAs<ObjCObjectPointerType>();
2874    if (T1OPType && T2OPType) {
2875      T1 = T1OPType->getPointeeType();
2876      T2 = T2OPType->getPointeeType();
2877      return true;
2878    }
2879  }
2880
2881  // FIXME: Block pointers, too?
2882
2883  return false;
2884}
2885
2886DeclarationNameInfo
2887ASTContext::getNameForTemplate(TemplateName Name,
2888                               SourceLocation NameLoc) const {
2889  if (TemplateDecl *TD = Name.getAsTemplateDecl())
2890    // DNInfo work in progress: CHECKME: what about DNLoc?
2891    return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2892
2893  if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2894    DeclarationName DName;
2895    if (DTN->isIdentifier()) {
2896      DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2897      return DeclarationNameInfo(DName, NameLoc);
2898    } else {
2899      DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2900      // DNInfo work in progress: FIXME: source locations?
2901      DeclarationNameLoc DNLoc;
2902      DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2903      DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2904      return DeclarationNameInfo(DName, NameLoc, DNLoc);
2905    }
2906  }
2907
2908  OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2909  assert(Storage);
2910  // DNInfo work in progress: CHECKME: what about DNLoc?
2911  return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
2912}
2913
2914TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
2915  if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2916    if (TemplateTemplateParmDecl *TTP
2917                              = dyn_cast<TemplateTemplateParmDecl>(Template))
2918      Template = getCanonicalTemplateTemplateParmDecl(TTP);
2919
2920    // The canonical template name is the canonical template declaration.
2921    return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
2922  }
2923
2924  if (SubstTemplateTemplateParmPackStorage *SubstPack
2925                                  = Name.getAsSubstTemplateTemplateParmPack()) {
2926    TemplateTemplateParmDecl *CanonParam
2927      = getCanonicalTemplateTemplateParmDecl(SubstPack->getParameterPack());
2928    TemplateArgument CanonArgPack
2929      = getCanonicalTemplateArgument(SubstPack->getArgumentPack());
2930    return getSubstTemplateTemplateParmPack(CanonParam, CanonArgPack);
2931  }
2932
2933  assert(!Name.getAsOverloadedTemplate());
2934
2935  DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2936  assert(DTN && "Non-dependent template names must refer to template decls.");
2937  return DTN->CanonicalTemplateName;
2938}
2939
2940bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2941  X = getCanonicalTemplateName(X);
2942  Y = getCanonicalTemplateName(Y);
2943  return X.getAsVoidPointer() == Y.getAsVoidPointer();
2944}
2945
2946TemplateArgument
2947ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
2948  switch (Arg.getKind()) {
2949    case TemplateArgument::Null:
2950      return Arg;
2951
2952    case TemplateArgument::Expression:
2953      return Arg;
2954
2955    case TemplateArgument::Declaration:
2956      return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
2957
2958    case TemplateArgument::Template:
2959      return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2960
2961    case TemplateArgument::TemplateExpansion:
2962      return TemplateArgument(getCanonicalTemplateName(
2963                                         Arg.getAsTemplateOrTemplatePattern()),
2964                              Arg.getNumTemplateExpansions());
2965
2966    case TemplateArgument::Integral:
2967      return TemplateArgument(*Arg.getAsIntegral(),
2968                              getCanonicalType(Arg.getIntegralType()));
2969
2970    case TemplateArgument::Type:
2971      return TemplateArgument(getCanonicalType(Arg.getAsType()));
2972
2973    case TemplateArgument::Pack: {
2974      if (Arg.pack_size() == 0)
2975        return Arg;
2976
2977      TemplateArgument *CanonArgs
2978        = new (*this) TemplateArgument[Arg.pack_size()];
2979      unsigned Idx = 0;
2980      for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
2981                                        AEnd = Arg.pack_end();
2982           A != AEnd; (void)++A, ++Idx)
2983        CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
2984
2985      return TemplateArgument(CanonArgs, Arg.pack_size());
2986    }
2987  }
2988
2989  // Silence GCC warning
2990  assert(false && "Unhandled template argument kind");
2991  return TemplateArgument();
2992}
2993
2994NestedNameSpecifier *
2995ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
2996  if (!NNS)
2997    return 0;
2998
2999  switch (NNS->getKind()) {
3000  case NestedNameSpecifier::Identifier:
3001    // Canonicalize the prefix but keep the identifier the same.
3002    return NestedNameSpecifier::Create(*this,
3003                         getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3004                                       NNS->getAsIdentifier());
3005
3006  case NestedNameSpecifier::Namespace:
3007    // A namespace is canonical; build a nested-name-specifier with
3008    // this namespace and no prefix.
3009    return NestedNameSpecifier::Create(*this, 0,
3010                                 NNS->getAsNamespace()->getOriginalNamespace());
3011
3012  case NestedNameSpecifier::NamespaceAlias:
3013    // A namespace is canonical; build a nested-name-specifier with
3014    // this namespace and no prefix.
3015    return NestedNameSpecifier::Create(*this, 0,
3016                                    NNS->getAsNamespaceAlias()->getNamespace()
3017                                                      ->getOriginalNamespace());
3018
3019  case NestedNameSpecifier::TypeSpec:
3020  case NestedNameSpecifier::TypeSpecWithTemplate: {
3021    QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
3022
3023    // If we have some kind of dependent-named type (e.g., "typename T::type"),
3024    // break it apart into its prefix and identifier, then reconsititute those
3025    // as the canonical nested-name-specifier. This is required to canonicalize
3026    // a dependent nested-name-specifier involving typedefs of dependent-name
3027    // types, e.g.,
3028    //   typedef typename T::type T1;
3029    //   typedef typename T1::type T2;
3030    if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3031      NestedNameSpecifier *Prefix
3032        = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3033      return NestedNameSpecifier::Create(*this, Prefix,
3034                           const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3035    }
3036
3037    // Do the same thing as above, but with dependent-named specializations.
3038    if (const DependentTemplateSpecializationType *DTST
3039          = T->getAs<DependentTemplateSpecializationType>()) {
3040      NestedNameSpecifier *Prefix
3041        = getCanonicalNestedNameSpecifier(DTST->getQualifier());
3042
3043      T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3044                                                 Prefix, DTST->getIdentifier(),
3045                                                 DTST->getNumArgs(),
3046                                                 DTST->getArgs());
3047      T = getCanonicalType(T);
3048    }
3049
3050    return NestedNameSpecifier::Create(*this, 0, false,
3051                                       const_cast<Type*>(T.getTypePtr()));
3052  }
3053
3054  case NestedNameSpecifier::Global:
3055    // The global specifier is canonical and unique.
3056    return NNS;
3057  }
3058
3059  // Required to silence a GCC warning
3060  return 0;
3061}
3062
3063
3064const ArrayType *ASTContext::getAsArrayType(QualType T) const {
3065  // Handle the non-qualified case efficiently.
3066  if (!T.hasLocalQualifiers()) {
3067    // Handle the common positive case fast.
3068    if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3069      return AT;
3070  }
3071
3072  // Handle the common negative case fast.
3073  if (!isa<ArrayType>(T.getCanonicalType()))
3074    return 0;
3075
3076  // Apply any qualifiers from the array type to the element type.  This
3077  // implements C99 6.7.3p8: "If the specification of an array type includes
3078  // any type qualifiers, the element type is so qualified, not the array type."
3079
3080  // If we get here, we either have type qualifiers on the type, or we have
3081  // sugar such as a typedef in the way.  If we have type qualifiers on the type
3082  // we must propagate them down into the element type.
3083
3084  SplitQualType split = T.getSplitDesugaredType();
3085  Qualifiers qs = split.second;
3086
3087  // If we have a simple case, just return now.
3088  const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3089  if (ATy == 0 || qs.empty())
3090    return ATy;
3091
3092  // Otherwise, we have an array and we have qualifiers on it.  Push the
3093  // qualifiers into the array element type and return a new array type.
3094  QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
3095
3096  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3097    return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3098                                                CAT->getSizeModifier(),
3099                                           CAT->getIndexTypeCVRQualifiers()));
3100  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3101    return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3102                                                  IAT->getSizeModifier(),
3103                                           IAT->getIndexTypeCVRQualifiers()));
3104
3105  if (const DependentSizedArrayType *DSAT
3106        = dyn_cast<DependentSizedArrayType>(ATy))
3107    return cast<ArrayType>(
3108                     getDependentSizedArrayType(NewEltTy,
3109                                                DSAT->getSizeExpr(),
3110                                                DSAT->getSizeModifier(),
3111                                              DSAT->getIndexTypeCVRQualifiers(),
3112                                                DSAT->getBracketsRange()));
3113
3114  const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
3115  return cast<ArrayType>(getVariableArrayType(NewEltTy,
3116                                              VAT->getSizeExpr(),
3117                                              VAT->getSizeModifier(),
3118                                              VAT->getIndexTypeCVRQualifiers(),
3119                                              VAT->getBracketsRange()));
3120}
3121
3122/// getArrayDecayedType - Return the properly qualified result of decaying the
3123/// specified array type to a pointer.  This operation is non-trivial when
3124/// handling typedefs etc.  The canonical type of "T" must be an array type,
3125/// this returns a pointer to a properly qualified element of the array.
3126///
3127/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
3128QualType ASTContext::getArrayDecayedType(QualType Ty) const {
3129  // Get the element type with 'getAsArrayType' so that we don't lose any
3130  // typedefs in the element type of the array.  This also handles propagation
3131  // of type qualifiers from the array type into the element type if present
3132  // (C99 6.7.3p8).
3133  const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3134  assert(PrettyArrayType && "Not an array type!");
3135
3136  QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
3137
3138  // int x[restrict 4] ->  int *restrict
3139  return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
3140}
3141
3142QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3143  return getBaseElementType(array->getElementType());
3144}
3145
3146QualType ASTContext::getBaseElementType(QualType type) const {
3147  Qualifiers qs;
3148  while (true) {
3149    SplitQualType split = type.getSplitDesugaredType();
3150    const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3151    if (!array) break;
3152
3153    type = array->getElementType();
3154    qs.addConsistentQualifiers(split.second);
3155  }
3156
3157  return getQualifiedType(type, qs);
3158}
3159
3160/// getConstantArrayElementCount - Returns number of constant array elements.
3161uint64_t
3162ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
3163  uint64_t ElementCount = 1;
3164  do {
3165    ElementCount *= CA->getSize().getZExtValue();
3166    CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3167  } while (CA);
3168  return ElementCount;
3169}
3170
3171/// getFloatingRank - Return a relative rank for floating point types.
3172/// This routine will assert if passed a built-in type that isn't a float.
3173static FloatingRank getFloatingRank(QualType T) {
3174  if (const ComplexType *CT = T->getAs<ComplexType>())
3175    return getFloatingRank(CT->getElementType());
3176
3177  assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3178  switch (T->getAs<BuiltinType>()->getKind()) {
3179  default: assert(0 && "getFloatingRank(): not a floating type");
3180  case BuiltinType::Float:      return FloatRank;
3181  case BuiltinType::Double:     return DoubleRank;
3182  case BuiltinType::LongDouble: return LongDoubleRank;
3183  }
3184}
3185
3186/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3187/// point or a complex type (based on typeDomain/typeSize).
3188/// 'typeDomain' is a real floating point or complex type.
3189/// 'typeSize' is a real floating point or complex type.
3190QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3191                                                       QualType Domain) const {
3192  FloatingRank EltRank = getFloatingRank(Size);
3193  if (Domain->isComplexType()) {
3194    switch (EltRank) {
3195    default: assert(0 && "getFloatingRank(): illegal value for rank");
3196    case FloatRank:      return FloatComplexTy;
3197    case DoubleRank:     return DoubleComplexTy;
3198    case LongDoubleRank: return LongDoubleComplexTy;
3199    }
3200  }
3201
3202  assert(Domain->isRealFloatingType() && "Unknown domain!");
3203  switch (EltRank) {
3204  default: assert(0 && "getFloatingRank(): illegal value for rank");
3205  case FloatRank:      return FloatTy;
3206  case DoubleRank:     return DoubleTy;
3207  case LongDoubleRank: return LongDoubleTy;
3208  }
3209}
3210
3211/// getFloatingTypeOrder - Compare the rank of the two specified floating
3212/// point types, ignoring the domain of the type (i.e. 'double' ==
3213/// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
3214/// LHS < RHS, return -1.
3215int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
3216  FloatingRank LHSR = getFloatingRank(LHS);
3217  FloatingRank RHSR = getFloatingRank(RHS);
3218
3219  if (LHSR == RHSR)
3220    return 0;
3221  if (LHSR > RHSR)
3222    return 1;
3223  return -1;
3224}
3225
3226/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3227/// routine will assert if passed a built-in type that isn't an integer or enum,
3228/// or if it is not canonicalized.
3229unsigned ASTContext::getIntegerRank(const Type *T) const {
3230  assert(T->isCanonicalUnqualified() && "T should be canonicalized");
3231  if (const EnumType* ET = dyn_cast<EnumType>(T))
3232    T = ET->getDecl()->getPromotionType().getTypePtr();
3233
3234  if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3235      T->isSpecificBuiltinType(BuiltinType::WChar_U))
3236    T = getFromTargetType(Target.getWCharType()).getTypePtr();
3237
3238  if (T->isSpecificBuiltinType(BuiltinType::Char16))
3239    T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3240
3241  if (T->isSpecificBuiltinType(BuiltinType::Char32))
3242    T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3243
3244  switch (cast<BuiltinType>(T)->getKind()) {
3245  default: assert(0 && "getIntegerRank(): not a built-in integer");
3246  case BuiltinType::Bool:
3247    return 1 + (getIntWidth(BoolTy) << 3);
3248  case BuiltinType::Char_S:
3249  case BuiltinType::Char_U:
3250  case BuiltinType::SChar:
3251  case BuiltinType::UChar:
3252    return 2 + (getIntWidth(CharTy) << 3);
3253  case BuiltinType::Short:
3254  case BuiltinType::UShort:
3255    return 3 + (getIntWidth(ShortTy) << 3);
3256  case BuiltinType::Int:
3257  case BuiltinType::UInt:
3258    return 4 + (getIntWidth(IntTy) << 3);
3259  case BuiltinType::Long:
3260  case BuiltinType::ULong:
3261    return 5 + (getIntWidth(LongTy) << 3);
3262  case BuiltinType::LongLong:
3263  case BuiltinType::ULongLong:
3264    return 6 + (getIntWidth(LongLongTy) << 3);
3265  case BuiltinType::Int128:
3266  case BuiltinType::UInt128:
3267    return 7 + (getIntWidth(Int128Ty) << 3);
3268  }
3269}
3270
3271/// \brief Whether this is a promotable bitfield reference according
3272/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3273///
3274/// \returns the type this bit-field will promote to, or NULL if no
3275/// promotion occurs.
3276QualType ASTContext::isPromotableBitField(Expr *E) const {
3277  if (E->isTypeDependent() || E->isValueDependent())
3278    return QualType();
3279
3280  FieldDecl *Field = E->getBitField();
3281  if (!Field)
3282    return QualType();
3283
3284  QualType FT = Field->getType();
3285
3286  llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3287  uint64_t BitWidth = BitWidthAP.getZExtValue();
3288  uint64_t IntSize = getTypeSize(IntTy);
3289  // GCC extension compatibility: if the bit-field size is less than or equal
3290  // to the size of int, it gets promoted no matter what its type is.
3291  // For instance, unsigned long bf : 4 gets promoted to signed int.
3292  if (BitWidth < IntSize)
3293    return IntTy;
3294
3295  if (BitWidth == IntSize)
3296    return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3297
3298  // Types bigger than int are not subject to promotions, and therefore act
3299  // like the base type.
3300  // FIXME: This doesn't quite match what gcc does, but what gcc does here
3301  // is ridiculous.
3302  return QualType();
3303}
3304
3305/// getPromotedIntegerType - Returns the type that Promotable will
3306/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3307/// integer type.
3308QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
3309  assert(!Promotable.isNull());
3310  assert(Promotable->isPromotableIntegerType());
3311  if (const EnumType *ET = Promotable->getAs<EnumType>())
3312    return ET->getDecl()->getPromotionType();
3313  if (Promotable->isSignedIntegerType())
3314    return IntTy;
3315  uint64_t PromotableSize = getTypeSize(Promotable);
3316  uint64_t IntSize = getTypeSize(IntTy);
3317  assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3318  return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3319}
3320
3321/// getIntegerTypeOrder - Returns the highest ranked integer type:
3322/// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
3323/// LHS < RHS, return -1.
3324int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
3325  const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3326  const Type *RHSC = getCanonicalType(RHS).getTypePtr();
3327  if (LHSC == RHSC) return 0;
3328
3329  bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3330  bool RHSUnsigned = RHSC->isUnsignedIntegerType();
3331
3332  unsigned LHSRank = getIntegerRank(LHSC);
3333  unsigned RHSRank = getIntegerRank(RHSC);
3334
3335  if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
3336    if (LHSRank == RHSRank) return 0;
3337    return LHSRank > RHSRank ? 1 : -1;
3338  }
3339
3340  // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3341  if (LHSUnsigned) {
3342    // If the unsigned [LHS] type is larger, return it.
3343    if (LHSRank >= RHSRank)
3344      return 1;
3345
3346    // If the signed type can represent all values of the unsigned type, it
3347    // wins.  Because we are dealing with 2's complement and types that are
3348    // powers of two larger than each other, this is always safe.
3349    return -1;
3350  }
3351
3352  // If the unsigned [RHS] type is larger, return it.
3353  if (RHSRank >= LHSRank)
3354    return -1;
3355
3356  // If the signed type can represent all values of the unsigned type, it
3357  // wins.  Because we are dealing with 2's complement and types that are
3358  // powers of two larger than each other, this is always safe.
3359  return 1;
3360}
3361
3362static RecordDecl *
3363CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
3364                 SourceLocation L, IdentifierInfo *Id) {
3365  if (Ctx.getLangOptions().CPlusPlus)
3366    return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3367  else
3368    return RecordDecl::Create(Ctx, TK, DC, L, Id);
3369}
3370
3371// getCFConstantStringType - Return the type used for constant CFStrings.
3372QualType ASTContext::getCFConstantStringType() const {
3373  if (!CFConstantStringTypeDecl) {
3374    CFConstantStringTypeDecl =
3375      CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
3376                       &Idents.get("NSConstantString"));
3377    CFConstantStringTypeDecl->startDefinition();
3378
3379    QualType FieldTypes[4];
3380
3381    // const int *isa;
3382    FieldTypes[0] = getPointerType(IntTy.withConst());
3383    // int flags;
3384    FieldTypes[1] = IntTy;
3385    // const char *str;
3386    FieldTypes[2] = getPointerType(CharTy.withConst());
3387    // long length;
3388    FieldTypes[3] = LongTy;
3389
3390    // Create fields
3391    for (unsigned i = 0; i < 4; ++i) {
3392      FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
3393                                           SourceLocation(), 0,
3394                                           FieldTypes[i], /*TInfo=*/0,
3395                                           /*BitWidth=*/0,
3396                                           /*Mutable=*/false);
3397      Field->setAccess(AS_public);
3398      CFConstantStringTypeDecl->addDecl(Field);
3399    }
3400
3401    CFConstantStringTypeDecl->completeDefinition();
3402  }
3403
3404  return getTagDeclType(CFConstantStringTypeDecl);
3405}
3406
3407void ASTContext::setCFConstantStringType(QualType T) {
3408  const RecordType *Rec = T->getAs<RecordType>();
3409  assert(Rec && "Invalid CFConstantStringType");
3410  CFConstantStringTypeDecl = Rec->getDecl();
3411}
3412
3413// getNSConstantStringType - Return the type used for constant NSStrings.
3414QualType ASTContext::getNSConstantStringType() const {
3415  if (!NSConstantStringTypeDecl) {
3416    NSConstantStringTypeDecl =
3417    CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
3418                     &Idents.get("__builtin_NSString"));
3419    NSConstantStringTypeDecl->startDefinition();
3420
3421    QualType FieldTypes[3];
3422
3423    // const int *isa;
3424    FieldTypes[0] = getPointerType(IntTy.withConst());
3425    // const char *str;
3426    FieldTypes[1] = getPointerType(CharTy.withConst());
3427    // unsigned int length;
3428    FieldTypes[2] = UnsignedIntTy;
3429
3430    // Create fields
3431    for (unsigned i = 0; i < 3; ++i) {
3432      FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3433                                           SourceLocation(), 0,
3434                                           FieldTypes[i], /*TInfo=*/0,
3435                                           /*BitWidth=*/0,
3436                                           /*Mutable=*/false);
3437      Field->setAccess(AS_public);
3438      NSConstantStringTypeDecl->addDecl(Field);
3439    }
3440
3441    NSConstantStringTypeDecl->completeDefinition();
3442  }
3443
3444  return getTagDeclType(NSConstantStringTypeDecl);
3445}
3446
3447void ASTContext::setNSConstantStringType(QualType T) {
3448  const RecordType *Rec = T->getAs<RecordType>();
3449  assert(Rec && "Invalid NSConstantStringType");
3450  NSConstantStringTypeDecl = Rec->getDecl();
3451}
3452
3453QualType ASTContext::getObjCFastEnumerationStateType() const {
3454  if (!ObjCFastEnumerationStateTypeDecl) {
3455    ObjCFastEnumerationStateTypeDecl =
3456      CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
3457                       &Idents.get("__objcFastEnumerationState"));
3458    ObjCFastEnumerationStateTypeDecl->startDefinition();
3459
3460    QualType FieldTypes[] = {
3461      UnsignedLongTy,
3462      getPointerType(ObjCIdTypedefType),
3463      getPointerType(UnsignedLongTy),
3464      getConstantArrayType(UnsignedLongTy,
3465                           llvm::APInt(32, 5), ArrayType::Normal, 0)
3466    };
3467
3468    for (size_t i = 0; i < 4; ++i) {
3469      FieldDecl *Field = FieldDecl::Create(*this,
3470                                           ObjCFastEnumerationStateTypeDecl,
3471                                           SourceLocation(), 0,
3472                                           FieldTypes[i], /*TInfo=*/0,
3473                                           /*BitWidth=*/0,
3474                                           /*Mutable=*/false);
3475      Field->setAccess(AS_public);
3476      ObjCFastEnumerationStateTypeDecl->addDecl(Field);
3477    }
3478
3479    ObjCFastEnumerationStateTypeDecl->completeDefinition();
3480  }
3481
3482  return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3483}
3484
3485QualType ASTContext::getBlockDescriptorType() const {
3486  if (BlockDescriptorType)
3487    return getTagDeclType(BlockDescriptorType);
3488
3489  RecordDecl *T;
3490  // FIXME: Needs the FlagAppleBlock bit.
3491  T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
3492                       &Idents.get("__block_descriptor"));
3493  T->startDefinition();
3494
3495  QualType FieldTypes[] = {
3496    UnsignedLongTy,
3497    UnsignedLongTy,
3498  };
3499
3500  const char *FieldNames[] = {
3501    "reserved",
3502    "Size"
3503  };
3504
3505  for (size_t i = 0; i < 2; ++i) {
3506    FieldDecl *Field = FieldDecl::Create(*this,
3507                                         T,
3508                                         SourceLocation(),
3509                                         &Idents.get(FieldNames[i]),
3510                                         FieldTypes[i], /*TInfo=*/0,
3511                                         /*BitWidth=*/0,
3512                                         /*Mutable=*/false);
3513    Field->setAccess(AS_public);
3514    T->addDecl(Field);
3515  }
3516
3517  T->completeDefinition();
3518
3519  BlockDescriptorType = T;
3520
3521  return getTagDeclType(BlockDescriptorType);
3522}
3523
3524void ASTContext::setBlockDescriptorType(QualType T) {
3525  const RecordType *Rec = T->getAs<RecordType>();
3526  assert(Rec && "Invalid BlockDescriptorType");
3527  BlockDescriptorType = Rec->getDecl();
3528}
3529
3530QualType ASTContext::getBlockDescriptorExtendedType() const {
3531  if (BlockDescriptorExtendedType)
3532    return getTagDeclType(BlockDescriptorExtendedType);
3533
3534  RecordDecl *T;
3535  // FIXME: Needs the FlagAppleBlock bit.
3536  T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
3537                       &Idents.get("__block_descriptor_withcopydispose"));
3538  T->startDefinition();
3539
3540  QualType FieldTypes[] = {
3541    UnsignedLongTy,
3542    UnsignedLongTy,
3543    getPointerType(VoidPtrTy),
3544    getPointerType(VoidPtrTy)
3545  };
3546
3547  const char *FieldNames[] = {
3548    "reserved",
3549    "Size",
3550    "CopyFuncPtr",
3551    "DestroyFuncPtr"
3552  };
3553
3554  for (size_t i = 0; i < 4; ++i) {
3555    FieldDecl *Field = FieldDecl::Create(*this,
3556                                         T,
3557                                         SourceLocation(),
3558                                         &Idents.get(FieldNames[i]),
3559                                         FieldTypes[i], /*TInfo=*/0,
3560                                         /*BitWidth=*/0,
3561                                         /*Mutable=*/false);
3562    Field->setAccess(AS_public);
3563    T->addDecl(Field);
3564  }
3565
3566  T->completeDefinition();
3567
3568  BlockDescriptorExtendedType = T;
3569
3570  return getTagDeclType(BlockDescriptorExtendedType);
3571}
3572
3573void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3574  const RecordType *Rec = T->getAs<RecordType>();
3575  assert(Rec && "Invalid BlockDescriptorType");
3576  BlockDescriptorExtendedType = Rec->getDecl();
3577}
3578
3579bool ASTContext::BlockRequiresCopying(QualType Ty) const {
3580  if (Ty->isBlockPointerType())
3581    return true;
3582  if (isObjCNSObjectType(Ty))
3583    return true;
3584  if (Ty->isObjCObjectPointerType())
3585    return true;
3586  if (getLangOptions().CPlusPlus) {
3587    if (const RecordType *RT = Ty->getAs<RecordType>()) {
3588      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3589      return RD->hasConstCopyConstructor(*this);
3590
3591    }
3592  }
3593  return false;
3594}
3595
3596QualType
3597ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
3598  //  type = struct __Block_byref_1_X {
3599  //    void *__isa;
3600  //    struct __Block_byref_1_X *__forwarding;
3601  //    unsigned int __flags;
3602  //    unsigned int __size;
3603  //    void *__copy_helper;            // as needed
3604  //    void *__destroy_help            // as needed
3605  //    int X;
3606  //  } *
3607
3608  bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3609
3610  // FIXME: Move up
3611  llvm::SmallString<36> Name;
3612  llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3613                                  ++UniqueBlockByRefTypeID << '_' << DeclName;
3614  RecordDecl *T;
3615  T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
3616                       &Idents.get(Name.str()));
3617  T->startDefinition();
3618  QualType Int32Ty = IntTy;
3619  assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3620  QualType FieldTypes[] = {
3621    getPointerType(VoidPtrTy),
3622    getPointerType(getTagDeclType(T)),
3623    Int32Ty,
3624    Int32Ty,
3625    getPointerType(VoidPtrTy),
3626    getPointerType(VoidPtrTy),
3627    Ty
3628  };
3629
3630  llvm::StringRef FieldNames[] = {
3631    "__isa",
3632    "__forwarding",
3633    "__flags",
3634    "__size",
3635    "__copy_helper",
3636    "__destroy_helper",
3637    DeclName,
3638  };
3639
3640  for (size_t i = 0; i < 7; ++i) {
3641    if (!HasCopyAndDispose && i >=4 && i <= 5)
3642      continue;
3643    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3644                                         &Idents.get(FieldNames[i]),
3645                                         FieldTypes[i], /*TInfo=*/0,
3646                                         /*BitWidth=*/0, /*Mutable=*/false);
3647    Field->setAccess(AS_public);
3648    T->addDecl(Field);
3649  }
3650
3651  T->completeDefinition();
3652
3653  return getPointerType(getTagDeclType(T));
3654}
3655
3656void ASTContext::setObjCFastEnumerationStateType(QualType T) {
3657  const RecordType *Rec = T->getAs<RecordType>();
3658  assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3659  ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3660}
3661
3662// This returns true if a type has been typedefed to BOOL:
3663// typedef <type> BOOL;
3664static bool isTypeTypedefedAsBOOL(QualType T) {
3665  if (const TypedefType *TT = dyn_cast<TypedefType>(T))
3666    if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3667      return II->isStr("BOOL");
3668
3669  return false;
3670}
3671
3672/// getObjCEncodingTypeSize returns size of type for objective-c encoding
3673/// purpose.
3674CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
3675  CharUnits sz = getTypeSizeInChars(type);
3676
3677  // Make all integer and enum types at least as large as an int
3678  if (sz.isPositive() && type->isIntegralOrEnumerationType())
3679    sz = std::max(sz, getTypeSizeInChars(IntTy));
3680  // Treat arrays as pointers, since that's how they're passed in.
3681  else if (type->isArrayType())
3682    sz = getTypeSizeInChars(VoidPtrTy);
3683  return sz;
3684}
3685
3686static inline
3687std::string charUnitsToString(const CharUnits &CU) {
3688  return llvm::itostr(CU.getQuantity());
3689}
3690
3691/// getObjCEncodingForBlock - Return the encoded type for this block
3692/// declaration.
3693std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3694  std::string S;
3695
3696  const BlockDecl *Decl = Expr->getBlockDecl();
3697  QualType BlockTy =
3698      Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3699  // Encode result type.
3700  getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
3701  // Compute size of all parameters.
3702  // Start with computing size of a pointer in number of bytes.
3703  // FIXME: There might(should) be a better way of doing this computation!
3704  SourceLocation Loc;
3705  CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3706  CharUnits ParmOffset = PtrSize;
3707  for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
3708       E = Decl->param_end(); PI != E; ++PI) {
3709    QualType PType = (*PI)->getType();
3710    CharUnits sz = getObjCEncodingTypeSize(PType);
3711    assert (sz.isPositive() && "BlockExpr - Incomplete param type");
3712    ParmOffset += sz;
3713  }
3714  // Size of the argument frame
3715  S += charUnitsToString(ParmOffset);
3716  // Block pointer and offset.
3717  S += "@?0";
3718  ParmOffset = PtrSize;
3719
3720  // Argument types.
3721  ParmOffset = PtrSize;
3722  for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3723       Decl->param_end(); PI != E; ++PI) {
3724    ParmVarDecl *PVDecl = *PI;
3725    QualType PType = PVDecl->getOriginalType();
3726    if (const ArrayType *AT =
3727          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3728      // Use array's original type only if it has known number of
3729      // elements.
3730      if (!isa<ConstantArrayType>(AT))
3731        PType = PVDecl->getType();
3732    } else if (PType->isFunctionType())
3733      PType = PVDecl->getType();
3734    getObjCEncodingForType(PType, S);
3735    S += charUnitsToString(ParmOffset);
3736    ParmOffset += getObjCEncodingTypeSize(PType);
3737  }
3738
3739  return S;
3740}
3741
3742void ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
3743                                                std::string& S) {
3744  // Encode result type.
3745  getObjCEncodingForType(Decl->getResultType(), S);
3746  CharUnits ParmOffset;
3747  // Compute size of all parameters.
3748  for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3749       E = Decl->param_end(); PI != E; ++PI) {
3750    QualType PType = (*PI)->getType();
3751    CharUnits sz = getObjCEncodingTypeSize(PType);
3752    assert (sz.isPositive() &&
3753        "getObjCEncodingForMethodDecl - Incomplete param type");
3754    ParmOffset += sz;
3755  }
3756  S += charUnitsToString(ParmOffset);
3757  ParmOffset = CharUnits::Zero();
3758
3759  // Argument types.
3760  for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3761       E = Decl->param_end(); PI != E; ++PI) {
3762    ParmVarDecl *PVDecl = *PI;
3763    QualType PType = PVDecl->getOriginalType();
3764    if (const ArrayType *AT =
3765          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3766      // Use array's original type only if it has known number of
3767      // elements.
3768      if (!isa<ConstantArrayType>(AT))
3769        PType = PVDecl->getType();
3770    } else if (PType->isFunctionType())
3771      PType = PVDecl->getType();
3772    getObjCEncodingForType(PType, S);
3773    S += charUnitsToString(ParmOffset);
3774    ParmOffset += getObjCEncodingTypeSize(PType);
3775  }
3776}
3777
3778/// getObjCEncodingForMethodDecl - Return the encoded type for this method
3779/// declaration.
3780void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
3781                                              std::string& S) const {
3782  // FIXME: This is not very efficient.
3783  // Encode type qualifer, 'in', 'inout', etc. for the return type.
3784  getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
3785  // Encode result type.
3786  getObjCEncodingForType(Decl->getResultType(), S);
3787  // Compute size of all parameters.
3788  // Start with computing size of a pointer in number of bytes.
3789  // FIXME: There might(should) be a better way of doing this computation!
3790  SourceLocation Loc;
3791  CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3792  // The first two arguments (self and _cmd) are pointers; account for
3793  // their size.
3794  CharUnits ParmOffset = 2 * PtrSize;
3795  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3796       E = Decl->sel_param_end(); PI != E; ++PI) {
3797    QualType PType = (*PI)->getType();
3798    CharUnits sz = getObjCEncodingTypeSize(PType);
3799    assert (sz.isPositive() &&
3800        "getObjCEncodingForMethodDecl - Incomplete param type");
3801    ParmOffset += sz;
3802  }
3803  S += charUnitsToString(ParmOffset);
3804  S += "@0:";
3805  S += charUnitsToString(PtrSize);
3806
3807  // Argument types.
3808  ParmOffset = 2 * PtrSize;
3809  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3810       E = Decl->sel_param_end(); PI != E; ++PI) {
3811    ParmVarDecl *PVDecl = *PI;
3812    QualType PType = PVDecl->getOriginalType();
3813    if (const ArrayType *AT =
3814          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3815      // Use array's original type only if it has known number of
3816      // elements.
3817      if (!isa<ConstantArrayType>(AT))
3818        PType = PVDecl->getType();
3819    } else if (PType->isFunctionType())
3820      PType = PVDecl->getType();
3821    // Process argument qualifiers for user supplied arguments; such as,
3822    // 'in', 'inout', etc.
3823    getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
3824    getObjCEncodingForType(PType, S);
3825    S += charUnitsToString(ParmOffset);
3826    ParmOffset += getObjCEncodingTypeSize(PType);
3827  }
3828}
3829
3830/// getObjCEncodingForPropertyDecl - Return the encoded type for this
3831/// property declaration. If non-NULL, Container must be either an
3832/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3833/// NULL when getting encodings for protocol properties.
3834/// Property attributes are stored as a comma-delimited C string. The simple
3835/// attributes readonly and bycopy are encoded as single characters. The
3836/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3837/// encoded as single characters, followed by an identifier. Property types
3838/// are also encoded as a parametrized attribute. The characters used to encode
3839/// these attributes are defined by the following enumeration:
3840/// @code
3841/// enum PropertyAttributes {
3842/// kPropertyReadOnly = 'R',   // property is read-only.
3843/// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
3844/// kPropertyByref = '&',  // property is a reference to the value last assigned
3845/// kPropertyDynamic = 'D',    // property is dynamic
3846/// kPropertyGetter = 'G',     // followed by getter selector name
3847/// kPropertySetter = 'S',     // followed by setter selector name
3848/// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
3849/// kPropertyType = 't'              // followed by old-style type encoding.
3850/// kPropertyWeak = 'W'              // 'weak' property
3851/// kPropertyStrong = 'P'            // property GC'able
3852/// kPropertyNonAtomic = 'N'         // property non-atomic
3853/// };
3854/// @endcode
3855void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
3856                                                const Decl *Container,
3857                                                std::string& S) const {
3858  // Collect information from the property implementation decl(s).
3859  bool Dynamic = false;
3860  ObjCPropertyImplDecl *SynthesizePID = 0;
3861
3862  // FIXME: Duplicated code due to poor abstraction.
3863  if (Container) {
3864    if (const ObjCCategoryImplDecl *CID =
3865        dyn_cast<ObjCCategoryImplDecl>(Container)) {
3866      for (ObjCCategoryImplDecl::propimpl_iterator
3867             i = CID->propimpl_begin(), e = CID->propimpl_end();
3868           i != e; ++i) {
3869        ObjCPropertyImplDecl *PID = *i;
3870        if (PID->getPropertyDecl() == PD) {
3871          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3872            Dynamic = true;
3873          } else {
3874            SynthesizePID = PID;
3875          }
3876        }
3877      }
3878    } else {
3879      const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
3880      for (ObjCCategoryImplDecl::propimpl_iterator
3881             i = OID->propimpl_begin(), e = OID->propimpl_end();
3882           i != e; ++i) {
3883        ObjCPropertyImplDecl *PID = *i;
3884        if (PID->getPropertyDecl() == PD) {
3885          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3886            Dynamic = true;
3887          } else {
3888            SynthesizePID = PID;
3889          }
3890        }
3891      }
3892    }
3893  }
3894
3895  // FIXME: This is not very efficient.
3896  S = "T";
3897
3898  // Encode result type.
3899  // GCC has some special rules regarding encoding of properties which
3900  // closely resembles encoding of ivars.
3901  getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
3902                             true /* outermost type */,
3903                             true /* encoding for property */);
3904
3905  if (PD->isReadOnly()) {
3906    S += ",R";
3907  } else {
3908    switch (PD->getSetterKind()) {
3909    case ObjCPropertyDecl::Assign: break;
3910    case ObjCPropertyDecl::Copy:   S += ",C"; break;
3911    case ObjCPropertyDecl::Retain: S += ",&"; break;
3912    }
3913  }
3914
3915  // It really isn't clear at all what this means, since properties
3916  // are "dynamic by default".
3917  if (Dynamic)
3918    S += ",D";
3919
3920  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3921    S += ",N";
3922
3923  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3924    S += ",G";
3925    S += PD->getGetterName().getAsString();
3926  }
3927
3928  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3929    S += ",S";
3930    S += PD->getSetterName().getAsString();
3931  }
3932
3933  if (SynthesizePID) {
3934    const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3935    S += ",V";
3936    S += OID->getNameAsString();
3937  }
3938
3939  // FIXME: OBJCGC: weak & strong
3940}
3941
3942/// getLegacyIntegralTypeEncoding -
3943/// Another legacy compatibility encoding: 32-bit longs are encoded as
3944/// 'l' or 'L' , but not always.  For typedefs, we need to use
3945/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3946///
3947void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
3948  if (isa<TypedefType>(PointeeTy.getTypePtr())) {
3949    if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
3950      if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
3951        PointeeTy = UnsignedIntTy;
3952      else
3953        if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
3954          PointeeTy = IntTy;
3955    }
3956  }
3957}
3958
3959void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
3960                                        const FieldDecl *Field) const {
3961  // We follow the behavior of gcc, expanding structures which are
3962  // directly pointed to, and expanding embedded structures. Note that
3963  // these rules are sufficient to prevent recursive encoding of the
3964  // same type.
3965  getObjCEncodingForTypeImpl(T, S, true, true, Field,
3966                             true /* outermost type */);
3967}
3968
3969static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3970    switch (T->getAs<BuiltinType>()->getKind()) {
3971    default: assert(0 && "Unhandled builtin type kind");
3972    case BuiltinType::Void:       return 'v';
3973    case BuiltinType::Bool:       return 'B';
3974    case BuiltinType::Char_U:
3975    case BuiltinType::UChar:      return 'C';
3976    case BuiltinType::UShort:     return 'S';
3977    case BuiltinType::UInt:       return 'I';
3978    case BuiltinType::ULong:
3979        return C->getIntWidth(T) == 32 ? 'L' : 'Q';
3980    case BuiltinType::UInt128:    return 'T';
3981    case BuiltinType::ULongLong:  return 'Q';
3982    case BuiltinType::Char_S:
3983    case BuiltinType::SChar:      return 'c';
3984    case BuiltinType::Short:      return 's';
3985    case BuiltinType::WChar_S:
3986    case BuiltinType::WChar_U:
3987    case BuiltinType::Int:        return 'i';
3988    case BuiltinType::Long:
3989      return C->getIntWidth(T) == 32 ? 'l' : 'q';
3990    case BuiltinType::LongLong:   return 'q';
3991    case BuiltinType::Int128:     return 't';
3992    case BuiltinType::Float:      return 'f';
3993    case BuiltinType::Double:     return 'd';
3994    case BuiltinType::LongDouble: return 'D';
3995    }
3996}
3997
3998static void EncodeBitField(const ASTContext *Ctx, std::string& S,
3999                           QualType T, const FieldDecl *FD) {
4000  const Expr *E = FD->getBitWidth();
4001  assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
4002  S += 'b';
4003  // The NeXT runtime encodes bit fields as b followed by the number of bits.
4004  // The GNU runtime requires more information; bitfields are encoded as b,
4005  // then the offset (in bits) of the first element, then the type of the
4006  // bitfield, then the size in bits.  For example, in this structure:
4007  //
4008  // struct
4009  // {
4010  //    int integer;
4011  //    int flags:2;
4012  // };
4013  // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4014  // runtime, but b32i2 for the GNU runtime.  The reason for this extra
4015  // information is not especially sensible, but we're stuck with it for
4016  // compatibility with GCC, although providing it breaks anything that
4017  // actually uses runtime introspection and wants to work on both runtimes...
4018  if (!Ctx->getLangOptions().NeXTRuntime) {
4019    const RecordDecl *RD = FD->getParent();
4020    const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
4021    // FIXME: This same linear search is also used in ExprConstant - it might
4022    // be better if the FieldDecl stored its offset.  We'd be increasing the
4023    // size of the object slightly, but saving some time every time it is used.
4024    unsigned i = 0;
4025    for (RecordDecl::field_iterator Field = RD->field_begin(),
4026                                 FieldEnd = RD->field_end();
4027         Field != FieldEnd; (void)++Field, ++i) {
4028      if (*Field == FD)
4029        break;
4030    }
4031    S += llvm::utostr(RL.getFieldOffset(i));
4032    if (T->isEnumeralType())
4033      S += 'i';
4034    else
4035      S += ObjCEncodingForPrimitiveKind(Ctx, T);
4036  }
4037  unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
4038  S += llvm::utostr(N);
4039}
4040
4041// FIXME: Use SmallString for accumulating string.
4042void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4043                                            bool ExpandPointedToStructures,
4044                                            bool ExpandStructures,
4045                                            const FieldDecl *FD,
4046                                            bool OutermostType,
4047                                            bool EncodingProperty) const {
4048  if (T->getAs<BuiltinType>()) {
4049    if (FD && FD->isBitField())
4050      return EncodeBitField(this, S, T, FD);
4051    S += ObjCEncodingForPrimitiveKind(this, T);
4052    return;
4053  }
4054
4055  if (const ComplexType *CT = T->getAs<ComplexType>()) {
4056    S += 'j';
4057    getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
4058                               false);
4059    return;
4060  }
4061
4062  // encoding for pointer or r3eference types.
4063  QualType PointeeTy;
4064  if (const PointerType *PT = T->getAs<PointerType>()) {
4065    if (PT->isObjCSelType()) {
4066      S += ':';
4067      return;
4068    }
4069    PointeeTy = PT->getPointeeType();
4070  }
4071  else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4072    PointeeTy = RT->getPointeeType();
4073  if (!PointeeTy.isNull()) {
4074    bool isReadOnly = false;
4075    // For historical/compatibility reasons, the read-only qualifier of the
4076    // pointee gets emitted _before_ the '^'.  The read-only qualifier of
4077    // the pointer itself gets ignored, _unless_ we are looking at a typedef!
4078    // Also, do not emit the 'r' for anything but the outermost type!
4079    if (isa<TypedefType>(T.getTypePtr())) {
4080      if (OutermostType && T.isConstQualified()) {
4081        isReadOnly = true;
4082        S += 'r';
4083      }
4084    } else if (OutermostType) {
4085      QualType P = PointeeTy;
4086      while (P->getAs<PointerType>())
4087        P = P->getAs<PointerType>()->getPointeeType();
4088      if (P.isConstQualified()) {
4089        isReadOnly = true;
4090        S += 'r';
4091      }
4092    }
4093    if (isReadOnly) {
4094      // Another legacy compatibility encoding. Some ObjC qualifier and type
4095      // combinations need to be rearranged.
4096      // Rewrite "in const" from "nr" to "rn"
4097      if (llvm::StringRef(S).endswith("nr"))
4098        S.replace(S.end()-2, S.end(), "rn");
4099    }
4100
4101    if (PointeeTy->isCharType()) {
4102      // char pointer types should be encoded as '*' unless it is a
4103      // type that has been typedef'd to 'BOOL'.
4104      if (!isTypeTypedefedAsBOOL(PointeeTy)) {
4105        S += '*';
4106        return;
4107      }
4108    } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
4109      // GCC binary compat: Need to convert "struct objc_class *" to "#".
4110      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4111        S += '#';
4112        return;
4113      }
4114      // GCC binary compat: Need to convert "struct objc_object *" to "@".
4115      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4116        S += '@';
4117        return;
4118      }
4119      // fall through...
4120    }
4121    S += '^';
4122    getLegacyIntegralTypeEncoding(PointeeTy);
4123
4124    getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
4125                               NULL);
4126    return;
4127  }
4128
4129  if (const ArrayType *AT =
4130      // Ignore type qualifiers etc.
4131        dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
4132    if (isa<IncompleteArrayType>(AT)) {
4133      // Incomplete arrays are encoded as a pointer to the array element.
4134      S += '^';
4135
4136      getObjCEncodingForTypeImpl(AT->getElementType(), S,
4137                                 false, ExpandStructures, FD);
4138    } else {
4139      S += '[';
4140
4141      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
4142        S += llvm::utostr(CAT->getSize().getZExtValue());
4143      else {
4144        //Variable length arrays are encoded as a regular array with 0 elements.
4145        assert(isa<VariableArrayType>(AT) && "Unknown array type!");
4146        S += '0';
4147      }
4148
4149      getObjCEncodingForTypeImpl(AT->getElementType(), S,
4150                                 false, ExpandStructures, FD);
4151      S += ']';
4152    }
4153    return;
4154  }
4155
4156  if (T->getAs<FunctionType>()) {
4157    S += '?';
4158    return;
4159  }
4160
4161  if (const RecordType *RTy = T->getAs<RecordType>()) {
4162    RecordDecl *RDecl = RTy->getDecl();
4163    S += RDecl->isUnion() ? '(' : '{';
4164    // Anonymous structures print as '?'
4165    if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4166      S += II->getName();
4167      if (ClassTemplateSpecializationDecl *Spec
4168          = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4169        const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4170        std::string TemplateArgsStr
4171          = TemplateSpecializationType::PrintTemplateArgumentList(
4172                                            TemplateArgs.data(),
4173                                            TemplateArgs.size(),
4174                                            (*this).PrintingPolicy);
4175
4176        S += TemplateArgsStr;
4177      }
4178    } else {
4179      S += '?';
4180    }
4181    if (ExpandStructures) {
4182      S += '=';
4183      for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4184                                   FieldEnd = RDecl->field_end();
4185           Field != FieldEnd; ++Field) {
4186        if (FD) {
4187          S += '"';
4188          S += Field->getNameAsString();
4189          S += '"';
4190        }
4191
4192        // Special case bit-fields.
4193        if (Field->isBitField()) {
4194          getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4195                                     (*Field));
4196        } else {
4197          QualType qt = Field->getType();
4198          getLegacyIntegralTypeEncoding(qt);
4199          getObjCEncodingForTypeImpl(qt, S, false, true,
4200                                     FD);
4201        }
4202      }
4203    }
4204    S += RDecl->isUnion() ? ')' : '}';
4205    return;
4206  }
4207
4208  if (T->isEnumeralType()) {
4209    if (FD && FD->isBitField())
4210      EncodeBitField(this, S, T, FD);
4211    else
4212      S += 'i';
4213    return;
4214  }
4215
4216  if (T->isBlockPointerType()) {
4217    S += "@?"; // Unlike a pointer-to-function, which is "^?".
4218    return;
4219  }
4220
4221  // Ignore protocol qualifiers when mangling at this level.
4222  if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4223    T = OT->getBaseType();
4224
4225  if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
4226    // @encode(class_name)
4227    ObjCInterfaceDecl *OI = OIT->getDecl();
4228    S += '{';
4229    const IdentifierInfo *II = OI->getIdentifier();
4230    S += II->getName();
4231    S += '=';
4232    llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4233    DeepCollectObjCIvars(OI, true, Ivars);
4234    for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4235      FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4236      if (Field->isBitField())
4237        getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
4238      else
4239        getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
4240    }
4241    S += '}';
4242    return;
4243  }
4244
4245  if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
4246    if (OPT->isObjCIdType()) {
4247      S += '@';
4248      return;
4249    }
4250
4251    if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4252      // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4253      // Since this is a binary compatibility issue, need to consult with runtime
4254      // folks. Fortunately, this is a *very* obsure construct.
4255      S += '#';
4256      return;
4257    }
4258
4259    if (OPT->isObjCQualifiedIdType()) {
4260      getObjCEncodingForTypeImpl(getObjCIdType(), S,
4261                                 ExpandPointedToStructures,
4262                                 ExpandStructures, FD);
4263      if (FD || EncodingProperty) {
4264        // Note that we do extended encoding of protocol qualifer list
4265        // Only when doing ivar or property encoding.
4266        S += '"';
4267        for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4268             E = OPT->qual_end(); I != E; ++I) {
4269          S += '<';
4270          S += (*I)->getNameAsString();
4271          S += '>';
4272        }
4273        S += '"';
4274      }
4275      return;
4276    }
4277
4278    QualType PointeeTy = OPT->getPointeeType();
4279    if (!EncodingProperty &&
4280        isa<TypedefType>(PointeeTy.getTypePtr())) {
4281      // Another historical/compatibility reason.
4282      // We encode the underlying type which comes out as
4283      // {...};
4284      S += '^';
4285      getObjCEncodingForTypeImpl(PointeeTy, S,
4286                                 false, ExpandPointedToStructures,
4287                                 NULL);
4288      return;
4289    }
4290
4291    S += '@';
4292    if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
4293      S += '"';
4294      S += OPT->getInterfaceDecl()->getIdentifier()->getName();
4295      for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4296           E = OPT->qual_end(); I != E; ++I) {
4297        S += '<';
4298        S += (*I)->getNameAsString();
4299        S += '>';
4300      }
4301      S += '"';
4302    }
4303    return;
4304  }
4305
4306  // gcc just blithely ignores member pointers.
4307  // TODO: maybe there should be a mangling for these
4308  if (T->getAs<MemberPointerType>())
4309    return;
4310
4311  if (T->isVectorType()) {
4312    // This matches gcc's encoding, even though technically it is
4313    // insufficient.
4314    // FIXME. We should do a better job than gcc.
4315    return;
4316  }
4317
4318  assert(0 && "@encode for type not implemented!");
4319}
4320
4321void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
4322                                                 std::string& S) const {
4323  if (QT & Decl::OBJC_TQ_In)
4324    S += 'n';
4325  if (QT & Decl::OBJC_TQ_Inout)
4326    S += 'N';
4327  if (QT & Decl::OBJC_TQ_Out)
4328    S += 'o';
4329  if (QT & Decl::OBJC_TQ_Bycopy)
4330    S += 'O';
4331  if (QT & Decl::OBJC_TQ_Byref)
4332    S += 'R';
4333  if (QT & Decl::OBJC_TQ_Oneway)
4334    S += 'V';
4335}
4336
4337void ASTContext::setBuiltinVaListType(QualType T) {
4338  assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
4339
4340  BuiltinVaListType = T;
4341}
4342
4343void ASTContext::setObjCIdType(QualType T) {
4344  ObjCIdTypedefType = T;
4345}
4346
4347void ASTContext::setObjCSelType(QualType T) {
4348  ObjCSelTypedefType = T;
4349}
4350
4351void ASTContext::setObjCProtoType(QualType QT) {
4352  ObjCProtoType = QT;
4353}
4354
4355void ASTContext::setObjCClassType(QualType T) {
4356  ObjCClassTypedefType = T;
4357}
4358
4359void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
4360  assert(ObjCConstantStringType.isNull() &&
4361         "'NSConstantString' type already set!");
4362
4363  ObjCConstantStringType = getObjCInterfaceType(Decl);
4364}
4365
4366/// \brief Retrieve the template name that corresponds to a non-empty
4367/// lookup.
4368TemplateName
4369ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4370                                      UnresolvedSetIterator End) const {
4371  unsigned size = End - Begin;
4372  assert(size > 1 && "set is not overloaded!");
4373
4374  void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4375                          size * sizeof(FunctionTemplateDecl*));
4376  OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4377
4378  NamedDecl **Storage = OT->getStorage();
4379  for (UnresolvedSetIterator I = Begin; I != End; ++I) {
4380    NamedDecl *D = *I;
4381    assert(isa<FunctionTemplateDecl>(D) ||
4382           (isa<UsingShadowDecl>(D) &&
4383            isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4384    *Storage++ = D;
4385  }
4386
4387  return TemplateName(OT);
4388}
4389
4390/// \brief Retrieve the template name that represents a qualified
4391/// template name such as \c std::vector.
4392TemplateName
4393ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4394                                     bool TemplateKeyword,
4395                                     TemplateDecl *Template) const {
4396  assert(NNS && "Missing nested-name-specifier in qualified template name");
4397
4398  // FIXME: Canonicalization?
4399  llvm::FoldingSetNodeID ID;
4400  QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4401
4402  void *InsertPos = 0;
4403  QualifiedTemplateName *QTN =
4404    QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4405  if (!QTN) {
4406    QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4407    QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4408  }
4409
4410  return TemplateName(QTN);
4411}
4412
4413/// \brief Retrieve the template name that represents a dependent
4414/// template name such as \c MetaFun::template apply.
4415TemplateName
4416ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4417                                     const IdentifierInfo *Name) const {
4418  assert((!NNS || NNS->isDependent()) &&
4419         "Nested name specifier must be dependent");
4420
4421  llvm::FoldingSetNodeID ID;
4422  DependentTemplateName::Profile(ID, NNS, Name);
4423
4424  void *InsertPos = 0;
4425  DependentTemplateName *QTN =
4426    DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4427
4428  if (QTN)
4429    return TemplateName(QTN);
4430
4431  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4432  if (CanonNNS == NNS) {
4433    QTN = new (*this,4) DependentTemplateName(NNS, Name);
4434  } else {
4435    TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4436    QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
4437    DependentTemplateName *CheckQTN =
4438      DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4439    assert(!CheckQTN && "Dependent type name canonicalization broken");
4440    (void)CheckQTN;
4441  }
4442
4443  DependentTemplateNames.InsertNode(QTN, InsertPos);
4444  return TemplateName(QTN);
4445}
4446
4447/// \brief Retrieve the template name that represents a dependent
4448/// template name such as \c MetaFun::template operator+.
4449TemplateName
4450ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4451                                     OverloadedOperatorKind Operator) const {
4452  assert((!NNS || NNS->isDependent()) &&
4453         "Nested name specifier must be dependent");
4454
4455  llvm::FoldingSetNodeID ID;
4456  DependentTemplateName::Profile(ID, NNS, Operator);
4457
4458  void *InsertPos = 0;
4459  DependentTemplateName *QTN
4460    = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4461
4462  if (QTN)
4463    return TemplateName(QTN);
4464
4465  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4466  if (CanonNNS == NNS) {
4467    QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4468  } else {
4469    TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4470    QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
4471
4472    DependentTemplateName *CheckQTN
4473      = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4474    assert(!CheckQTN && "Dependent template name canonicalization broken");
4475    (void)CheckQTN;
4476  }
4477
4478  DependentTemplateNames.InsertNode(QTN, InsertPos);
4479  return TemplateName(QTN);
4480}
4481
4482TemplateName
4483ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4484                                       const TemplateArgument &ArgPack) const {
4485  ASTContext &Self = const_cast<ASTContext &>(*this);
4486  llvm::FoldingSetNodeID ID;
4487  SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4488
4489  void *InsertPos = 0;
4490  SubstTemplateTemplateParmPackStorage *Subst
4491    = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4492
4493  if (!Subst) {
4494    Subst = new (*this) SubstTemplateTemplateParmPackStorage(Self, Param,
4495                                                           ArgPack.pack_size(),
4496                                                         ArgPack.pack_begin());
4497    SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4498  }
4499
4500  return TemplateName(Subst);
4501}
4502
4503/// getFromTargetType - Given one of the integer types provided by
4504/// TargetInfo, produce the corresponding type. The unsigned @p Type
4505/// is actually a value of type @c TargetInfo::IntType.
4506CanQualType ASTContext::getFromTargetType(unsigned Type) const {
4507  switch (Type) {
4508  case TargetInfo::NoInt: return CanQualType();
4509  case TargetInfo::SignedShort: return ShortTy;
4510  case TargetInfo::UnsignedShort: return UnsignedShortTy;
4511  case TargetInfo::SignedInt: return IntTy;
4512  case TargetInfo::UnsignedInt: return UnsignedIntTy;
4513  case TargetInfo::SignedLong: return LongTy;
4514  case TargetInfo::UnsignedLong: return UnsignedLongTy;
4515  case TargetInfo::SignedLongLong: return LongLongTy;
4516  case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4517  }
4518
4519  assert(false && "Unhandled TargetInfo::IntType value");
4520  return CanQualType();
4521}
4522
4523//===----------------------------------------------------------------------===//
4524//                        Type Predicates.
4525//===----------------------------------------------------------------------===//
4526
4527/// isObjCNSObjectType - Return true if this is an NSObject object using
4528/// NSObject attribute on a c-style pointer type.
4529/// FIXME - Make it work directly on types.
4530/// FIXME: Move to Type.
4531///
4532bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4533  if (const TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4534    if (TypedefDecl *TD = TDT->getDecl())
4535      if (TD->getAttr<ObjCNSObjectAttr>())
4536        return true;
4537  }
4538  return false;
4539}
4540
4541/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4542/// garbage collection attribute.
4543///
4544Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4545  if (getLangOptions().getGCMode() == LangOptions::NonGC)
4546    return Qualifiers::GCNone;
4547
4548  assert(getLangOptions().ObjC1);
4549  Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4550
4551  // Default behaviour under objective-C's gc is for ObjC pointers
4552  // (or pointers to them) be treated as though they were declared
4553  // as __strong.
4554  if (GCAttrs == Qualifiers::GCNone) {
4555    if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4556      return Qualifiers::Strong;
4557    else if (Ty->isPointerType())
4558      return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4559  } else {
4560    // It's not valid to set GC attributes on anything that isn't a
4561    // pointer.
4562#ifndef NDEBUG
4563    QualType CT = Ty->getCanonicalTypeInternal();
4564    while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4565      CT = AT->getElementType();
4566    assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4567#endif
4568  }
4569  return GCAttrs;
4570}
4571
4572//===----------------------------------------------------------------------===//
4573//                        Type Compatibility Testing
4574//===----------------------------------------------------------------------===//
4575
4576/// areCompatVectorTypes - Return true if the two specified vector types are
4577/// compatible.
4578static bool areCompatVectorTypes(const VectorType *LHS,
4579                                 const VectorType *RHS) {
4580  assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
4581  return LHS->getElementType() == RHS->getElementType() &&
4582         LHS->getNumElements() == RHS->getNumElements();
4583}
4584
4585bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4586                                          QualType SecondVec) {
4587  assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4588  assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4589
4590  if (hasSameUnqualifiedType(FirstVec, SecondVec))
4591    return true;
4592
4593  // Treat Neon vector types and most AltiVec vector types as if they are the
4594  // equivalent GCC vector types.
4595  const VectorType *First = FirstVec->getAs<VectorType>();
4596  const VectorType *Second = SecondVec->getAs<VectorType>();
4597  if (First->getNumElements() == Second->getNumElements() &&
4598      hasSameType(First->getElementType(), Second->getElementType()) &&
4599      First->getVectorKind() != VectorType::AltiVecPixel &&
4600      First->getVectorKind() != VectorType::AltiVecBool &&
4601      Second->getVectorKind() != VectorType::AltiVecPixel &&
4602      Second->getVectorKind() != VectorType::AltiVecBool)
4603    return true;
4604
4605  return false;
4606}
4607
4608//===----------------------------------------------------------------------===//
4609// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4610//===----------------------------------------------------------------------===//
4611
4612/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4613/// inheritance hierarchy of 'rProto'.
4614bool
4615ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4616                                           ObjCProtocolDecl *rProto) const {
4617  if (lProto == rProto)
4618    return true;
4619  for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4620       E = rProto->protocol_end(); PI != E; ++PI)
4621    if (ProtocolCompatibleWithProtocol(lProto, *PI))
4622      return true;
4623  return false;
4624}
4625
4626/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4627/// return true if lhs's protocols conform to rhs's protocol; false
4628/// otherwise.
4629bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4630  if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4631    return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4632  return false;
4633}
4634
4635/// ObjCQualifiedClassTypesAreCompatible - compare  Class<p,...> and
4636/// Class<p1, ...>.
4637bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4638                                                      QualType rhs) {
4639  const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4640  const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4641  assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4642
4643  for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4644       E = lhsQID->qual_end(); I != E; ++I) {
4645    bool match = false;
4646    ObjCProtocolDecl *lhsProto = *I;
4647    for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4648         E = rhsOPT->qual_end(); J != E; ++J) {
4649      ObjCProtocolDecl *rhsProto = *J;
4650      if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4651        match = true;
4652        break;
4653      }
4654    }
4655    if (!match)
4656      return false;
4657  }
4658  return true;
4659}
4660
4661/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4662/// ObjCQualifiedIDType.
4663bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4664                                                   bool compare) {
4665  // Allow id<P..> and an 'id' or void* type in all cases.
4666  if (lhs->isVoidPointerType() ||
4667      lhs->isObjCIdType() || lhs->isObjCClassType())
4668    return true;
4669  else if (rhs->isVoidPointerType() ||
4670           rhs->isObjCIdType() || rhs->isObjCClassType())
4671    return true;
4672
4673  if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
4674    const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4675
4676    if (!rhsOPT) return false;
4677
4678    if (rhsOPT->qual_empty()) {
4679      // If the RHS is a unqualified interface pointer "NSString*",
4680      // make sure we check the class hierarchy.
4681      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4682        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4683             E = lhsQID->qual_end(); I != E; ++I) {
4684          // when comparing an id<P> on lhs with a static type on rhs,
4685          // see if static class implements all of id's protocols, directly or
4686          // through its super class and categories.
4687          if (!rhsID->ClassImplementsProtocol(*I, true))
4688            return false;
4689        }
4690      }
4691      // If there are no qualifiers and no interface, we have an 'id'.
4692      return true;
4693    }
4694    // Both the right and left sides have qualifiers.
4695    for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4696         E = lhsQID->qual_end(); I != E; ++I) {
4697      ObjCProtocolDecl *lhsProto = *I;
4698      bool match = false;
4699
4700      // when comparing an id<P> on lhs with a static type on rhs,
4701      // see if static class implements all of id's protocols, directly or
4702      // through its super class and categories.
4703      for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4704           E = rhsOPT->qual_end(); J != E; ++J) {
4705        ObjCProtocolDecl *rhsProto = *J;
4706        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4707            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4708          match = true;
4709          break;
4710        }
4711      }
4712      // If the RHS is a qualified interface pointer "NSString<P>*",
4713      // make sure we check the class hierarchy.
4714      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4715        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4716             E = lhsQID->qual_end(); I != E; ++I) {
4717          // when comparing an id<P> on lhs with a static type on rhs,
4718          // see if static class implements all of id's protocols, directly or
4719          // through its super class and categories.
4720          if (rhsID->ClassImplementsProtocol(*I, true)) {
4721            match = true;
4722            break;
4723          }
4724        }
4725      }
4726      if (!match)
4727        return false;
4728    }
4729
4730    return true;
4731  }
4732
4733  const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4734  assert(rhsQID && "One of the LHS/RHS should be id<x>");
4735
4736  if (const ObjCObjectPointerType *lhsOPT =
4737        lhs->getAsObjCInterfacePointerType()) {
4738    // If both the right and left sides have qualifiers.
4739    for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4740         E = lhsOPT->qual_end(); I != E; ++I) {
4741      ObjCProtocolDecl *lhsProto = *I;
4742      bool match = false;
4743
4744      // when comparing an id<P> on rhs with a static type on lhs,
4745      // see if static class implements all of id's protocols, directly or
4746      // through its super class and categories.
4747      // First, lhs protocols in the qualifier list must be found, direct
4748      // or indirect in rhs's qualifier list or it is a mismatch.
4749      for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4750           E = rhsQID->qual_end(); J != E; ++J) {
4751        ObjCProtocolDecl *rhsProto = *J;
4752        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4753            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4754          match = true;
4755          break;
4756        }
4757      }
4758      if (!match)
4759        return false;
4760    }
4761
4762    // Static class's protocols, or its super class or category protocols
4763    // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
4764    if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4765      llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4766      CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
4767      // This is rather dubious but matches gcc's behavior. If lhs has
4768      // no type qualifier and its class has no static protocol(s)
4769      // assume that it is mismatch.
4770      if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
4771        return false;
4772      for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4773           LHSInheritedProtocols.begin(),
4774           E = LHSInheritedProtocols.end(); I != E; ++I) {
4775        bool match = false;
4776        ObjCProtocolDecl *lhsProto = (*I);
4777        for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4778             E = rhsQID->qual_end(); J != E; ++J) {
4779          ObjCProtocolDecl *rhsProto = *J;
4780          if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4781              (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4782            match = true;
4783            break;
4784          }
4785        }
4786        if (!match)
4787          return false;
4788      }
4789    }
4790    return true;
4791  }
4792  return false;
4793}
4794
4795/// canAssignObjCInterfaces - Return true if the two interface types are
4796/// compatible for assignment from RHS to LHS.  This handles validation of any
4797/// protocol qualifiers on the LHS or RHS.
4798///
4799bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4800                                         const ObjCObjectPointerType *RHSOPT) {
4801  const ObjCObjectType* LHS = LHSOPT->getObjectType();
4802  const ObjCObjectType* RHS = RHSOPT->getObjectType();
4803
4804  // If either type represents the built-in 'id' or 'Class' types, return true.
4805  if (LHS->isObjCUnqualifiedIdOrClass() ||
4806      RHS->isObjCUnqualifiedIdOrClass())
4807    return true;
4808
4809  if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
4810    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4811                                             QualType(RHSOPT,0),
4812                                             false);
4813
4814  if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4815    return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4816                                                QualType(RHSOPT,0));
4817
4818  // If we have 2 user-defined types, fall into that path.
4819  if (LHS->getInterface() && RHS->getInterface())
4820    return canAssignObjCInterfaces(LHS, RHS);
4821
4822  return false;
4823}
4824
4825/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4826/// for providing type-safty for objective-c pointers used to pass/return
4827/// arguments in block literals. When passed as arguments, passing 'A*' where
4828/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4829/// not OK. For the return type, the opposite is not OK.
4830bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4831                                         const ObjCObjectPointerType *LHSOPT,
4832                                         const ObjCObjectPointerType *RHSOPT) {
4833  if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
4834    return true;
4835
4836  if (LHSOPT->isObjCBuiltinType()) {
4837    return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4838  }
4839
4840  if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
4841    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4842                                             QualType(RHSOPT,0),
4843                                             false);
4844
4845  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4846  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4847  if (LHS && RHS)  { // We have 2 user-defined types.
4848    if (LHS != RHS) {
4849      if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4850        return false;
4851      if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4852        return true;
4853    }
4854    else
4855      return true;
4856  }
4857  return false;
4858}
4859
4860/// getIntersectionOfProtocols - This routine finds the intersection of set
4861/// of protocols inherited from two distinct objective-c pointer objects.
4862/// It is used to build composite qualifier list of the composite type of
4863/// the conditional expression involving two objective-c pointer objects.
4864static
4865void getIntersectionOfProtocols(ASTContext &Context,
4866                                const ObjCObjectPointerType *LHSOPT,
4867                                const ObjCObjectPointerType *RHSOPT,
4868      llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4869
4870  const ObjCObjectType* LHS = LHSOPT->getObjectType();
4871  const ObjCObjectType* RHS = RHSOPT->getObjectType();
4872  assert(LHS->getInterface() && "LHS must have an interface base");
4873  assert(RHS->getInterface() && "RHS must have an interface base");
4874
4875  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4876  unsigned LHSNumProtocols = LHS->getNumProtocols();
4877  if (LHSNumProtocols > 0)
4878    InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4879  else {
4880    llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4881    Context.CollectInheritedProtocols(LHS->getInterface(),
4882                                      LHSInheritedProtocols);
4883    InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4884                                LHSInheritedProtocols.end());
4885  }
4886
4887  unsigned RHSNumProtocols = RHS->getNumProtocols();
4888  if (RHSNumProtocols > 0) {
4889    ObjCProtocolDecl **RHSProtocols =
4890      const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
4891    for (unsigned i = 0; i < RHSNumProtocols; ++i)
4892      if (InheritedProtocolSet.count(RHSProtocols[i]))
4893        IntersectionOfProtocols.push_back(RHSProtocols[i]);
4894  }
4895  else {
4896    llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
4897    Context.CollectInheritedProtocols(RHS->getInterface(),
4898                                      RHSInheritedProtocols);
4899    for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4900         RHSInheritedProtocols.begin(),
4901         E = RHSInheritedProtocols.end(); I != E; ++I)
4902      if (InheritedProtocolSet.count((*I)))
4903        IntersectionOfProtocols.push_back((*I));
4904  }
4905}
4906
4907/// areCommonBaseCompatible - Returns common base class of the two classes if
4908/// one found. Note that this is O'2 algorithm. But it will be called as the
4909/// last type comparison in a ?-exp of ObjC pointer types before a
4910/// warning is issued. So, its invokation is extremely rare.
4911QualType ASTContext::areCommonBaseCompatible(
4912                                          const ObjCObjectPointerType *Lptr,
4913                                          const ObjCObjectPointerType *Rptr) {
4914  const ObjCObjectType *LHS = Lptr->getObjectType();
4915  const ObjCObjectType *RHS = Rptr->getObjectType();
4916  const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4917  const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4918  if (!LDecl || !RDecl)
4919    return QualType();
4920
4921  while ((LDecl = LDecl->getSuperClass())) {
4922    LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
4923    if (canAssignObjCInterfaces(LHS, RHS)) {
4924      llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4925      getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4926
4927      QualType Result = QualType(LHS, 0);
4928      if (!Protocols.empty())
4929        Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4930      Result = getObjCObjectPointerType(Result);
4931      return Result;
4932    }
4933  }
4934
4935  return QualType();
4936}
4937
4938bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4939                                         const ObjCObjectType *RHS) {
4940  assert(LHS->getInterface() && "LHS is not an interface type");
4941  assert(RHS->getInterface() && "RHS is not an interface type");
4942
4943  // Verify that the base decls are compatible: the RHS must be a subclass of
4944  // the LHS.
4945  if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
4946    return false;
4947
4948  // RHS must have a superset of the protocols in the LHS.  If the LHS is not
4949  // protocol qualified at all, then we are good.
4950  if (LHS->getNumProtocols() == 0)
4951    return true;
4952
4953  // Okay, we know the LHS has protocol qualifiers.  If the RHS doesn't, then it
4954  // isn't a superset.
4955  if (RHS->getNumProtocols() == 0)
4956    return true;  // FIXME: should return false!
4957
4958  for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4959                                     LHSPE = LHS->qual_end();
4960       LHSPI != LHSPE; LHSPI++) {
4961    bool RHSImplementsProtocol = false;
4962
4963    // If the RHS doesn't implement the protocol on the left, the types
4964    // are incompatible.
4965    for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4966                                       RHSPE = RHS->qual_end();
4967         RHSPI != RHSPE; RHSPI++) {
4968      if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
4969        RHSImplementsProtocol = true;
4970        break;
4971      }
4972    }
4973    // FIXME: For better diagnostics, consider passing back the protocol name.
4974    if (!RHSImplementsProtocol)
4975      return false;
4976  }
4977  // The RHS implements all protocols listed on the LHS.
4978  return true;
4979}
4980
4981bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4982  // get the "pointed to" types
4983  const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4984  const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
4985
4986  if (!LHSOPT || !RHSOPT)
4987    return false;
4988
4989  return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4990         canAssignObjCInterfaces(RHSOPT, LHSOPT);
4991}
4992
4993bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
4994  return canAssignObjCInterfaces(
4995                getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
4996                getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
4997}
4998
4999/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
5000/// both shall have the identically qualified version of a compatible type.
5001/// C99 6.2.7p1: Two types have compatible types if their types are the
5002/// same. See 6.7.[2,3,5] for additional rules.
5003bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5004                                    bool CompareUnqualified) {
5005  if (getLangOptions().CPlusPlus)
5006    return hasSameType(LHS, RHS);
5007
5008  return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
5009}
5010
5011bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5012  return !mergeTypes(LHS, RHS, true).isNull();
5013}
5014
5015/// mergeTransparentUnionType - if T is a transparent union type and a member
5016/// of T is compatible with SubType, return the merged type, else return
5017/// QualType()
5018QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5019                                               bool OfBlockPointer,
5020                                               bool Unqualified) {
5021  if (const RecordType *UT = T->getAsUnionType()) {
5022    RecordDecl *UD = UT->getDecl();
5023    if (UD->hasAttr<TransparentUnionAttr>()) {
5024      for (RecordDecl::field_iterator it = UD->field_begin(),
5025           itend = UD->field_end(); it != itend; ++it) {
5026        QualType ET = it->getType().getUnqualifiedType();
5027        QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5028        if (!MT.isNull())
5029          return MT;
5030      }
5031    }
5032  }
5033
5034  return QualType();
5035}
5036
5037/// mergeFunctionArgumentTypes - merge two types which appear as function
5038/// argument types
5039QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5040                                                bool OfBlockPointer,
5041                                                bool Unqualified) {
5042  // GNU extension: two types are compatible if they appear as a function
5043  // argument, one of the types is a transparent union type and the other
5044  // type is compatible with a union member
5045  QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5046                                              Unqualified);
5047  if (!lmerge.isNull())
5048    return lmerge;
5049
5050  QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5051                                              Unqualified);
5052  if (!rmerge.isNull())
5053    return rmerge;
5054
5055  return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5056}
5057
5058QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
5059                                        bool OfBlockPointer,
5060                                        bool Unqualified) {
5061  const FunctionType *lbase = lhs->getAs<FunctionType>();
5062  const FunctionType *rbase = rhs->getAs<FunctionType>();
5063  const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5064  const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
5065  bool allLTypes = true;
5066  bool allRTypes = true;
5067
5068  // Check return type
5069  QualType retType;
5070  if (OfBlockPointer) {
5071    QualType RHS = rbase->getResultType();
5072    QualType LHS = lbase->getResultType();
5073    bool UnqualifiedResult = Unqualified;
5074    if (!UnqualifiedResult)
5075      UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
5076    retType = mergeTypes(RHS, LHS, true, UnqualifiedResult);
5077  }
5078  else
5079    retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5080                         Unqualified);
5081  if (retType.isNull()) return QualType();
5082
5083  if (Unqualified)
5084    retType = retType.getUnqualifiedType();
5085
5086  CanQualType LRetType = getCanonicalType(lbase->getResultType());
5087  CanQualType RRetType = getCanonicalType(rbase->getResultType());
5088  if (Unqualified) {
5089    LRetType = LRetType.getUnqualifiedType();
5090    RRetType = RRetType.getUnqualifiedType();
5091  }
5092
5093  if (getCanonicalType(retType) != LRetType)
5094    allLTypes = false;
5095  if (getCanonicalType(retType) != RRetType)
5096    allRTypes = false;
5097
5098  // FIXME: double check this
5099  // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5100  //                           rbase->getRegParmAttr() != 0 &&
5101  //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
5102  FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5103  FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
5104
5105  // Compatible functions must have compatible calling conventions
5106  if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
5107    return QualType();
5108
5109  // Regparm is part of the calling convention.
5110  if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5111    return QualType();
5112
5113  // It's noreturn if either type is.
5114  // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5115  bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5116  if (NoReturn != lbaseInfo.getNoReturn())
5117    allLTypes = false;
5118  if (NoReturn != rbaseInfo.getNoReturn())
5119    allRTypes = false;
5120
5121  FunctionType::ExtInfo einfo(NoReturn,
5122                              lbaseInfo.getRegParm(),
5123                              lbaseInfo.getCC());
5124
5125  if (lproto && rproto) { // two C99 style function prototypes
5126    assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5127           "C++ shouldn't be here");
5128    unsigned lproto_nargs = lproto->getNumArgs();
5129    unsigned rproto_nargs = rproto->getNumArgs();
5130
5131    // Compatible functions must have the same number of arguments
5132    if (lproto_nargs != rproto_nargs)
5133      return QualType();
5134
5135    // Variadic and non-variadic functions aren't compatible
5136    if (lproto->isVariadic() != rproto->isVariadic())
5137      return QualType();
5138
5139    if (lproto->getTypeQuals() != rproto->getTypeQuals())
5140      return QualType();
5141
5142    // Check argument compatibility
5143    llvm::SmallVector<QualType, 10> types;
5144    for (unsigned i = 0; i < lproto_nargs; i++) {
5145      QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5146      QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
5147      QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5148                                                    OfBlockPointer,
5149                                                    Unqualified);
5150      if (argtype.isNull()) return QualType();
5151
5152      if (Unqualified)
5153        argtype = argtype.getUnqualifiedType();
5154
5155      types.push_back(argtype);
5156      if (Unqualified) {
5157        largtype = largtype.getUnqualifiedType();
5158        rargtype = rargtype.getUnqualifiedType();
5159      }
5160
5161      if (getCanonicalType(argtype) != getCanonicalType(largtype))
5162        allLTypes = false;
5163      if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5164        allRTypes = false;
5165    }
5166    if (allLTypes) return lhs;
5167    if (allRTypes) return rhs;
5168
5169    FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5170    EPI.ExtInfo = einfo;
5171    return getFunctionType(retType, types.begin(), types.size(), EPI);
5172  }
5173
5174  if (lproto) allRTypes = false;
5175  if (rproto) allLTypes = false;
5176
5177  const FunctionProtoType *proto = lproto ? lproto : rproto;
5178  if (proto) {
5179    assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
5180    if (proto->isVariadic()) return QualType();
5181    // Check that the types are compatible with the types that
5182    // would result from default argument promotions (C99 6.7.5.3p15).
5183    // The only types actually affected are promotable integer
5184    // types and floats, which would be passed as a different
5185    // type depending on whether the prototype is visible.
5186    unsigned proto_nargs = proto->getNumArgs();
5187    for (unsigned i = 0; i < proto_nargs; ++i) {
5188      QualType argTy = proto->getArgType(i);
5189
5190      // Look at the promotion type of enum types, since that is the type used
5191      // to pass enum values.
5192      if (const EnumType *Enum = argTy->getAs<EnumType>())
5193        argTy = Enum->getDecl()->getPromotionType();
5194
5195      if (argTy->isPromotableIntegerType() ||
5196          getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5197        return QualType();
5198    }
5199
5200    if (allLTypes) return lhs;
5201    if (allRTypes) return rhs;
5202
5203    FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5204    EPI.ExtInfo = einfo;
5205    return getFunctionType(retType, proto->arg_type_begin(),
5206                           proto->getNumArgs(), EPI);
5207  }
5208
5209  if (allLTypes) return lhs;
5210  if (allRTypes) return rhs;
5211  return getFunctionNoProtoType(retType, einfo);
5212}
5213
5214QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
5215                                bool OfBlockPointer,
5216                                bool Unqualified) {
5217  // C++ [expr]: If an expression initially has the type "reference to T", the
5218  // type is adjusted to "T" prior to any further analysis, the expression
5219  // designates the object or function denoted by the reference, and the
5220  // expression is an lvalue unless the reference is an rvalue reference and
5221  // the expression is a function call (possibly inside parentheses).
5222  assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5223  assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
5224
5225  if (Unqualified) {
5226    LHS = LHS.getUnqualifiedType();
5227    RHS = RHS.getUnqualifiedType();
5228  }
5229
5230  QualType LHSCan = getCanonicalType(LHS),
5231           RHSCan = getCanonicalType(RHS);
5232
5233  // If two types are identical, they are compatible.
5234  if (LHSCan == RHSCan)
5235    return LHS;
5236
5237  // If the qualifiers are different, the types aren't compatible... mostly.
5238  Qualifiers LQuals = LHSCan.getLocalQualifiers();
5239  Qualifiers RQuals = RHSCan.getLocalQualifiers();
5240  if (LQuals != RQuals) {
5241    // If any of these qualifiers are different, we have a type
5242    // mismatch.
5243    if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5244        LQuals.getAddressSpace() != RQuals.getAddressSpace())
5245      return QualType();
5246
5247    // Exactly one GC qualifier difference is allowed: __strong is
5248    // okay if the other type has no GC qualifier but is an Objective
5249    // C object pointer (i.e. implicitly strong by default).  We fix
5250    // this by pretending that the unqualified type was actually
5251    // qualified __strong.
5252    Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5253    Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5254    assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5255
5256    if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5257      return QualType();
5258
5259    if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5260      return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5261    }
5262    if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5263      return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5264    }
5265    return QualType();
5266  }
5267
5268  // Okay, qualifiers are equal.
5269
5270  Type::TypeClass LHSClass = LHSCan->getTypeClass();
5271  Type::TypeClass RHSClass = RHSCan->getTypeClass();
5272
5273  // We want to consider the two function types to be the same for these
5274  // comparisons, just force one to the other.
5275  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5276  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
5277
5278  // Same as above for arrays
5279  if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5280    LHSClass = Type::ConstantArray;
5281  if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5282    RHSClass = Type::ConstantArray;
5283
5284  // ObjCInterfaces are just specialized ObjCObjects.
5285  if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5286  if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5287
5288  // Canonicalize ExtVector -> Vector.
5289  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5290  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
5291
5292  // If the canonical type classes don't match.
5293  if (LHSClass != RHSClass) {
5294    // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
5295    // a signed integer type, or an unsigned integer type.
5296    // Compatibility is based on the underlying type, not the promotion
5297    // type.
5298    if (const EnumType* ETy = LHS->getAs<EnumType>()) {
5299      if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5300        return RHS;
5301    }
5302    if (const EnumType* ETy = RHS->getAs<EnumType>()) {
5303      if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5304        return LHS;
5305    }
5306
5307    return QualType();
5308  }
5309
5310  // The canonical type classes match.
5311  switch (LHSClass) {
5312#define TYPE(Class, Base)
5313#define ABSTRACT_TYPE(Class, Base)
5314#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
5315#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5316#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5317#include "clang/AST/TypeNodes.def"
5318    assert(false && "Non-canonical and dependent types shouldn't get here");
5319    return QualType();
5320
5321  case Type::LValueReference:
5322  case Type::RValueReference:
5323  case Type::MemberPointer:
5324    assert(false && "C++ should never be in mergeTypes");
5325    return QualType();
5326
5327  case Type::ObjCInterface:
5328  case Type::IncompleteArray:
5329  case Type::VariableArray:
5330  case Type::FunctionProto:
5331  case Type::ExtVector:
5332    assert(false && "Types are eliminated above");
5333    return QualType();
5334
5335  case Type::Pointer:
5336  {
5337    // Merge two pointer types, while trying to preserve typedef info
5338    QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5339    QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
5340    if (Unqualified) {
5341      LHSPointee = LHSPointee.getUnqualifiedType();
5342      RHSPointee = RHSPointee.getUnqualifiedType();
5343    }
5344    QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5345                                     Unqualified);
5346    if (ResultType.isNull()) return QualType();
5347    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5348      return LHS;
5349    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5350      return RHS;
5351    return getPointerType(ResultType);
5352  }
5353  case Type::BlockPointer:
5354  {
5355    // Merge two block pointer types, while trying to preserve typedef info
5356    QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5357    QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
5358    if (Unqualified) {
5359      LHSPointee = LHSPointee.getUnqualifiedType();
5360      RHSPointee = RHSPointee.getUnqualifiedType();
5361    }
5362    QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5363                                     Unqualified);
5364    if (ResultType.isNull()) return QualType();
5365    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5366      return LHS;
5367    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5368      return RHS;
5369    return getBlockPointerType(ResultType);
5370  }
5371  case Type::ConstantArray:
5372  {
5373    const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5374    const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5375    if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5376      return QualType();
5377
5378    QualType LHSElem = getAsArrayType(LHS)->getElementType();
5379    QualType RHSElem = getAsArrayType(RHS)->getElementType();
5380    if (Unqualified) {
5381      LHSElem = LHSElem.getUnqualifiedType();
5382      RHSElem = RHSElem.getUnqualifiedType();
5383    }
5384
5385    QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
5386    if (ResultType.isNull()) return QualType();
5387    if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5388      return LHS;
5389    if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5390      return RHS;
5391    if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5392                                          ArrayType::ArraySizeModifier(), 0);
5393    if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5394                                          ArrayType::ArraySizeModifier(), 0);
5395    const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5396    const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
5397    if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5398      return LHS;
5399    if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5400      return RHS;
5401    if (LVAT) {
5402      // FIXME: This isn't correct! But tricky to implement because
5403      // the array's size has to be the size of LHS, but the type
5404      // has to be different.
5405      return LHS;
5406    }
5407    if (RVAT) {
5408      // FIXME: This isn't correct! But tricky to implement because
5409      // the array's size has to be the size of RHS, but the type
5410      // has to be different.
5411      return RHS;
5412    }
5413    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5414    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
5415    return getIncompleteArrayType(ResultType,
5416                                  ArrayType::ArraySizeModifier(), 0);
5417  }
5418  case Type::FunctionNoProto:
5419    return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
5420  case Type::Record:
5421  case Type::Enum:
5422    return QualType();
5423  case Type::Builtin:
5424    // Only exactly equal builtin types are compatible, which is tested above.
5425    return QualType();
5426  case Type::Complex:
5427    // Distinct complex types are incompatible.
5428    return QualType();
5429  case Type::Vector:
5430    // FIXME: The merged type should be an ExtVector!
5431    if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5432                             RHSCan->getAs<VectorType>()))
5433      return LHS;
5434    return QualType();
5435  case Type::ObjCObject: {
5436    // Check if the types are assignment compatible.
5437    // FIXME: This should be type compatibility, e.g. whether
5438    // "LHS x; RHS x;" at global scope is legal.
5439    const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5440    const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5441    if (canAssignObjCInterfaces(LHSIface, RHSIface))
5442      return LHS;
5443
5444    return QualType();
5445  }
5446  case Type::ObjCObjectPointer: {
5447    if (OfBlockPointer) {
5448      if (canAssignObjCInterfacesInBlockPointer(
5449                                          LHS->getAs<ObjCObjectPointerType>(),
5450                                          RHS->getAs<ObjCObjectPointerType>()))
5451      return LHS;
5452      return QualType();
5453    }
5454    if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5455                                RHS->getAs<ObjCObjectPointerType>()))
5456      return LHS;
5457
5458    return QualType();
5459    }
5460  }
5461
5462  return QualType();
5463}
5464
5465/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5466/// 'RHS' attributes and returns the merged version; including for function
5467/// return types.
5468QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5469  QualType LHSCan = getCanonicalType(LHS),
5470  RHSCan = getCanonicalType(RHS);
5471  // If two types are identical, they are compatible.
5472  if (LHSCan == RHSCan)
5473    return LHS;
5474  if (RHSCan->isFunctionType()) {
5475    if (!LHSCan->isFunctionType())
5476      return QualType();
5477    QualType OldReturnType =
5478      cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5479    QualType NewReturnType =
5480      cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5481    QualType ResReturnType =
5482      mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5483    if (ResReturnType.isNull())
5484      return QualType();
5485    if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5486      // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5487      // In either case, use OldReturnType to build the new function type.
5488      const FunctionType *F = LHS->getAs<FunctionType>();
5489      if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
5490        FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5491        EPI.ExtInfo = getFunctionExtInfo(LHS);
5492        QualType ResultType
5493          = getFunctionType(OldReturnType, FPT->arg_type_begin(),
5494                            FPT->getNumArgs(), EPI);
5495        return ResultType;
5496      }
5497    }
5498    return QualType();
5499  }
5500
5501  // If the qualifiers are different, the types can still be merged.
5502  Qualifiers LQuals = LHSCan.getLocalQualifiers();
5503  Qualifiers RQuals = RHSCan.getLocalQualifiers();
5504  if (LQuals != RQuals) {
5505    // If any of these qualifiers are different, we have a type mismatch.
5506    if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5507        LQuals.getAddressSpace() != RQuals.getAddressSpace())
5508      return QualType();
5509
5510    // Exactly one GC qualifier difference is allowed: __strong is
5511    // okay if the other type has no GC qualifier but is an Objective
5512    // C object pointer (i.e. implicitly strong by default).  We fix
5513    // this by pretending that the unqualified type was actually
5514    // qualified __strong.
5515    Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5516    Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5517    assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5518
5519    if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5520      return QualType();
5521
5522    if (GC_L == Qualifiers::Strong)
5523      return LHS;
5524    if (GC_R == Qualifiers::Strong)
5525      return RHS;
5526    return QualType();
5527  }
5528
5529  if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5530    QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5531    QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5532    QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5533    if (ResQT == LHSBaseQT)
5534      return LHS;
5535    if (ResQT == RHSBaseQT)
5536      return RHS;
5537  }
5538  return QualType();
5539}
5540
5541//===----------------------------------------------------------------------===//
5542//                         Integer Predicates
5543//===----------------------------------------------------------------------===//
5544
5545unsigned ASTContext::getIntWidth(QualType T) const {
5546  if (const EnumType *ET = dyn_cast<EnumType>(T))
5547    T = ET->getDecl()->getIntegerType();
5548  if (T->isBooleanType())
5549    return 1;
5550  // For builtin types, just use the standard type sizing method
5551  return (unsigned)getTypeSize(T);
5552}
5553
5554QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
5555  assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
5556
5557  // Turn <4 x signed int> -> <4 x unsigned int>
5558  if (const VectorType *VTy = T->getAs<VectorType>())
5559    return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
5560                         VTy->getNumElements(), VTy->getVectorKind());
5561
5562  // For enums, we return the unsigned version of the base type.
5563  if (const EnumType *ETy = T->getAs<EnumType>())
5564    T = ETy->getDecl()->getIntegerType();
5565
5566  const BuiltinType *BTy = T->getAs<BuiltinType>();
5567  assert(BTy && "Unexpected signed integer type");
5568  switch (BTy->getKind()) {
5569  case BuiltinType::Char_S:
5570  case BuiltinType::SChar:
5571    return UnsignedCharTy;
5572  case BuiltinType::Short:
5573    return UnsignedShortTy;
5574  case BuiltinType::Int:
5575    return UnsignedIntTy;
5576  case BuiltinType::Long:
5577    return UnsignedLongTy;
5578  case BuiltinType::LongLong:
5579    return UnsignedLongLongTy;
5580  case BuiltinType::Int128:
5581    return UnsignedInt128Ty;
5582  default:
5583    assert(0 && "Unexpected signed integer type");
5584    return QualType();
5585  }
5586}
5587
5588ASTMutationListener::~ASTMutationListener() { }
5589
5590
5591//===----------------------------------------------------------------------===//
5592//                          Builtin Type Computation
5593//===----------------------------------------------------------------------===//
5594
5595/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
5596/// pointer over the consumed characters.  This returns the resultant type.  If
5597/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5598/// types.  This allows "v2i*" to be parsed as a pointer to a v2i instead of
5599/// a vector of "i*".
5600///
5601/// RequiresICE is filled in on return to indicate whether the value is required
5602/// to be an Integer Constant Expression.
5603static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
5604                                  ASTContext::GetBuiltinTypeError &Error,
5605                                  bool &RequiresICE,
5606                                  bool AllowTypeModifiers) {
5607  // Modifiers.
5608  int HowLong = 0;
5609  bool Signed = false, Unsigned = false;
5610  RequiresICE = false;
5611
5612  // Read the prefixed modifiers first.
5613  bool Done = false;
5614  while (!Done) {
5615    switch (*Str++) {
5616    default: Done = true; --Str; break;
5617    case 'I':
5618      RequiresICE = true;
5619      break;
5620    case 'S':
5621      assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5622      assert(!Signed && "Can't use 'S' modifier multiple times!");
5623      Signed = true;
5624      break;
5625    case 'U':
5626      assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5627      assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5628      Unsigned = true;
5629      break;
5630    case 'L':
5631      assert(HowLong <= 2 && "Can't have LLLL modifier");
5632      ++HowLong;
5633      break;
5634    }
5635  }
5636
5637  QualType Type;
5638
5639  // Read the base type.
5640  switch (*Str++) {
5641  default: assert(0 && "Unknown builtin type letter!");
5642  case 'v':
5643    assert(HowLong == 0 && !Signed && !Unsigned &&
5644           "Bad modifiers used with 'v'!");
5645    Type = Context.VoidTy;
5646    break;
5647  case 'f':
5648    assert(HowLong == 0 && !Signed && !Unsigned &&
5649           "Bad modifiers used with 'f'!");
5650    Type = Context.FloatTy;
5651    break;
5652  case 'd':
5653    assert(HowLong < 2 && !Signed && !Unsigned &&
5654           "Bad modifiers used with 'd'!");
5655    if (HowLong)
5656      Type = Context.LongDoubleTy;
5657    else
5658      Type = Context.DoubleTy;
5659    break;
5660  case 's':
5661    assert(HowLong == 0 && "Bad modifiers used with 's'!");
5662    if (Unsigned)
5663      Type = Context.UnsignedShortTy;
5664    else
5665      Type = Context.ShortTy;
5666    break;
5667  case 'i':
5668    if (HowLong == 3)
5669      Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5670    else if (HowLong == 2)
5671      Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5672    else if (HowLong == 1)
5673      Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5674    else
5675      Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5676    break;
5677  case 'c':
5678    assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5679    if (Signed)
5680      Type = Context.SignedCharTy;
5681    else if (Unsigned)
5682      Type = Context.UnsignedCharTy;
5683    else
5684      Type = Context.CharTy;
5685    break;
5686  case 'b': // boolean
5687    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5688    Type = Context.BoolTy;
5689    break;
5690  case 'z':  // size_t.
5691    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5692    Type = Context.getSizeType();
5693    break;
5694  case 'F':
5695    Type = Context.getCFConstantStringType();
5696    break;
5697  case 'G':
5698    Type = Context.getObjCIdType();
5699    break;
5700  case 'H':
5701    Type = Context.getObjCSelType();
5702    break;
5703  case 'a':
5704    Type = Context.getBuiltinVaListType();
5705    assert(!Type.isNull() && "builtin va list type not initialized!");
5706    break;
5707  case 'A':
5708    // This is a "reference" to a va_list; however, what exactly
5709    // this means depends on how va_list is defined. There are two
5710    // different kinds of va_list: ones passed by value, and ones
5711    // passed by reference.  An example of a by-value va_list is
5712    // x86, where va_list is a char*. An example of by-ref va_list
5713    // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5714    // we want this argument to be a char*&; for x86-64, we want
5715    // it to be a __va_list_tag*.
5716    Type = Context.getBuiltinVaListType();
5717    assert(!Type.isNull() && "builtin va list type not initialized!");
5718    if (Type->isArrayType())
5719      Type = Context.getArrayDecayedType(Type);
5720    else
5721      Type = Context.getLValueReferenceType(Type);
5722    break;
5723  case 'V': {
5724    char *End;
5725    unsigned NumElements = strtoul(Str, &End, 10);
5726    assert(End != Str && "Missing vector size");
5727    Str = End;
5728
5729    QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
5730                                             RequiresICE, false);
5731    assert(!RequiresICE && "Can't require vector ICE");
5732
5733    // TODO: No way to make AltiVec vectors in builtins yet.
5734    Type = Context.getVectorType(ElementType, NumElements,
5735                                 VectorType::GenericVector);
5736    break;
5737  }
5738  case 'X': {
5739    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
5740                                             false);
5741    assert(!RequiresICE && "Can't require complex ICE");
5742    Type = Context.getComplexType(ElementType);
5743    break;
5744  }
5745  case 'P':
5746    Type = Context.getFILEType();
5747    if (Type.isNull()) {
5748      Error = ASTContext::GE_Missing_stdio;
5749      return QualType();
5750    }
5751    break;
5752  case 'J':
5753    if (Signed)
5754      Type = Context.getsigjmp_bufType();
5755    else
5756      Type = Context.getjmp_bufType();
5757
5758    if (Type.isNull()) {
5759      Error = ASTContext::GE_Missing_setjmp;
5760      return QualType();
5761    }
5762    break;
5763  }
5764
5765  // If there are modifiers and if we're allowed to parse them, go for it.
5766  Done = !AllowTypeModifiers;
5767  while (!Done) {
5768    switch (char c = *Str++) {
5769    default: Done = true; --Str; break;
5770    case '*':
5771    case '&': {
5772      // Both pointers and references can have their pointee types
5773      // qualified with an address space.
5774      char *End;
5775      unsigned AddrSpace = strtoul(Str, &End, 10);
5776      if (End != Str && AddrSpace != 0) {
5777        Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5778        Str = End;
5779      }
5780      if (c == '*')
5781        Type = Context.getPointerType(Type);
5782      else
5783        Type = Context.getLValueReferenceType(Type);
5784      break;
5785    }
5786    // FIXME: There's no way to have a built-in with an rvalue ref arg.
5787    case 'C':
5788      Type = Type.withConst();
5789      break;
5790    case 'D':
5791      Type = Context.getVolatileType(Type);
5792      break;
5793    }
5794  }
5795
5796  assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
5797         "Integer constant 'I' type must be an integer");
5798
5799  return Type;
5800}
5801
5802/// GetBuiltinType - Return the type for the specified builtin.
5803QualType ASTContext::GetBuiltinType(unsigned Id,
5804                                    GetBuiltinTypeError &Error,
5805                                    unsigned *IntegerConstantArgs) const {
5806  const char *TypeStr = BuiltinInfo.GetTypeString(Id);
5807
5808  llvm::SmallVector<QualType, 8> ArgTypes;
5809
5810  bool RequiresICE = false;
5811  Error = GE_None;
5812  QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
5813                                       RequiresICE, true);
5814  if (Error != GE_None)
5815    return QualType();
5816
5817  assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
5818
5819  while (TypeStr[0] && TypeStr[0] != '.') {
5820    QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
5821    if (Error != GE_None)
5822      return QualType();
5823
5824    // If this argument is required to be an IntegerConstantExpression and the
5825    // caller cares, fill in the bitmask we return.
5826    if (RequiresICE && IntegerConstantArgs)
5827      *IntegerConstantArgs |= 1 << ArgTypes.size();
5828
5829    // Do array -> pointer decay.  The builtin should use the decayed type.
5830    if (Ty->isArrayType())
5831      Ty = getArrayDecayedType(Ty);
5832
5833    ArgTypes.push_back(Ty);
5834  }
5835
5836  assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5837         "'.' should only occur at end of builtin type list!");
5838
5839  FunctionType::ExtInfo EI;
5840  if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
5841
5842  bool Variadic = (TypeStr[0] == '.');
5843
5844  // We really shouldn't be making a no-proto type here, especially in C++.
5845  if (ArgTypes.empty() && Variadic)
5846    return getFunctionNoProtoType(ResType, EI);
5847
5848  FunctionProtoType::ExtProtoInfo EPI;
5849  EPI.ExtInfo = EI;
5850  EPI.Variadic = Variadic;
5851
5852  return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
5853}
5854
5855GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5856  GVALinkage External = GVA_StrongExternal;
5857
5858  Linkage L = FD->getLinkage();
5859  switch (L) {
5860  case NoLinkage:
5861  case InternalLinkage:
5862  case UniqueExternalLinkage:
5863    return GVA_Internal;
5864
5865  case ExternalLinkage:
5866    switch (FD->getTemplateSpecializationKind()) {
5867    case TSK_Undeclared:
5868    case TSK_ExplicitSpecialization:
5869      External = GVA_StrongExternal;
5870      break;
5871
5872    case TSK_ExplicitInstantiationDefinition:
5873      return GVA_ExplicitTemplateInstantiation;
5874
5875    case TSK_ExplicitInstantiationDeclaration:
5876    case TSK_ImplicitInstantiation:
5877      External = GVA_TemplateInstantiation;
5878      break;
5879    }
5880  }
5881
5882  if (!FD->isInlined())
5883    return External;
5884
5885  if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5886    // GNU or C99 inline semantics. Determine whether this symbol should be
5887    // externally visible.
5888    if (FD->isInlineDefinitionExternallyVisible())
5889      return External;
5890
5891    // C99 inline semantics, where the symbol is not externally visible.
5892    return GVA_C99Inline;
5893  }
5894
5895  // C++0x [temp.explicit]p9:
5896  //   [ Note: The intent is that an inline function that is the subject of
5897  //   an explicit instantiation declaration will still be implicitly
5898  //   instantiated when used so that the body can be considered for
5899  //   inlining, but that no out-of-line copy of the inline function would be
5900  //   generated in the translation unit. -- end note ]
5901  if (FD->getTemplateSpecializationKind()
5902                                       == TSK_ExplicitInstantiationDeclaration)
5903    return GVA_C99Inline;
5904
5905  return GVA_CXXInline;
5906}
5907
5908GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5909  // If this is a static data member, compute the kind of template
5910  // specialization. Otherwise, this variable is not part of a
5911  // template.
5912  TemplateSpecializationKind TSK = TSK_Undeclared;
5913  if (VD->isStaticDataMember())
5914    TSK = VD->getTemplateSpecializationKind();
5915
5916  Linkage L = VD->getLinkage();
5917  if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5918      VD->getType()->getLinkage() == UniqueExternalLinkage)
5919    L = UniqueExternalLinkage;
5920
5921  switch (L) {
5922  case NoLinkage:
5923  case InternalLinkage:
5924  case UniqueExternalLinkage:
5925    return GVA_Internal;
5926
5927  case ExternalLinkage:
5928    switch (TSK) {
5929    case TSK_Undeclared:
5930    case TSK_ExplicitSpecialization:
5931      return GVA_StrongExternal;
5932
5933    case TSK_ExplicitInstantiationDeclaration:
5934      llvm_unreachable("Variable should not be instantiated");
5935      // Fall through to treat this like any other instantiation.
5936
5937    case TSK_ExplicitInstantiationDefinition:
5938      return GVA_ExplicitTemplateInstantiation;
5939
5940    case TSK_ImplicitInstantiation:
5941      return GVA_TemplateInstantiation;
5942    }
5943  }
5944
5945  return GVA_StrongExternal;
5946}
5947
5948bool ASTContext::DeclMustBeEmitted(const Decl *D) {
5949  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5950    if (!VD->isFileVarDecl())
5951      return false;
5952  } else if (!isa<FunctionDecl>(D))
5953    return false;
5954
5955  // Weak references don't produce any output by themselves.
5956  if (D->hasAttr<WeakRefAttr>())
5957    return false;
5958
5959  // Aliases and used decls are required.
5960  if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5961    return true;
5962
5963  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5964    // Forward declarations aren't required.
5965    if (!FD->isThisDeclarationADefinition())
5966      return false;
5967
5968    // Constructors and destructors are required.
5969    if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5970      return true;
5971
5972    // The key function for a class is required.
5973    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5974      const CXXRecordDecl *RD = MD->getParent();
5975      if (MD->isOutOfLine() && RD->isDynamicClass()) {
5976        const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5977        if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5978          return true;
5979      }
5980    }
5981
5982    GVALinkage Linkage = GetGVALinkageForFunction(FD);
5983
5984    // static, static inline, always_inline, and extern inline functions can
5985    // always be deferred.  Normal inline functions can be deferred in C99/C++.
5986    // Implicit template instantiations can also be deferred in C++.
5987    if (Linkage == GVA_Internal  || Linkage == GVA_C99Inline ||
5988        Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5989      return false;
5990    return true;
5991  }
5992
5993  const VarDecl *VD = cast<VarDecl>(D);
5994  assert(VD->isFileVarDecl() && "Expected file scoped var");
5995
5996  if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
5997    return false;
5998
5999  // Structs that have non-trivial constructors or destructors are required.
6000
6001  // FIXME: Handle references.
6002  if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6003    if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
6004      if (RD->hasDefinition() &&
6005          (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
6006        return true;
6007    }
6008  }
6009
6010  GVALinkage L = GetGVALinkageForVariable(VD);
6011  if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6012    if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6013      return false;
6014  }
6015
6016  return true;
6017}
6018
6019CallingConv ASTContext::getDefaultMethodCallConv() {
6020  // Pass through to the C++ ABI object
6021  return ABI->getDefaultMethodCallConv();
6022}
6023
6024bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
6025  // Pass through to the C++ ABI object
6026  return ABI->isNearlyEmpty(RD);
6027}
6028
6029MangleContext *ASTContext::createMangleContext() {
6030  switch (Target.getCXXABI()) {
6031  case CXXABI_ARM:
6032  case CXXABI_Itanium:
6033    return createItaniumMangleContext(*this, getDiagnostics());
6034  case CXXABI_Microsoft:
6035    return createMicrosoftMangleContext(*this, getDiagnostics());
6036  }
6037  assert(0 && "Unsupported ABI");
6038  return 0;
6039}
6040
6041CXXABI::~CXXABI() {}
6042