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