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