blob: f5c4ffac92dc325323631f38f1b041e3eff42118 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCallea1471e2010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +000033#include "llvm/Support/Capacity.h"
Charles Davis071cc7d2010-08-16 03:33:14 +000034#include "CXXABI.h"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000035#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000036
Reid Spencer5f016e22007-07-11 17:01:13 +000037using namespace clang;
38
Douglas Gregor18274032010-07-03 00:47:00 +000039unsigned ASTContext::NumImplicitDefaultConstructors;
40unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000041unsigned ASTContext::NumImplicitCopyConstructors;
42unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000043unsigned ASTContext::NumImplicitMoveConstructors;
44unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000045unsigned ASTContext::NumImplicitCopyAssignmentOperators;
46unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000047unsigned ASTContext::NumImplicitMoveAssignmentOperators;
48unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000049unsigned ASTContext::NumImplicitDestructors;
50unsigned ASTContext::NumImplicitDestructorsDeclared;
51
Reid Spencer5f016e22007-07-11 17:01:13 +000052enum FloatingRank {
53 FloatRank, DoubleRank, LongDoubleRank
54};
55
Douglas Gregor3e1274f2010-06-16 21:09:37 +000056void
57ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
58 TemplateTemplateParmDecl *Parm) {
59 ID.AddInteger(Parm->getDepth());
60 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +000061 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000062
63 TemplateParameterList *Params = Parm->getTemplateParameters();
64 ID.AddInteger(Params->size());
65 for (TemplateParameterList::const_iterator P = Params->begin(),
66 PEnd = Params->end();
67 P != PEnd; ++P) {
68 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
69 ID.AddInteger(0);
70 ID.AddBoolean(TTP->isParameterPack());
71 continue;
72 }
73
74 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
75 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +000076 ID.AddBoolean(NTTP->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000077 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +000078 if (NTTP->isExpandedParameterPack()) {
79 ID.AddBoolean(true);
80 ID.AddInteger(NTTP->getNumExpansionTypes());
81 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
82 ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
83 } else
84 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +000085 continue;
86 }
87
88 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
89 ID.AddInteger(2);
90 Profile(ID, TTP);
91 }
92}
93
94TemplateTemplateParmDecl *
95ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +000096 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +000097 // Check if we already have a canonical template template parameter.
98 llvm::FoldingSetNodeID ID;
99 CanonicalTemplateTemplateParm::Profile(ID, TTP);
100 void *InsertPos = 0;
101 CanonicalTemplateTemplateParm *Canonical
102 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
103 if (Canonical)
104 return Canonical->getParam();
105
106 // Build a canonical template parameter list.
107 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000108 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000109 CanonParams.reserve(Params->size());
110 for (TemplateParameterList::const_iterator P = Params->begin(),
111 PEnd = Params->end();
112 P != PEnd; ++P) {
113 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
114 CanonParams.push_back(
115 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000116 SourceLocation(),
117 SourceLocation(),
118 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000119 TTP->getIndex(), 0, false,
120 TTP->isParameterPack()));
121 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000122 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
123 QualType T = getCanonicalType(NTTP->getType());
124 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
125 NonTypeTemplateParmDecl *Param;
126 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000127 SmallVector<QualType, 2> ExpandedTypes;
128 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000129 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
130 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
131 ExpandedTInfos.push_back(
132 getTrivialTypeSourceInfo(ExpandedTypes.back()));
133 }
134
135 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000136 SourceLocation(),
137 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000138 NTTP->getDepth(),
139 NTTP->getPosition(), 0,
140 T,
141 TInfo,
142 ExpandedTypes.data(),
143 ExpandedTypes.size(),
144 ExpandedTInfos.data());
145 } else {
146 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000147 SourceLocation(),
148 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000149 NTTP->getDepth(),
150 NTTP->getPosition(), 0,
151 T,
152 NTTP->isParameterPack(),
153 TInfo);
154 }
155 CanonParams.push_back(Param);
156
157 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000158 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
159 cast<TemplateTemplateParmDecl>(*P)));
160 }
161
162 TemplateTemplateParmDecl *CanonTTP
163 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
164 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000165 TTP->getPosition(),
166 TTP->isParameterPack(),
167 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000168 TemplateParameterList::Create(*this, SourceLocation(),
169 SourceLocation(),
170 CanonParams.data(),
171 CanonParams.size(),
172 SourceLocation()));
173
174 // Get the new insert position for the node we care about.
175 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
176 assert(Canonical == 0 && "Shouldn't be in the map!");
177 (void)Canonical;
178
179 // Create the canonical template template parameter entry.
180 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
181 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
182 return CanonTTP;
183}
184
Charles Davis071cc7d2010-08-16 03:33:14 +0000185CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000186 if (!LangOpts.CPlusPlus) return 0;
187
Charles Davis20cf7172010-08-19 02:18:14 +0000188 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000189 case CXXABI_ARM:
190 return CreateARMCXXABI(*this);
191 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000192 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000193 case CXXABI_Microsoft:
194 return CreateMicrosoftCXXABI(*this);
195 }
John McCallee79a4c2010-08-21 22:46:04 +0000196 return 0;
Charles Davis071cc7d2010-08-16 03:33:14 +0000197}
198
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000199static const LangAS::Map &getAddressSpaceMap(const TargetInfo &T,
200 const LangOptions &LOpts) {
201 if (LOpts.FakeAddressSpaceMap) {
202 // The fake address space map must have a distinct entry for each
203 // language-specific address space.
204 static const unsigned FakeAddrSpaceMap[] = {
205 1, // opencl_global
206 2, // opencl_local
207 3 // opencl_constant
208 };
209 return FakeAddrSpaceMap;
210 } else {
211 return T.getAddressSpaceMap();
212 }
213}
214
Chris Lattner61710852008-10-05 17:34:18 +0000215ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +0000216 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000217 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000218 Builtin::Context &builtins,
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000219 unsigned size_reserve) :
Sebastian Redl8026f6d2011-03-13 17:09:40 +0000220 FunctionProtoTypes(this_()),
John McCallef990012010-06-11 11:07:21 +0000221 TemplateSpecializationTypes(this_()),
222 DependentTemplateSpecializationTypes(this_()),
John McCall14606042011-06-30 08:33:18 +0000223 SubstTemplateTemplateParmPacks(this_()),
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +0000224 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
225 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
John McCallf85e1932011-06-15 23:02:42 +0000226 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0),
227 jmp_bufDecl(0), sigjmp_bufDecl(0), BlockDescriptorType(0),
228 BlockDescriptorExtendedType(0), cudaConfigureCallDecl(0),
John McCallbf1a0282010-06-04 23:28:52 +0000229 NullTypeSourceInfo(QualType()),
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000230 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)),
231 AddrSpaceMap(getAddressSpaceMap(t, LOpts)), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +0000232 Idents(idents), Selectors(sels),
Ted Kremenekac9590e2010-05-10 20:40:08 +0000233 BuiltinInfo(builtins),
234 DeclarationNames(*this),
Argyrios Kyrtzidis9a44b5f2010-10-28 09:29:35 +0000235 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenekf057bf72010-06-18 00:31:04 +0000236 LastSDM(0, 0),
John McCall8178df32011-02-22 22:38:33 +0000237 UniqueBlockByRefTypeID(0) {
David Chisnall0f436562009-08-17 16:35:33 +0000238 ObjCIdRedefinitionType = QualType();
239 ObjCClassRedefinitionType = QualType();
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000240 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000241 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000242 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +0000243 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +0000244}
245
Reid Spencer5f016e22007-07-11 17:01:13 +0000246ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000247 // Release the DenseMaps associated with DeclContext objects.
248 // FIXME: Is this the ideal solution?
249 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000250
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000251 // Call all of the deallocation functions.
252 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
253 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000254
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000255 // Release all of the memory associated with overridden C++ methods.
256 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
257 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
258 OM != OMEnd; ++OM)
259 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +0000260
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000261 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000262 // because they can contain DenseMaps.
263 for (llvm::DenseMap<const ObjCContainerDecl*,
264 const ASTRecordLayout*>::iterator
265 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
266 // Increment in loop to prevent using deallocated memory.
267 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
268 R->Destroy(*this);
269
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000270 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
271 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
272 // Increment in loop to prevent using deallocated memory.
273 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
274 R->Destroy(*this);
275 }
Douglas Gregor63200642010-08-30 16:49:28 +0000276
277 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
278 AEnd = DeclAttrs.end();
279 A != AEnd; ++A)
280 A->second->~AttrVec();
281}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000282
Douglas Gregor00545312010-05-23 18:26:36 +0000283void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
284 Deallocations.push_back(std::make_pair(Callback, Data));
285}
286
Mike Stump1eb44332009-09-09 15:08:12 +0000287void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000288ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
289 ExternalSource.reset(Source.take());
290}
291
Reid Spencer5f016e22007-07-11 17:01:13 +0000292void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000293 llvm::errs() << "\n*** AST Context Stats:\n";
294 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000295
Douglas Gregordbe833d2009-05-26 14:40:08 +0000296 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000297#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000298#define ABSTRACT_TYPE(Name, Parent)
299#include "clang/AST/TypeNodes.def"
300 0 // Extra
301 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000302
Reid Spencer5f016e22007-07-11 17:01:13 +0000303 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
304 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000305 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000306 }
307
Douglas Gregordbe833d2009-05-26 14:40:08 +0000308 unsigned Idx = 0;
309 unsigned TotalBytes = 0;
310#define TYPE(Name, Parent) \
311 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000312 llvm::errs() << " " << counts[Idx] << " " << #Name \
313 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000314 TotalBytes += counts[Idx] * sizeof(Name##Type); \
315 ++Idx;
316#define ABSTRACT_TYPE(Name, Parent)
317#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000318
Chandler Carruthcd92a652011-07-04 05:32:14 +0000319 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
320
Douglas Gregor4923aa22010-07-02 20:37:36 +0000321 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000322 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
323 << NumImplicitDefaultConstructors
324 << " implicit default constructors created\n";
325 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
326 << NumImplicitCopyConstructors
327 << " implicit copy constructors created\n";
Sean Huntffe37fd2011-05-25 20:50:04 +0000328 if (getLangOptions().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000329 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
330 << NumImplicitMoveConstructors
331 << " implicit move constructors created\n";
332 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
333 << NumImplicitCopyAssignmentOperators
334 << " implicit copy assignment operators created\n";
Sean Huntffe37fd2011-05-25 20:50:04 +0000335 if (getLangOptions().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000336 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
337 << NumImplicitMoveAssignmentOperators
338 << " implicit move assignment operators created\n";
339 llvm::errs() << NumImplicitDestructorsDeclared << "/"
340 << NumImplicitDestructors
341 << " implicit destructors created\n";
342
Douglas Gregor2cf26342009-04-09 22:27:44 +0000343 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000344 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000345 ExternalSource->PrintStats();
346 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000347
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000348 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000349}
350
351
John McCalle27ec8a2009-10-23 23:03:21 +0000352void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000353 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000354 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000355 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000356}
357
Reid Spencer5f016e22007-07-11 17:01:13 +0000358void ASTContext::InitBuiltinTypes() {
359 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Reid Spencer5f016e22007-07-11 17:01:13 +0000361 // C99 6.2.5p19.
362 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000363
Reid Spencer5f016e22007-07-11 17:01:13 +0000364 // C99 6.2.5p2.
365 InitBuiltinType(BoolTy, BuiltinType::Bool);
366 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000367 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000368 InitBuiltinType(CharTy, BuiltinType::Char_S);
369 else
370 InitBuiltinType(CharTy, BuiltinType::Char_U);
371 // C99 6.2.5p4.
372 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
373 InitBuiltinType(ShortTy, BuiltinType::Short);
374 InitBuiltinType(IntTy, BuiltinType::Int);
375 InitBuiltinType(LongTy, BuiltinType::Long);
376 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000377
Reid Spencer5f016e22007-07-11 17:01:13 +0000378 // C99 6.2.5p6.
379 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
380 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
381 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
382 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
383 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000384
Reid Spencer5f016e22007-07-11 17:01:13 +0000385 // C99 6.2.5p10.
386 InitBuiltinType(FloatTy, BuiltinType::Float);
387 InitBuiltinType(DoubleTy, BuiltinType::Double);
388 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000389
Chris Lattner2df9ced2009-04-30 02:43:43 +0000390 // GNU extension, 128-bit integers.
391 InitBuiltinType(Int128Ty, BuiltinType::Int128);
392 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
393
Chris Lattner3f59c972010-12-25 23:25:43 +0000394 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedmand3d77cd2011-04-30 19:24:24 +0000395 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattner3f59c972010-12-25 23:25:43 +0000396 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
397 else // -fshort-wchar makes wchar_t be unsigned.
398 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
399 } else // C99
Chris Lattner3a250322009-02-26 23:43:47 +0000400 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000401
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000402 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
403 InitBuiltinType(Char16Ty, BuiltinType::Char16);
404 else // C99
405 Char16Ty = getFromTargetType(Target.getChar16Type());
406
407 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
408 InitBuiltinType(Char32Ty, BuiltinType::Char32);
409 else // C99
410 Char32Ty = getFromTargetType(Target.getChar32Type());
411
Douglas Gregor898574e2008-12-05 23:32:09 +0000412 // Placeholder type for type-dependent expressions whose type is
413 // completely unknown. No code should ever check a type against
414 // DependentTy and users should never see it; however, it is here to
415 // help diagnose failures to properly check for type-dependent
416 // expressions.
417 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000418
John McCall2a984ca2010-10-12 00:20:44 +0000419 // Placeholder type for functions.
420 InitBuiltinType(OverloadTy, BuiltinType::Overload);
421
John McCall864c0412011-04-26 20:42:42 +0000422 // Placeholder type for bound members.
423 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
424
John McCall1de4d4e2011-04-07 08:22:57 +0000425 // "any" type; useful for debugger-like clients.
426 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
427
Reid Spencer5f016e22007-07-11 17:01:13 +0000428 // C99 6.2.5p11.
429 FloatComplexTy = getComplexType(FloatTy);
430 DoubleComplexTy = getComplexType(DoubleTy);
431 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000432
Steve Naroff7e219e42007-10-15 14:41:52 +0000433 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Steve Naroffde2e22d2009-07-15 18:40:39 +0000435 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
436 ObjCIdTypedefType = QualType();
437 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000438 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000440 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000441 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
442 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000443 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000444
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000445 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000446
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000447 // void * type
448 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000449
450 // nullptr type (C++0x 2.14.7)
451 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000452}
453
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000454Diagnostic &ASTContext::getDiagnostics() const {
455 return SourceMgr.getDiagnostics();
456}
457
Douglas Gregor63200642010-08-30 16:49:28 +0000458AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
459 AttrVec *&Result = DeclAttrs[D];
460 if (!Result) {
461 void *Mem = Allocate(sizeof(AttrVec));
462 Result = new (Mem) AttrVec;
463 }
464
465 return *Result;
466}
467
468/// \brief Erase the attributes corresponding to the given declaration.
469void ASTContext::eraseDeclAttrs(const Decl *D) {
470 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
471 if (Pos != DeclAttrs.end()) {
472 Pos->second->~AttrVec();
473 DeclAttrs.erase(Pos);
474 }
475}
476
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000477MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000478ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000479 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000480 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000481 = InstantiatedFromStaticDataMember.find(Var);
482 if (Pos == InstantiatedFromStaticDataMember.end())
483 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Douglas Gregor7caa6822009-07-24 20:34:43 +0000485 return Pos->second;
486}
487
Mike Stump1eb44332009-09-09 15:08:12 +0000488void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000489ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000490 TemplateSpecializationKind TSK,
491 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000492 assert(Inst->isStaticDataMember() && "Not a static data member");
493 assert(Tmpl->isStaticDataMember() && "Not a static data member");
494 assert(!InstantiatedFromStaticDataMember[Inst] &&
495 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000496 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000497 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000498}
499
John McCall7ba107a2009-11-18 02:36:19 +0000500NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000501ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000502 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000503 = InstantiatedFromUsingDecl.find(UUD);
504 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000505 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000506
Anders Carlsson0d8df782009-08-29 19:37:28 +0000507 return Pos->second;
508}
509
510void
John McCalled976492009-12-04 22:46:56 +0000511ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
512 assert((isa<UsingDecl>(Pattern) ||
513 isa<UnresolvedUsingValueDecl>(Pattern) ||
514 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
515 "pattern decl is not a using decl");
516 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
517 InstantiatedFromUsingDecl[Inst] = Pattern;
518}
519
520UsingShadowDecl *
521ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
522 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
523 = InstantiatedFromUsingShadowDecl.find(Inst);
524 if (Pos == InstantiatedFromUsingShadowDecl.end())
525 return 0;
526
527 return Pos->second;
528}
529
530void
531ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
532 UsingShadowDecl *Pattern) {
533 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
534 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000535}
536
Anders Carlssond8b285f2009-09-01 04:26:58 +0000537FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
538 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
539 = InstantiatedFromUnnamedFieldDecl.find(Field);
540 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
541 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000542
Anders Carlssond8b285f2009-09-01 04:26:58 +0000543 return Pos->second;
544}
545
546void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
547 FieldDecl *Tmpl) {
548 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
549 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
550 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
551 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000552
Anders Carlssond8b285f2009-09-01 04:26:58 +0000553 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
554}
555
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000556bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
557 const FieldDecl *LastFD) const {
558 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Chad Rosier682b7f82011-08-04 21:50:29 +0000559 FD->getBitWidth()->EvaluateAsInt(*this).getZExtValue() == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000560}
561
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000562bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
563 const FieldDecl *LastFD) const {
564 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Chad Rosier682b7f82011-08-04 21:50:29 +0000565 FD->getBitWidth()->EvaluateAsInt(*this).getZExtValue() == 0 &&
566 LastFD->getBitWidth()->EvaluateAsInt(*this).getZExtValue() != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000567}
568
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000569bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
570 const FieldDecl *LastFD) const {
571 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Chad Rosier682b7f82011-08-04 21:50:29 +0000572 FD->getBitWidth()->EvaluateAsInt(*this).getZExtValue() &&
573 LastFD->getBitWidth()->EvaluateAsInt(*this).getZExtValue());
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000574}
575
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000576bool ASTContext::NoneBitfieldFollowsBitfield(const FieldDecl *FD,
577 const FieldDecl *LastFD) const {
578 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Chad Rosier682b7f82011-08-04 21:50:29 +0000579 LastFD->getBitWidth()->EvaluateAsInt(*this).getZExtValue());
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000580}
581
582bool ASTContext::BitfieldFollowsNoneBitfield(const FieldDecl *FD,
583 const FieldDecl *LastFD) const {
584 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Chad Rosier682b7f82011-08-04 21:50:29 +0000585 FD->getBitWidth()->EvaluateAsInt(*this).getZExtValue());
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000586}
587
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000588ASTContext::overridden_cxx_method_iterator
589ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
590 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
591 = OverriddenMethods.find(Method);
592 if (Pos == OverriddenMethods.end())
593 return 0;
594
595 return Pos->second.begin();
596}
597
598ASTContext::overridden_cxx_method_iterator
599ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
600 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
601 = OverriddenMethods.find(Method);
602 if (Pos == OverriddenMethods.end())
603 return 0;
604
605 return Pos->second.end();
606}
607
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000608unsigned
609ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
610 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
611 = OverriddenMethods.find(Method);
612 if (Pos == OverriddenMethods.end())
613 return 0;
614
615 return Pos->second.size();
616}
617
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000618void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
619 const CXXMethodDecl *Overridden) {
620 OverriddenMethods[Method].push_back(Overridden);
621}
622
Chris Lattner464175b2007-07-18 17:52:12 +0000623//===----------------------------------------------------------------------===//
624// Type Sizing and Analysis
625//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000626
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000627/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
628/// scalar floating point type.
629const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000630 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000631 assert(BT && "Not a floating point type!");
632 switch (BT->getKind()) {
633 default: assert(0 && "Not a floating point type!");
634 case BuiltinType::Float: return Target.getFloatFormat();
635 case BuiltinType::Double: return Target.getDoubleFormat();
636 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
637 }
638}
639
Ken Dyck8b752f12010-01-27 17:10:57 +0000640/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000641/// specified decl. Note that bitfields do not have a valid alignment, so
642/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000643/// If @p RefAsPointee, references are treated like their underlying type
644/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +0000645CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000646 unsigned Align = Target.getCharWidth();
647
John McCall4081a5c2010-10-08 18:24:19 +0000648 bool UseAlignAttrOnly = false;
649 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
650 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +0000651
John McCall4081a5c2010-10-08 18:24:19 +0000652 // __attribute__((aligned)) can increase or decrease alignment
653 // *except* on a struct or struct member, where it only increases
654 // alignment unless 'packed' is also specified.
655 //
656 // It is an error for [[align]] to decrease alignment, so we can
657 // ignore that possibility; Sema should diagnose it.
658 if (isa<FieldDecl>(D)) {
659 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
660 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
661 } else {
662 UseAlignAttrOnly = true;
663 }
664 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +0000665 else if (isa<FieldDecl>(D))
666 UseAlignAttrOnly =
667 D->hasAttr<PackedAttr>() ||
668 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +0000669
John McCallba4f5d52011-01-20 07:57:12 +0000670 // If we're using the align attribute only, just ignore everything
671 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +0000672 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +0000673 // do nothing
674
John McCall4081a5c2010-10-08 18:24:19 +0000675 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +0000676 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000677 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000678 if (RefAsPointee)
679 T = RT->getPointeeType();
680 else
681 T = getPointerType(RT->getPointeeType());
682 }
683 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +0000684 // Adjust alignments of declarations with array type by the
685 // large-array alignment on the target.
Rafael Espindola6deecb02010-06-04 23:15:27 +0000686 unsigned MinWidth = Target.getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +0000687 const ArrayType *arrayType;
688 if (MinWidth && (arrayType = getAsArrayType(T))) {
689 if (isa<VariableArrayType>(arrayType))
690 Align = std::max(Align, Target.getLargeArrayAlign());
691 else if (isa<ConstantArrayType>(arrayType) &&
692 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
693 Align = std::max(Align, Target.getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000694
John McCall3b657512011-01-19 10:06:00 +0000695 // Walk through any array types while we're at it.
696 T = getBaseElementType(arrayType);
697 }
Chad Rosier9f1210c2011-07-26 07:03:04 +0000698 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedmandcdafb62009-02-22 02:56:25 +0000699 }
John McCallba4f5d52011-01-20 07:57:12 +0000700
701 // Fields can be subject to extra alignment constraints, like if
702 // the field is packed, the struct is packed, or the struct has a
703 // a max-field-alignment constraint (#pragma pack). So calculate
704 // the actual alignment of the field within the struct, and then
705 // (as we're expected to) constrain that by the alignment of the type.
706 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
707 // So calculate the alignment of the field.
708 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
709
710 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +0000711 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +0000712
713 // Use the GCD of that and the offset within the record.
714 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
715 if (offset > 0) {
716 // Alignment is always a power of 2, so the GCD will be a power of 2,
717 // which means we get to do this crazy thing instead of Euclid's.
718 uint64_t lowBitOfOffset = offset & (~offset + 1);
719 if (lowBitOfOffset < fieldAlign)
720 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
721 }
722
723 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +0000724 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000725 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000726
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000727 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +0000728}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000729
John McCallea1471e2010-05-20 01:18:31 +0000730std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000731ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +0000732 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000733 return std::make_pair(toCharUnitsFromBits(Info.first),
734 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +0000735}
736
737std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000738ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +0000739 return getTypeInfoInChars(T.getTypePtr());
740}
741
Chris Lattnera7674d82007-07-13 22:13:22 +0000742/// getTypeSize - Return the size of the specified type, in bits. This method
743/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000744///
745/// FIXME: Pointers into different addr spaces could have different sizes and
746/// alignment requirements: getPointerInfo should take an AddrSpace, this
747/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000748std::pair<uint64_t, unsigned>
Jay Foad4ba2a172011-01-12 09:06:06 +0000749ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +0000750 uint64_t Width=0;
751 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000752 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000753#define TYPE(Class, Base)
754#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000755#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000756#define DEPENDENT_TYPE(Class, Base) case Type::Class:
757#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +0000758 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000759 break;
760
Chris Lattner692233e2007-07-13 22:27:08 +0000761 case Type::FunctionNoProto:
762 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000763 // GCC extension: alignof(function) = 32 bits
764 Width = 0;
765 Align = 32;
766 break;
767
Douglas Gregor72564e72009-02-26 23:50:07 +0000768 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000769 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000770 Width = 0;
771 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
772 break;
773
Steve Narofffb22d962007-08-30 01:06:46 +0000774 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000775 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000776
Chris Lattner98be4942008-03-05 18:54:05 +0000777 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000778 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000779 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +0000780 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000781 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000782 }
Nate Begeman213541a2008-04-18 23:10:10 +0000783 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000784 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000785 const VectorType *VT = cast<VectorType>(T);
786 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
787 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000788 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000789 // If the alignment is not a power of 2, round up to the next power of 2.
790 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000791 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000792 Align = llvm::NextPowerOf2(Align);
793 Width = llvm::RoundUpToAlignment(Width, Align);
794 }
Chris Lattner030d8842007-07-19 22:06:24 +0000795 break;
796 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000797
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000798 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000799 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000800 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000801 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000802 // GCC extension: alignof(void) = 8 bits.
803 Width = 0;
804 Align = 8;
805 break;
806
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000807 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000808 Width = Target.getBoolWidth();
809 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000810 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000811 case BuiltinType::Char_S:
812 case BuiltinType::Char_U:
813 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000814 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000815 Width = Target.getCharWidth();
816 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000817 break;
Chris Lattner3f59c972010-12-25 23:25:43 +0000818 case BuiltinType::WChar_S:
819 case BuiltinType::WChar_U:
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000820 Width = Target.getWCharWidth();
821 Align = Target.getWCharAlign();
822 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000823 case BuiltinType::Char16:
824 Width = Target.getChar16Width();
825 Align = Target.getChar16Align();
826 break;
827 case BuiltinType::Char32:
828 Width = Target.getChar32Width();
829 Align = Target.getChar32Align();
830 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000831 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000832 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000833 Width = Target.getShortWidth();
834 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000835 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000836 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000837 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000838 Width = Target.getIntWidth();
839 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000840 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000841 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000842 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000843 Width = Target.getLongWidth();
844 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000845 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000846 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000847 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000848 Width = Target.getLongLongWidth();
849 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000850 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000851 case BuiltinType::Int128:
852 case BuiltinType::UInt128:
853 Width = 128;
854 Align = 128; // int128_t is 128-bit aligned on all targets.
855 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000856 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000857 Width = Target.getFloatWidth();
858 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000859 break;
860 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000861 Width = Target.getDoubleWidth();
862 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000863 break;
864 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000865 Width = Target.getLongDoubleWidth();
866 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000867 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000868 case BuiltinType::NullPtr:
869 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
870 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000871 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000872 case BuiltinType::ObjCId:
873 case BuiltinType::ObjCClass:
874 case BuiltinType::ObjCSel:
875 Width = Target.getPointerWidth(0);
876 Align = Target.getPointerAlign(0);
877 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000878 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000879 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000880 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000881 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000882 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000883 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000884 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000885 unsigned AS = getTargetAddressSpace(
886 cast<BlockPointerType>(T)->getPointeeType());
Steve Naroff485eeff2008-09-24 15:05:44 +0000887 Width = Target.getPointerWidth(AS);
888 Align = Target.getPointerAlign(AS);
889 break;
890 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000891 case Type::LValueReference:
892 case Type::RValueReference: {
893 // alignof and sizeof should never enter this code path here, so we go
894 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000895 unsigned AS = getTargetAddressSpace(
896 cast<ReferenceType>(T)->getPointeeType());
Sebastian Redl5d484e82009-11-23 17:18:46 +0000897 Width = Target.getPointerWidth(AS);
898 Align = Target.getPointerAlign(AS);
899 break;
900 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000901 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000902 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Chris Lattner5426bf62008-04-07 07:01:58 +0000903 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000904 Align = Target.getPointerAlign(AS);
905 break;
906 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000907 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +0000908 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000909 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000910 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +0000911 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000912 Align = PtrDiffInfo.second;
913 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000914 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000915 case Type::Complex: {
916 // Complex types have the same alignment as their elements, but twice the
917 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000918 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000919 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000920 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000921 Align = EltInfo.second;
922 break;
923 }
John McCallc12c5bb2010-05-15 11:32:37 +0000924 case Type::ObjCObject:
925 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000926 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000927 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000928 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +0000929 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +0000930 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +0000931 break;
932 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000933 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000934 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000935 const TagType *TT = cast<TagType>(T);
936
937 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +0000938 Width = 8;
939 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +0000940 break;
941 }
Mike Stump1eb44332009-09-09 15:08:12 +0000942
Daniel Dunbar1d751182008-11-08 05:48:37 +0000943 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000944 return getTypeInfo(ET->getDecl()->getIntegerType());
945
Daniel Dunbar1d751182008-11-08 05:48:37 +0000946 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000947 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +0000948 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +0000949 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000950 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000951 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000952
Chris Lattner9fcfe922009-10-22 05:17:15 +0000953 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000954 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
955 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000956
Richard Smith34b41d92011-02-20 03:19:35 +0000957 case Type::Auto: {
958 const AutoType *A = cast<AutoType>(T);
959 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +0000960 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +0000961 }
962
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000963 case Type::Paren:
964 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
965
Douglas Gregor18857642009-04-30 17:32:17 +0000966 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +0000967 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +0000968 std::pair<uint64_t, unsigned> Info
969 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +0000970 // If the typedef has an aligned attribute on it, it overrides any computed
971 // alignment we have. This violates the GCC documentation (which says that
972 // attribute(aligned) can only round up) but matches its implementation.
973 if (unsigned AttrAlign = Typedef->getMaxAlignment())
974 Align = AttrAlign;
975 else
976 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +0000977 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +0000978 break;
Chris Lattner71763312008-04-06 22:05:18 +0000979 }
Douglas Gregor18857642009-04-30 17:32:17 +0000980
981 case Type::TypeOfExpr:
982 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
983 .getTypePtr());
984
985 case Type::TypeOf:
986 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
987
Anders Carlsson395b4752009-06-24 19:06:50 +0000988 case Type::Decltype:
989 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
990 .getTypePtr());
991
Sean Huntca63c202011-05-24 22:41:36 +0000992 case Type::UnaryTransform:
993 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
994
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000995 case Type::Elaborated:
996 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000997
John McCall9d156a72011-01-06 01:58:22 +0000998 case Type::Attributed:
999 return getTypeInfo(
1000 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1001
Richard Smith3e4c6c42011-05-05 21:57:07 +00001002 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001003 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001004 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001005 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1006 // A type alias template specialization may refer to a typedef with the
1007 // aligned attribute on it.
1008 if (TST->isTypeAlias())
1009 return getTypeInfo(TST->getAliasedType().getTypePtr());
1010 else
1011 return getTypeInfo(getCanonicalType(T));
1012 }
1013
Douglas Gregor18857642009-04-30 17:32:17 +00001014 }
Mike Stump1eb44332009-09-09 15:08:12 +00001015
Chris Lattner464175b2007-07-18 17:52:12 +00001016 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001017 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001018}
1019
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001020/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1021CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1022 return CharUnits::fromQuantity(BitSize / getCharWidth());
1023}
1024
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001025/// toBits - Convert a size in characters to a size in characters.
1026int64_t ASTContext::toBits(CharUnits CharSize) const {
1027 return CharSize.getQuantity() * getCharWidth();
1028}
1029
Ken Dyckbdc601b2009-12-22 14:23:30 +00001030/// getTypeSizeInChars - Return the size of the specified type, in characters.
1031/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001032CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001033 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001034}
Jay Foad4ba2a172011-01-12 09:06:06 +00001035CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001036 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001037}
1038
Ken Dyck16e20cc2010-01-26 17:25:18 +00001039/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001040/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001041CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001042 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001043}
Jay Foad4ba2a172011-01-12 09:06:06 +00001044CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001045 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001046}
1047
Chris Lattner34ebde42009-01-27 18:08:34 +00001048/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1049/// type for the current target in bits. This can be different than the ABI
1050/// alignment in cases where it is beneficial for performance to overalign
1051/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001052unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001053 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001054
1055 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001056 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001057 T = CT->getElementType().getTypePtr();
1058 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1059 T->isSpecificBuiltinType(BuiltinType::LongLong))
1060 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1061
Chris Lattner34ebde42009-01-27 18:08:34 +00001062 return ABIAlign;
1063}
1064
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001065/// DeepCollectObjCIvars -
1066/// This routine first collects all declared, but not synthesized, ivars in
1067/// super class and then collects all ivars, including those synthesized for
1068/// current class. This routine is used for implementation of current class
1069/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001070///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001071void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1072 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001073 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001074 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1075 DeepCollectObjCIvars(SuperClass, false, Ivars);
1076 if (!leafClass) {
1077 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1078 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanian11062e12010-02-19 00:31:17 +00001079 Ivars.push_back(*I);
1080 }
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001081 else {
1082 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001083 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001084 Iv= Iv->getNextIvar())
1085 Ivars.push_back(Iv);
1086 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001087}
1088
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001089/// CollectInheritedProtocols - Collect all protocols in current class and
1090/// those inherited by it.
1091void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001092 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001093 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001094 // We can use protocol_iterator here instead of
1095 // all_referenced_protocol_iterator since we are walking all categories.
1096 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1097 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001098 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001099 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001100 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001101 PE = Proto->protocol_end(); P != PE; ++P) {
1102 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001103 CollectInheritedProtocols(*P, Protocols);
1104 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001105 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001106
1107 // Categories of this Interface.
1108 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1109 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1110 CollectInheritedProtocols(CDeclChain, Protocols);
1111 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1112 while (SD) {
1113 CollectInheritedProtocols(SD, Protocols);
1114 SD = SD->getSuperClass();
1115 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001116 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001117 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001118 PE = OC->protocol_end(); P != PE; ++P) {
1119 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001120 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001121 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1122 PE = Proto->protocol_end(); P != PE; ++P)
1123 CollectInheritedProtocols(*P, Protocols);
1124 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001125 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001126 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1127 PE = OP->protocol_end(); P != PE; ++P) {
1128 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001129 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001130 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1131 PE = Proto->protocol_end(); P != PE; ++P)
1132 CollectInheritedProtocols(*P, Protocols);
1133 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001134 }
1135}
1136
Jay Foad4ba2a172011-01-12 09:06:06 +00001137unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001138 unsigned count = 0;
1139 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001140 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1141 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001142 count += CDecl->ivar_size();
1143
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001144 // Count ivar defined in this class's implementation. This
1145 // includes synthesized ivars.
1146 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001147 count += ImplDecl->ivar_size();
1148
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001149 return count;
1150}
1151
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001152/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1153ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1154 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1155 I = ObjCImpls.find(D);
1156 if (I != ObjCImpls.end())
1157 return cast<ObjCImplementationDecl>(I->second);
1158 return 0;
1159}
1160/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1161ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1162 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1163 I = ObjCImpls.find(D);
1164 if (I != ObjCImpls.end())
1165 return cast<ObjCCategoryImplDecl>(I->second);
1166 return 0;
1167}
1168
1169/// \brief Set the implementation of ObjCInterfaceDecl.
1170void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1171 ObjCImplementationDecl *ImplD) {
1172 assert(IFaceD && ImplD && "Passed null params");
1173 ObjCImpls[IFaceD] = ImplD;
1174}
1175/// \brief Set the implementation of ObjCCategoryDecl.
1176void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1177 ObjCCategoryImplDecl *ImplD) {
1178 assert(CatD && ImplD && "Passed null params");
1179 ObjCImpls[CatD] = ImplD;
1180}
1181
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001182/// \brief Get the copy initialization expression of VarDecl,or NULL if
1183/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001184Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001185 assert(VD && "Passed null params");
1186 assert(VD->hasAttr<BlocksAttr>() &&
1187 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001188 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001189 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001190 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1191}
1192
1193/// \brief Set the copy inialization expression of a block var decl.
1194void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1195 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001196 assert(VD->hasAttr<BlocksAttr>() &&
1197 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001198 BlockVarCopyInits[VD] = Init;
1199}
1200
John McCalla93c9342009-12-07 02:54:59 +00001201/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001202///
John McCalla93c9342009-12-07 02:54:59 +00001203/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001204/// the TypeLoc wrappers.
1205///
1206/// \param T the type that will be the basis for type source info. This type
1207/// should refer to how the declarator was written in source code, not to
1208/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001209TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001210 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001211 if (!DataSize)
1212 DataSize = TypeLoc::getFullDataSizeForType(T);
1213 else
1214 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001215 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001216
John McCalla93c9342009-12-07 02:54:59 +00001217 TypeSourceInfo *TInfo =
1218 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1219 new (TInfo) TypeSourceInfo(T);
1220 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001221}
1222
John McCalla93c9342009-12-07 02:54:59 +00001223TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001224 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001225 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001226 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001227 return DI;
1228}
1229
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001230const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001231ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001232 return getObjCLayout(D, 0);
1233}
1234
1235const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001236ASTContext::getASTObjCImplementationLayout(
1237 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001238 return getObjCLayout(D->getClassInterface(), D);
1239}
1240
Chris Lattnera7674d82007-07-13 22:13:22 +00001241//===----------------------------------------------------------------------===//
1242// Type creation/memoization methods
1243//===----------------------------------------------------------------------===//
1244
Jay Foad4ba2a172011-01-12 09:06:06 +00001245QualType
John McCall3b657512011-01-19 10:06:00 +00001246ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1247 unsigned fastQuals = quals.getFastQualifiers();
1248 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001249
1250 // Check if we've already instantiated this type.
1251 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001252 ExtQuals::Profile(ID, baseType, quals);
1253 void *insertPos = 0;
1254 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1255 assert(eq->getQualifiers() == quals);
1256 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001257 }
1258
John McCall3b657512011-01-19 10:06:00 +00001259 // If the base type is not canonical, make the appropriate canonical type.
1260 QualType canon;
1261 if (!baseType->isCanonicalUnqualified()) {
1262 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1263 canonSplit.second.addConsistentQualifiers(quals);
1264 canon = getExtQualType(canonSplit.first, canonSplit.second);
1265
1266 // Re-find the insert position.
1267 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1268 }
1269
1270 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1271 ExtQualNodes.InsertNode(eq, insertPos);
1272 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001273}
1274
Jay Foad4ba2a172011-01-12 09:06:06 +00001275QualType
1276ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001277 QualType CanT = getCanonicalType(T);
1278 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001279 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001280
John McCall0953e762009-09-24 19:53:00 +00001281 // If we are composing extended qualifiers together, merge together
1282 // into one ExtQuals node.
1283 QualifierCollector Quals;
1284 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001285
John McCall0953e762009-09-24 19:53:00 +00001286 // If this type already has an address space specified, it cannot get
1287 // another one.
1288 assert(!Quals.hasAddressSpace() &&
1289 "Type cannot be in multiple addr spaces!");
1290 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001291
John McCall0953e762009-09-24 19:53:00 +00001292 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001293}
1294
Chris Lattnerb7d25532009-02-18 22:53:11 +00001295QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001296 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001297 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001298 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001299 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001300
John McCall7f040a92010-12-24 02:08:15 +00001301 if (const PointerType *ptr = T->getAs<PointerType>()) {
1302 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001303 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001304 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1305 return getPointerType(ResultType);
1306 }
1307 }
Mike Stump1eb44332009-09-09 15:08:12 +00001308
John McCall0953e762009-09-24 19:53:00 +00001309 // If we are composing extended qualifiers together, merge together
1310 // into one ExtQuals node.
1311 QualifierCollector Quals;
1312 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001313
John McCall0953e762009-09-24 19:53:00 +00001314 // If this type already has an ObjCGC specified, it cannot get
1315 // another one.
1316 assert(!Quals.hasObjCGCAttr() &&
1317 "Type cannot have multiple ObjCGCs!");
1318 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001319
John McCall0953e762009-09-24 19:53:00 +00001320 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001321}
Chris Lattnera7674d82007-07-13 22:13:22 +00001322
John McCalle6a365d2010-12-19 02:44:49 +00001323const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1324 FunctionType::ExtInfo Info) {
1325 if (T->getExtInfo() == Info)
1326 return T;
1327
1328 QualType Result;
1329 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1330 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1331 } else {
1332 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1333 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1334 EPI.ExtInfo = Info;
1335 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1336 FPT->getNumArgs(), EPI);
1337 }
1338
1339 return cast<FunctionType>(Result.getTypePtr());
1340}
1341
Reid Spencer5f016e22007-07-11 17:01:13 +00001342/// getComplexType - Return the uniqued reference to the type for a complex
1343/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001344QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001345 // Unique pointers, to guarantee there is only one pointer of a particular
1346 // structure.
1347 llvm::FoldingSetNodeID ID;
1348 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001349
Reid Spencer5f016e22007-07-11 17:01:13 +00001350 void *InsertPos = 0;
1351 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1352 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001353
Reid Spencer5f016e22007-07-11 17:01:13 +00001354 // If the pointee type isn't canonical, this won't be a canonical type either,
1355 // so fill in the canonical type field.
1356 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001357 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001358 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001359
Reid Spencer5f016e22007-07-11 17:01:13 +00001360 // Get the new insert position for the node we care about.
1361 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001362 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001363 }
John McCall6b304a02009-09-24 23:30:46 +00001364 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001365 Types.push_back(New);
1366 ComplexTypes.InsertNode(New, InsertPos);
1367 return QualType(New, 0);
1368}
1369
Reid Spencer5f016e22007-07-11 17:01:13 +00001370/// getPointerType - Return the uniqued reference to the type for a pointer to
1371/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001372QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001373 // Unique pointers, to guarantee there is only one pointer of a particular
1374 // structure.
1375 llvm::FoldingSetNodeID ID;
1376 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001377
Reid Spencer5f016e22007-07-11 17:01:13 +00001378 void *InsertPos = 0;
1379 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1380 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001381
Reid Spencer5f016e22007-07-11 17:01:13 +00001382 // If the pointee type isn't canonical, this won't be a canonical type either,
1383 // so fill in the canonical type field.
1384 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001385 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001386 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001387
Reid Spencer5f016e22007-07-11 17:01:13 +00001388 // Get the new insert position for the node we care about.
1389 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001390 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001391 }
John McCall6b304a02009-09-24 23:30:46 +00001392 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001393 Types.push_back(New);
1394 PointerTypes.InsertNode(New, InsertPos);
1395 return QualType(New, 0);
1396}
1397
Mike Stump1eb44332009-09-09 15:08:12 +00001398/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001399/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001400QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001401 assert(T->isFunctionType() && "block of function types only");
1402 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001403 // structure.
1404 llvm::FoldingSetNodeID ID;
1405 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001406
Steve Naroff5618bd42008-08-27 16:04:49 +00001407 void *InsertPos = 0;
1408 if (BlockPointerType *PT =
1409 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1410 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001411
1412 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001413 // type either so fill in the canonical type field.
1414 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001415 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001416 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001417
Steve Naroff5618bd42008-08-27 16:04:49 +00001418 // Get the new insert position for the node we care about.
1419 BlockPointerType *NewIP =
1420 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001421 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001422 }
John McCall6b304a02009-09-24 23:30:46 +00001423 BlockPointerType *New
1424 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001425 Types.push_back(New);
1426 BlockPointerTypes.InsertNode(New, InsertPos);
1427 return QualType(New, 0);
1428}
1429
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001430/// getLValueReferenceType - Return the uniqued reference to the type for an
1431/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001432QualType
1433ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00001434 assert(getCanonicalType(T) != OverloadTy &&
1435 "Unresolved overloaded function type");
1436
Reid Spencer5f016e22007-07-11 17:01:13 +00001437 // Unique pointers, to guarantee there is only one pointer of a particular
1438 // structure.
1439 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001440 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001441
1442 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001443 if (LValueReferenceType *RT =
1444 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001445 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001446
John McCall54e14c42009-10-22 22:37:11 +00001447 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1448
Reid Spencer5f016e22007-07-11 17:01:13 +00001449 // If the referencee type isn't canonical, this won't be a canonical type
1450 // either, so fill in the canonical type field.
1451 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001452 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1453 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1454 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001455
Reid Spencer5f016e22007-07-11 17:01:13 +00001456 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001457 LValueReferenceType *NewIP =
1458 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001459 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001460 }
1461
John McCall6b304a02009-09-24 23:30:46 +00001462 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001463 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1464 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001465 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001466 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001467
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001468 return QualType(New, 0);
1469}
1470
1471/// getRValueReferenceType - Return the uniqued reference to the type for an
1472/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001473QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001474 // Unique pointers, to guarantee there is only one pointer of a particular
1475 // structure.
1476 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001477 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001478
1479 void *InsertPos = 0;
1480 if (RValueReferenceType *RT =
1481 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1482 return QualType(RT, 0);
1483
John McCall54e14c42009-10-22 22:37:11 +00001484 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1485
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001486 // If the referencee type isn't canonical, this won't be a canonical type
1487 // either, so fill in the canonical type field.
1488 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001489 if (InnerRef || !T.isCanonical()) {
1490 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1491 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001492
1493 // Get the new insert position for the node we care about.
1494 RValueReferenceType *NewIP =
1495 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001496 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001497 }
1498
John McCall6b304a02009-09-24 23:30:46 +00001499 RValueReferenceType *New
1500 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001501 Types.push_back(New);
1502 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001503 return QualType(New, 0);
1504}
1505
Sebastian Redlf30208a2009-01-24 21:16:55 +00001506/// getMemberPointerType - Return the uniqued reference to the type for a
1507/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00001508QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001509 // Unique pointers, to guarantee there is only one pointer of a particular
1510 // structure.
1511 llvm::FoldingSetNodeID ID;
1512 MemberPointerType::Profile(ID, T, Cls);
1513
1514 void *InsertPos = 0;
1515 if (MemberPointerType *PT =
1516 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1517 return QualType(PT, 0);
1518
1519 // If the pointee or class type isn't canonical, this won't be a canonical
1520 // type either, so fill in the canonical type field.
1521 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001522 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001523 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1524
1525 // Get the new insert position for the node we care about.
1526 MemberPointerType *NewIP =
1527 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001528 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001529 }
John McCall6b304a02009-09-24 23:30:46 +00001530 MemberPointerType *New
1531 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001532 Types.push_back(New);
1533 MemberPointerTypes.InsertNode(New, InsertPos);
1534 return QualType(New, 0);
1535}
1536
Mike Stump1eb44332009-09-09 15:08:12 +00001537/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001538/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001539QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001540 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001541 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001542 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001543 assert((EltTy->isDependentType() ||
1544 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001545 "Constant array of VLAs is illegal!");
1546
Chris Lattner38aeec72009-05-13 04:12:56 +00001547 // Convert the array size into a canonical width matching the pointer size for
1548 // the target.
1549 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001550 ArySize =
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001551 ArySize.zextOrTrunc(Target.getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Reid Spencer5f016e22007-07-11 17:01:13 +00001553 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001554 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Reid Spencer5f016e22007-07-11 17:01:13 +00001556 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001557 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001558 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001559 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001560
John McCall3b657512011-01-19 10:06:00 +00001561 // If the element type isn't canonical or has qualifiers, this won't
1562 // be a canonical type either, so fill in the canonical type field.
1563 QualType Canon;
1564 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1565 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1566 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001567 ASM, IndexTypeQuals);
John McCall3b657512011-01-19 10:06:00 +00001568 Canon = getQualifiedType(Canon, canonSplit.second);
1569
Reid Spencer5f016e22007-07-11 17:01:13 +00001570 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001571 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001572 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001573 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001574 }
Mike Stump1eb44332009-09-09 15:08:12 +00001575
John McCall6b304a02009-09-24 23:30:46 +00001576 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001577 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001578 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001579 Types.push_back(New);
1580 return QualType(New, 0);
1581}
1582
John McCallce889032011-01-18 08:40:38 +00001583/// getVariableArrayDecayedType - Turns the given type, which may be
1584/// variably-modified, into the corresponding type with all the known
1585/// sizes replaced with [*].
1586QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1587 // Vastly most common case.
1588 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001589
John McCallce889032011-01-18 08:40:38 +00001590 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001591
John McCallce889032011-01-18 08:40:38 +00001592 SplitQualType split = type.getSplitDesugaredType();
1593 const Type *ty = split.first;
1594 switch (ty->getTypeClass()) {
1595#define TYPE(Class, Base)
1596#define ABSTRACT_TYPE(Class, Base)
1597#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1598#include "clang/AST/TypeNodes.def"
1599 llvm_unreachable("didn't desugar past all non-canonical types?");
1600
1601 // These types should never be variably-modified.
1602 case Type::Builtin:
1603 case Type::Complex:
1604 case Type::Vector:
1605 case Type::ExtVector:
1606 case Type::DependentSizedExtVector:
1607 case Type::ObjCObject:
1608 case Type::ObjCInterface:
1609 case Type::ObjCObjectPointer:
1610 case Type::Record:
1611 case Type::Enum:
1612 case Type::UnresolvedUsing:
1613 case Type::TypeOfExpr:
1614 case Type::TypeOf:
1615 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00001616 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00001617 case Type::DependentName:
1618 case Type::InjectedClassName:
1619 case Type::TemplateSpecialization:
1620 case Type::DependentTemplateSpecialization:
1621 case Type::TemplateTypeParm:
1622 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00001623 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00001624 case Type::PackExpansion:
1625 llvm_unreachable("type should never be variably-modified");
1626
1627 // These types can be variably-modified but should never need to
1628 // further decay.
1629 case Type::FunctionNoProto:
1630 case Type::FunctionProto:
1631 case Type::BlockPointer:
1632 case Type::MemberPointer:
1633 return type;
1634
1635 // These types can be variably-modified. All these modifications
1636 // preserve structure except as noted by comments.
1637 // TODO: if we ever care about optimizing VLAs, there are no-op
1638 // optimizations available here.
1639 case Type::Pointer:
1640 result = getPointerType(getVariableArrayDecayedType(
1641 cast<PointerType>(ty)->getPointeeType()));
1642 break;
1643
1644 case Type::LValueReference: {
1645 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1646 result = getLValueReferenceType(
1647 getVariableArrayDecayedType(lv->getPointeeType()),
1648 lv->isSpelledAsLValue());
1649 break;
1650 }
1651
1652 case Type::RValueReference: {
1653 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1654 result = getRValueReferenceType(
1655 getVariableArrayDecayedType(lv->getPointeeType()));
1656 break;
1657 }
1658
1659 case Type::ConstantArray: {
1660 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1661 result = getConstantArrayType(
1662 getVariableArrayDecayedType(cat->getElementType()),
1663 cat->getSize(),
1664 cat->getSizeModifier(),
1665 cat->getIndexTypeCVRQualifiers());
1666 break;
1667 }
1668
1669 case Type::DependentSizedArray: {
1670 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1671 result = getDependentSizedArrayType(
1672 getVariableArrayDecayedType(dat->getElementType()),
1673 dat->getSizeExpr(),
1674 dat->getSizeModifier(),
1675 dat->getIndexTypeCVRQualifiers(),
1676 dat->getBracketsRange());
1677 break;
1678 }
1679
1680 // Turn incomplete types into [*] types.
1681 case Type::IncompleteArray: {
1682 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1683 result = getVariableArrayType(
1684 getVariableArrayDecayedType(iat->getElementType()),
1685 /*size*/ 0,
1686 ArrayType::Normal,
1687 iat->getIndexTypeCVRQualifiers(),
1688 SourceRange());
1689 break;
1690 }
1691
1692 // Turn VLA types into [*] types.
1693 case Type::VariableArray: {
1694 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1695 result = getVariableArrayType(
1696 getVariableArrayDecayedType(vat->getElementType()),
1697 /*size*/ 0,
1698 ArrayType::Star,
1699 vat->getIndexTypeCVRQualifiers(),
1700 vat->getBracketsRange());
1701 break;
1702 }
1703 }
1704
1705 // Apply the top-level qualifiers from the original.
1706 return getQualifiedType(result, split.second);
1707}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001708
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001709/// getVariableArrayType - Returns a non-unique reference to the type for a
1710/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001711QualType ASTContext::getVariableArrayType(QualType EltTy,
1712 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001713 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001714 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00001715 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001716 // Since we don't unique expressions, it isn't possible to unique VLA's
1717 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00001718 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00001719
John McCall3b657512011-01-19 10:06:00 +00001720 // Be sure to pull qualifiers off the element type.
1721 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1722 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1723 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001724 IndexTypeQuals, Brackets);
John McCall3b657512011-01-19 10:06:00 +00001725 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor715e9c82010-05-23 16:10:32 +00001726 }
1727
John McCall6b304a02009-09-24 23:30:46 +00001728 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001729 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001730
1731 VariableArrayTypes.push_back(New);
1732 Types.push_back(New);
1733 return QualType(New, 0);
1734}
1735
Douglas Gregor898574e2008-12-05 23:32:09 +00001736/// getDependentSizedArrayType - Returns a non-unique reference to
1737/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001738/// type.
John McCall3b657512011-01-19 10:06:00 +00001739QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1740 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00001741 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001742 unsigned elementTypeQuals,
1743 SourceRange brackets) const {
1744 assert((!numElements || numElements->isTypeDependent() ||
1745 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001746 "Size must be type- or value-dependent!");
1747
John McCall3b657512011-01-19 10:06:00 +00001748 // Dependently-sized array types that do not have a specified number
1749 // of elements will have their sizes deduced from a dependent
1750 // initializer. We do no canonicalization here at all, which is okay
1751 // because they can't be used in most locations.
1752 if (!numElements) {
1753 DependentSizedArrayType *newType
1754 = new (*this, TypeAlignment)
1755 DependentSizedArrayType(*this, elementType, QualType(),
1756 numElements, ASM, elementTypeQuals,
1757 brackets);
1758 Types.push_back(newType);
1759 return QualType(newType, 0);
1760 }
1761
1762 // Otherwise, we actually build a new type every time, but we
1763 // also build a canonical type.
1764
1765 SplitQualType canonElementType = getCanonicalType(elementType).split();
1766
1767 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001768 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001769 DependentSizedArrayType::Profile(ID, *this,
1770 QualType(canonElementType.first, 0),
1771 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001772
John McCall3b657512011-01-19 10:06:00 +00001773 // Look for an existing type with these properties.
1774 DependentSizedArrayType *canonTy =
1775 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001776
John McCall3b657512011-01-19 10:06:00 +00001777 // If we don't have one, build one.
1778 if (!canonTy) {
1779 canonTy = new (*this, TypeAlignment)
1780 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1781 QualType(), numElements, ASM, elementTypeQuals,
1782 brackets);
1783 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1784 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001785 }
1786
John McCall3b657512011-01-19 10:06:00 +00001787 // Apply qualifiers from the element type to the array.
1788 QualType canon = getQualifiedType(QualType(canonTy,0),
1789 canonElementType.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001790
John McCall3b657512011-01-19 10:06:00 +00001791 // If we didn't need extra canonicalization for the element type,
1792 // then just use that as our result.
1793 if (QualType(canonElementType.first, 0) == elementType)
1794 return canon;
1795
1796 // Otherwise, we need to build a type which follows the spelling
1797 // of the element type.
1798 DependentSizedArrayType *sugaredType
1799 = new (*this, TypeAlignment)
1800 DependentSizedArrayType(*this, elementType, canon, numElements,
1801 ASM, elementTypeQuals, brackets);
1802 Types.push_back(sugaredType);
1803 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00001804}
1805
John McCall3b657512011-01-19 10:06:00 +00001806QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00001807 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001808 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001809 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001810 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001811
John McCall3b657512011-01-19 10:06:00 +00001812 void *insertPos = 0;
1813 if (IncompleteArrayType *iat =
1814 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1815 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001816
1817 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00001818 // either, so fill in the canonical type field. We also have to pull
1819 // qualifiers off the element type.
1820 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00001821
John McCall3b657512011-01-19 10:06:00 +00001822 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1823 SplitQualType canonSplit = getCanonicalType(elementType).split();
1824 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1825 ASM, elementTypeQuals);
1826 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001827
1828 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00001829 IncompleteArrayType *existing =
1830 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1831 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001832 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001833
John McCall3b657512011-01-19 10:06:00 +00001834 IncompleteArrayType *newType = new (*this, TypeAlignment)
1835 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001836
John McCall3b657512011-01-19 10:06:00 +00001837 IncompleteArrayTypes.InsertNode(newType, insertPos);
1838 Types.push_back(newType);
1839 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001840}
1841
Steve Naroff73322922007-07-18 18:00:27 +00001842/// getVectorType - Return the unique reference to a vector type of
1843/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001844QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00001845 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00001846 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001847
Reid Spencer5f016e22007-07-11 17:01:13 +00001848 // Check if we've already instantiated a vector of this type.
1849 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00001850 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00001851
Reid Spencer5f016e22007-07-11 17:01:13 +00001852 void *InsertPos = 0;
1853 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1854 return QualType(VTP, 0);
1855
1856 // If the element type isn't canonical, this won't be a canonical type either,
1857 // so fill in the canonical type field.
1858 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00001859 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00001860 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00001861
Reid Spencer5f016e22007-07-11 17:01:13 +00001862 // Get the new insert position for the node we care about.
1863 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001864 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001865 }
John McCall6b304a02009-09-24 23:30:46 +00001866 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00001867 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001868 VectorTypes.InsertNode(New, InsertPos);
1869 Types.push_back(New);
1870 return QualType(New, 0);
1871}
1872
Nate Begeman213541a2008-04-18 23:10:10 +00001873/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001874/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001875QualType
1876ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00001877 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00001878
Steve Naroff73322922007-07-18 18:00:27 +00001879 // Check if we've already instantiated a vector of this type.
1880 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001881 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001882 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00001883 void *InsertPos = 0;
1884 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1885 return QualType(VTP, 0);
1886
1887 // If the element type isn't canonical, this won't be a canonical type either,
1888 // so fill in the canonical type field.
1889 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001890 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001891 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001892
Steve Naroff73322922007-07-18 18:00:27 +00001893 // Get the new insert position for the node we care about.
1894 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001895 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001896 }
John McCall6b304a02009-09-24 23:30:46 +00001897 ExtVectorType *New = new (*this, TypeAlignment)
1898 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001899 VectorTypes.InsertNode(New, InsertPos);
1900 Types.push_back(New);
1901 return QualType(New, 0);
1902}
1903
Jay Foad4ba2a172011-01-12 09:06:06 +00001904QualType
1905ASTContext::getDependentSizedExtVectorType(QualType vecType,
1906 Expr *SizeExpr,
1907 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001908 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001909 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001910 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001911
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001912 void *InsertPos = 0;
1913 DependentSizedExtVectorType *Canon
1914 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1915 DependentSizedExtVectorType *New;
1916 if (Canon) {
1917 // We already have a canonical version of this array type; use it as
1918 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001919 New = new (*this, TypeAlignment)
1920 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1921 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001922 } else {
1923 QualType CanonVecTy = getCanonicalType(vecType);
1924 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001925 New = new (*this, TypeAlignment)
1926 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1927 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001928
1929 DependentSizedExtVectorType *CanonCheck
1930 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1931 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1932 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001933 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1934 } else {
1935 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1936 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001937 New = new (*this, TypeAlignment)
1938 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001939 }
1940 }
Mike Stump1eb44332009-09-09 15:08:12 +00001941
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001942 Types.push_back(New);
1943 return QualType(New, 0);
1944}
1945
Douglas Gregor72564e72009-02-26 23:50:07 +00001946/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001947///
Jay Foad4ba2a172011-01-12 09:06:06 +00001948QualType
1949ASTContext::getFunctionNoProtoType(QualType ResultTy,
1950 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00001951 const CallingConv DefaultCC = Info.getCC();
1952 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1953 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00001954 // Unique functions, to guarantee there is only one function of a particular
1955 // structure.
1956 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00001957 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001958
Reid Spencer5f016e22007-07-11 17:01:13 +00001959 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001960 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001961 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001962 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001963
Reid Spencer5f016e22007-07-11 17:01:13 +00001964 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001965 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001966 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001967 Canonical =
1968 getFunctionNoProtoType(getCanonicalType(ResultTy),
1969 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Reid Spencer5f016e22007-07-11 17:01:13 +00001971 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001972 FunctionNoProtoType *NewIP =
1973 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001974 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001975 }
Mike Stump1eb44332009-09-09 15:08:12 +00001976
Roman Divackycfe9af22011-03-01 17:40:53 +00001977 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00001978 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00001979 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00001980 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001981 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001982 return QualType(New, 0);
1983}
1984
1985/// getFunctionType - Return a normal function type with a typed argument
1986/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00001987QualType
1988ASTContext::getFunctionType(QualType ResultTy,
1989 const QualType *ArgArray, unsigned NumArgs,
1990 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001991 // Unique functions, to guarantee there is only one function of a particular
1992 // structure.
1993 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001994 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00001995
1996 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001997 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001998 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001999 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002000
2001 // Determine whether the type being created is already canonical or not.
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002002 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00002003 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002004 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002005 isCanonical = false;
2006
Roman Divackycfe9af22011-03-01 17:40:53 +00002007 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2008 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2009 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002010
Reid Spencer5f016e22007-07-11 17:01:13 +00002011 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002012 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002013 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002014 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002015 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002016 CanonicalArgs.reserve(NumArgs);
2017 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002018 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002019
John McCalle23cf432010-12-14 08:05:40 +00002020 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002021 CanonicalEPI.ExceptionSpecType = EST_None;
2022 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002023 CanonicalEPI.ExtInfo
2024 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2025
Chris Lattnerf52ab252008-04-06 22:59:24 +00002026 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00002027 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002028 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002029
Reid Spencer5f016e22007-07-11 17:01:13 +00002030 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002031 FunctionProtoType *NewIP =
2032 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002033 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002034 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002035
John McCallf85e1932011-06-15 23:02:42 +00002036 // FunctionProtoType objects are allocated with extra bytes after
2037 // them for three variable size arrays at the end:
2038 // - parameter types
2039 // - exception types
2040 // - consumed-arguments flags
2041 // Instead of the exception types, there could be a noexcept
2042 // expression.
John McCalle23cf432010-12-14 08:05:40 +00002043 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002044 NumArgs * sizeof(QualType);
2045 if (EPI.ExceptionSpecType == EST_Dynamic)
2046 Size += EPI.NumExceptions * sizeof(QualType);
2047 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002048 Size += sizeof(Expr*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002049 }
John McCallf85e1932011-06-15 23:02:42 +00002050 if (EPI.ConsumedArguments)
2051 Size += NumArgs * sizeof(bool);
2052
John McCalle23cf432010-12-14 08:05:40 +00002053 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002054 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2055 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002056 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002057 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002058 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002059 return QualType(FTP, 0);
2060}
2061
John McCall3cb0ebd2010-03-10 03:28:59 +00002062#ifndef NDEBUG
2063static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2064 if (!isa<CXXRecordDecl>(D)) return false;
2065 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2066 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2067 return true;
2068 if (RD->getDescribedClassTemplate() &&
2069 !isa<ClassTemplateSpecializationDecl>(RD))
2070 return true;
2071 return false;
2072}
2073#endif
2074
2075/// getInjectedClassNameType - Return the unique reference to the
2076/// injected class name type for the specified templated declaration.
2077QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002078 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002079 assert(NeedsInjectedClassNameType(Decl));
2080 if (Decl->TypeForDecl) {
2081 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00002082 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002083 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2084 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2085 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2086 } else {
John McCallf4c73712011-01-19 06:33:43 +00002087 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002088 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002089 Decl->TypeForDecl = newType;
2090 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002091 }
2092 return QualType(Decl->TypeForDecl, 0);
2093}
2094
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002095/// getTypeDeclType - Return the unique reference to the type for the
2096/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002097QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002098 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002099 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002100
Richard Smith162e1c12011-04-15 14:24:37 +00002101 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002102 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002103
John McCallbecb8d52010-03-10 06:48:02 +00002104 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2105 "Template type parameter types are always available.");
2106
John McCall19c85762010-02-16 03:57:14 +00002107 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002108 assert(!Record->getPreviousDeclaration() &&
2109 "struct/union has previous declaration");
2110 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002111 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002112 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002113 assert(!Enum->getPreviousDeclaration() &&
2114 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002115 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002116 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002117 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002118 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2119 Decl->TypeForDecl = newType;
2120 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002121 } else
John McCallbecb8d52010-03-10 06:48:02 +00002122 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002123
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002124 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002125}
2126
Reid Spencer5f016e22007-07-11 17:01:13 +00002127/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002128/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002129QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002130ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2131 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002132 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002133
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002134 if (Canonical.isNull())
2135 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002136 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002137 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002138 Decl->TypeForDecl = newType;
2139 Types.push_back(newType);
2140 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002141}
2142
Jay Foad4ba2a172011-01-12 09:06:06 +00002143QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002144 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2145
2146 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2147 if (PrevDecl->TypeForDecl)
2148 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2149
John McCallf4c73712011-01-19 06:33:43 +00002150 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2151 Decl->TypeForDecl = newType;
2152 Types.push_back(newType);
2153 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002154}
2155
Jay Foad4ba2a172011-01-12 09:06:06 +00002156QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002157 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2158
2159 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2160 if (PrevDecl->TypeForDecl)
2161 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2162
John McCallf4c73712011-01-19 06:33:43 +00002163 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2164 Decl->TypeForDecl = newType;
2165 Types.push_back(newType);
2166 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002167}
2168
John McCall9d156a72011-01-06 01:58:22 +00002169QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2170 QualType modifiedType,
2171 QualType equivalentType) {
2172 llvm::FoldingSetNodeID id;
2173 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2174
2175 void *insertPos = 0;
2176 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2177 if (type) return QualType(type, 0);
2178
2179 QualType canon = getCanonicalType(equivalentType);
2180 type = new (*this, TypeAlignment)
2181 AttributedType(canon, attrKind, modifiedType, equivalentType);
2182
2183 Types.push_back(type);
2184 AttributedTypes.InsertNode(type, insertPos);
2185
2186 return QualType(type, 0);
2187}
2188
2189
John McCall49a832b2009-10-18 09:09:24 +00002190/// \brief Retrieve a substitution-result type.
2191QualType
2192ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002193 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002194 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002195 && "replacement types must always be canonical");
2196
2197 llvm::FoldingSetNodeID ID;
2198 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2199 void *InsertPos = 0;
2200 SubstTemplateTypeParmType *SubstParm
2201 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2202
2203 if (!SubstParm) {
2204 SubstParm = new (*this, TypeAlignment)
2205 SubstTemplateTypeParmType(Parm, Replacement);
2206 Types.push_back(SubstParm);
2207 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2208 }
2209
2210 return QualType(SubstParm, 0);
2211}
2212
Douglas Gregorc3069d62011-01-14 02:55:32 +00002213/// \brief Retrieve a
2214QualType ASTContext::getSubstTemplateTypeParmPackType(
2215 const TemplateTypeParmType *Parm,
2216 const TemplateArgument &ArgPack) {
2217#ifndef NDEBUG
2218 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2219 PEnd = ArgPack.pack_end();
2220 P != PEnd; ++P) {
2221 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2222 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2223 }
2224#endif
2225
2226 llvm::FoldingSetNodeID ID;
2227 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2228 void *InsertPos = 0;
2229 if (SubstTemplateTypeParmPackType *SubstParm
2230 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2231 return QualType(SubstParm, 0);
2232
2233 QualType Canon;
2234 if (!Parm->isCanonicalUnqualified()) {
2235 Canon = getCanonicalType(QualType(Parm, 0));
2236 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2237 ArgPack);
2238 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2239 }
2240
2241 SubstTemplateTypeParmPackType *SubstParm
2242 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2243 ArgPack);
2244 Types.push_back(SubstParm);
2245 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2246 return QualType(SubstParm, 0);
2247}
2248
Douglas Gregorfab9d672009-02-05 23:33:38 +00002249/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002250/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002251/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002252QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002253 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002254 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002255 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002256 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002257 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002258 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002259 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2260
2261 if (TypeParm)
2262 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002263
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002264 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002265 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002266 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002267
2268 TemplateTypeParmType *TypeCheck
2269 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2270 assert(!TypeCheck && "Template type parameter canonical type broken");
2271 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002272 } else
John McCall6b304a02009-09-24 23:30:46 +00002273 TypeParm = new (*this, TypeAlignment)
2274 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002275
2276 Types.push_back(TypeParm);
2277 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2278
2279 return QualType(TypeParm, 0);
2280}
2281
John McCall3cb0ebd2010-03-10 03:28:59 +00002282TypeSourceInfo *
2283ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2284 SourceLocation NameLoc,
2285 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002286 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002287 assert(!Name.getAsDependentTemplateName() &&
2288 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002289 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002290
2291 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2292 TemplateSpecializationTypeLoc TL
2293 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2294 TL.setTemplateNameLoc(NameLoc);
2295 TL.setLAngleLoc(Args.getLAngleLoc());
2296 TL.setRAngleLoc(Args.getRAngleLoc());
2297 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2298 TL.setArgLocInfo(i, Args[i].getLocInfo());
2299 return DI;
2300}
2301
Mike Stump1eb44332009-09-09 15:08:12 +00002302QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002303ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002304 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002305 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002306 assert(!Template.getAsDependentTemplateName() &&
2307 "No dependent template names here!");
2308
John McCalld5532b62009-11-23 01:53:49 +00002309 unsigned NumArgs = Args.size();
2310
Chris Lattner5f9e2722011-07-23 10:55:15 +00002311 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002312 ArgVec.reserve(NumArgs);
2313 for (unsigned i = 0; i != NumArgs; ++i)
2314 ArgVec.push_back(Args[i].getArgument());
2315
John McCall31f17ec2010-04-27 00:57:59 +00002316 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002317 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002318}
2319
2320QualType
2321ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002322 const TemplateArgument *Args,
2323 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002324 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002325 assert(!Template.getAsDependentTemplateName() &&
2326 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002327 // Look through qualified template names.
2328 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2329 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002330
Richard Smith3e4c6c42011-05-05 21:57:07 +00002331 bool isTypeAlias =
2332 Template.getAsTemplateDecl() &&
2333 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2334
2335 QualType CanonType;
2336 if (!Underlying.isNull())
2337 CanonType = getCanonicalType(Underlying);
2338 else {
2339 assert(!isTypeAlias &&
2340 "Underlying type for template alias must be computed by caller");
2341 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2342 NumArgs);
2343 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002344
Douglas Gregor1275ae02009-07-28 23:00:59 +00002345 // Allocate the (non-canonical) template specialization type, but don't
2346 // try to unique it: these types typically have location information that
2347 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002348 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2349 sizeof(TemplateArgument) * NumArgs +
2350 (isTypeAlias ? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00002351 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002352 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00002353 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00002354 Args, NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002355 CanonType,
2356 isTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00002357
Douglas Gregor55f6b142009-02-09 18:46:07 +00002358 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002359 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002360}
2361
Mike Stump1eb44332009-09-09 15:08:12 +00002362QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002363ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2364 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002365 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002366 assert(!Template.getAsDependentTemplateName() &&
2367 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002368 assert((!Template.getAsTemplateDecl() ||
2369 !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2370 "Underlying type for template alias must be computed by caller");
2371
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002372 // Look through qualified template names.
2373 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2374 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002375
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002376 // Build the canonical template specialization type.
2377 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002378 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002379 CanonArgs.reserve(NumArgs);
2380 for (unsigned I = 0; I != NumArgs; ++I)
2381 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2382
2383 // Determine whether this canonical template specialization type already
2384 // exists.
2385 llvm::FoldingSetNodeID ID;
2386 TemplateSpecializationType::Profile(ID, CanonTemplate,
2387 CanonArgs.data(), NumArgs, *this);
2388
2389 void *InsertPos = 0;
2390 TemplateSpecializationType *Spec
2391 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2392
2393 if (!Spec) {
2394 // Allocate a new canonical template specialization type.
2395 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2396 sizeof(TemplateArgument) * NumArgs),
2397 TypeAlignment);
2398 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2399 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002400 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002401 Types.push_back(Spec);
2402 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2403 }
2404
2405 assert(Spec->isDependentType() &&
2406 "Non-dependent template-id type must have a canonical type");
2407 return QualType(Spec, 0);
2408}
2409
2410QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002411ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2412 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002413 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002414 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002415 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002416
2417 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002418 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002419 if (T)
2420 return QualType(T, 0);
2421
Douglas Gregor789b1f62010-02-04 18:10:26 +00002422 QualType Canon = NamedType;
2423 if (!Canon.isCanonical()) {
2424 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002425 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2426 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002427 (void)CheckT;
2428 }
2429
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002430 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002431 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002432 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002433 return QualType(T, 0);
2434}
2435
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002436QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002437ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002438 llvm::FoldingSetNodeID ID;
2439 ParenType::Profile(ID, InnerType);
2440
2441 void *InsertPos = 0;
2442 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2443 if (T)
2444 return QualType(T, 0);
2445
2446 QualType Canon = InnerType;
2447 if (!Canon.isCanonical()) {
2448 Canon = getCanonicalType(InnerType);
2449 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2450 assert(!CheckT && "Paren canonical type broken");
2451 (void)CheckT;
2452 }
2453
2454 T = new (*this) ParenType(InnerType, Canon);
2455 Types.push_back(T);
2456 ParenTypes.InsertNode(T, InsertPos);
2457 return QualType(T, 0);
2458}
2459
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002460QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2461 NestedNameSpecifier *NNS,
2462 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002463 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002464 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2465
2466 if (Canon.isNull()) {
2467 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002468 ElaboratedTypeKeyword CanonKeyword = Keyword;
2469 if (Keyword == ETK_None)
2470 CanonKeyword = ETK_Typename;
2471
2472 if (CanonNNS != NNS || CanonKeyword != Keyword)
2473 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002474 }
2475
2476 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002477 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002478
2479 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002480 DependentNameType *T
2481 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002482 if (T)
2483 return QualType(T, 0);
2484
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002485 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002486 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002487 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002488 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002489}
2490
Mike Stump1eb44332009-09-09 15:08:12 +00002491QualType
John McCall33500952010-06-11 00:33:02 +00002492ASTContext::getDependentTemplateSpecializationType(
2493 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002494 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002495 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002496 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00002497 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00002498 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00002499 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2500 ArgCopy.push_back(Args[I].getArgument());
2501 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2502 ArgCopy.size(),
2503 ArgCopy.data());
2504}
2505
2506QualType
2507ASTContext::getDependentTemplateSpecializationType(
2508 ElaboratedTypeKeyword Keyword,
2509 NestedNameSpecifier *NNS,
2510 const IdentifierInfo *Name,
2511 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002512 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00002513 assert((!NNS || NNS->isDependent()) &&
2514 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00002515
Douglas Gregor789b1f62010-02-04 18:10:26 +00002516 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002517 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2518 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002519
2520 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002521 DependentTemplateSpecializationType *T
2522 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002523 if (T)
2524 return QualType(T, 0);
2525
John McCall33500952010-06-11 00:33:02 +00002526 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002527
John McCall33500952010-06-11 00:33:02 +00002528 ElaboratedTypeKeyword CanonKeyword = Keyword;
2529 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2530
2531 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002532 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00002533 for (unsigned I = 0; I != NumArgs; ++I) {
2534 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2535 if (!CanonArgs[I].structurallyEquals(Args[I]))
2536 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002537 }
2538
John McCall33500952010-06-11 00:33:02 +00002539 QualType Canon;
2540 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2541 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2542 Name, NumArgs,
2543 CanonArgs.data());
2544
2545 // Find the insert position again.
2546 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2547 }
2548
2549 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2550 sizeof(TemplateArgument) * NumArgs),
2551 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002552 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002553 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002554 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002555 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002556 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002557}
2558
Douglas Gregorcded4f62011-01-14 17:04:44 +00002559QualType ASTContext::getPackExpansionType(QualType Pattern,
2560 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00002561 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002562 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002563
2564 assert(Pattern->containsUnexpandedParameterPack() &&
2565 "Pack expansions must expand one or more parameter packs");
2566 void *InsertPos = 0;
2567 PackExpansionType *T
2568 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2569 if (T)
2570 return QualType(T, 0);
2571
2572 QualType Canon;
2573 if (!Pattern.isCanonical()) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002574 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002575
2576 // Find the insert position again.
2577 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2578 }
2579
Douglas Gregorcded4f62011-01-14 17:04:44 +00002580 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002581 Types.push_back(T);
2582 PackExpansionTypes.InsertNode(T, InsertPos);
2583 return QualType(T, 0);
2584}
2585
Chris Lattner88cb27a2008-04-07 04:56:42 +00002586/// CmpProtocolNames - Comparison predicate for sorting protocols
2587/// alphabetically.
2588static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2589 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002590 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002591}
2592
John McCallc12c5bb2010-05-15 11:32:37 +00002593static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002594 unsigned NumProtocols) {
2595 if (NumProtocols == 0) return true;
2596
2597 for (unsigned i = 1; i != NumProtocols; ++i)
2598 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2599 return false;
2600 return true;
2601}
2602
2603static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002604 unsigned &NumProtocols) {
2605 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002606
Chris Lattner88cb27a2008-04-07 04:56:42 +00002607 // Sort protocols, keyed by name.
2608 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2609
2610 // Remove duplicates.
2611 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2612 NumProtocols = ProtocolsEnd-Protocols;
2613}
2614
John McCallc12c5bb2010-05-15 11:32:37 +00002615QualType ASTContext::getObjCObjectType(QualType BaseType,
2616 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00002617 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002618 // If the base type is an interface and there aren't any protocols
2619 // to add, then the interface type will do just fine.
2620 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2621 return BaseType;
2622
2623 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002624 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002625 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002626 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002627 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2628 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002629
John McCallc12c5bb2010-05-15 11:32:37 +00002630 // Build the canonical type, which has the canonical base type and
2631 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002632 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002633 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2634 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2635 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002636 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00002637 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002638 unsigned UniqueCount = NumProtocols;
2639
John McCall54e14c42009-10-22 22:37:11 +00002640 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002641 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2642 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002643 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002644 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2645 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002646 }
2647
2648 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002649 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2650 }
2651
2652 unsigned Size = sizeof(ObjCObjectTypeImpl);
2653 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2654 void *Mem = Allocate(Size, TypeAlignment);
2655 ObjCObjectTypeImpl *T =
2656 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2657
2658 Types.push_back(T);
2659 ObjCObjectTypes.InsertNode(T, InsertPos);
2660 return QualType(T, 0);
2661}
2662
2663/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2664/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002665QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002666 llvm::FoldingSetNodeID ID;
2667 ObjCObjectPointerType::Profile(ID, ObjectT);
2668
2669 void *InsertPos = 0;
2670 if (ObjCObjectPointerType *QT =
2671 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2672 return QualType(QT, 0);
2673
2674 // Find the canonical object type.
2675 QualType Canonical;
2676 if (!ObjectT.isCanonical()) {
2677 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2678
2679 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002680 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2681 }
2682
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002683 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002684 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2685 ObjCObjectPointerType *QType =
2686 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002687
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002688 Types.push_back(QType);
2689 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002690 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002691}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002692
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002693/// getObjCInterfaceType - Return the unique reference to the type for the
2694/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad4ba2a172011-01-12 09:06:06 +00002695QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002696 if (Decl->TypeForDecl)
2697 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002698
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002699 // FIXME: redeclarations?
2700 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2701 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2702 Decl->TypeForDecl = T;
2703 Types.push_back(T);
2704 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002705}
2706
Douglas Gregor72564e72009-02-26 23:50:07 +00002707/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2708/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002709/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002710/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002711/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002712QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002713 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002714 if (tofExpr->isTypeDependent()) {
2715 llvm::FoldingSetNodeID ID;
2716 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002717
Douglas Gregorb1975722009-07-30 23:18:24 +00002718 void *InsertPos = 0;
2719 DependentTypeOfExprType *Canon
2720 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2721 if (Canon) {
2722 // We already have a "canonical" version of an identical, dependent
2723 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002724 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002725 QualType((TypeOfExprType*)Canon, 0));
2726 }
2727 else {
2728 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002729 Canon
2730 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002731 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2732 toe = Canon;
2733 }
2734 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002735 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002736 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002737 }
Steve Naroff9752f252007-08-01 18:02:17 +00002738 Types.push_back(toe);
2739 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002740}
2741
Steve Naroff9752f252007-08-01 18:02:17 +00002742/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2743/// TypeOfType AST's. The only motivation to unique these nodes would be
2744/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002745/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002746/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002747QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002748 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002749 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002750 Types.push_back(tot);
2751 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002752}
2753
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002754/// getDecltypeForExpr - Given an expr, will return the decltype for that
2755/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad4ba2a172011-01-12 09:06:06 +00002756static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002757 if (e->isTypeDependent())
2758 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002759
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002760 // If e is an id expression or a class member access, decltype(e) is defined
2761 // as the type of the entity named by e.
2762 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2763 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2764 return VD->getType();
2765 }
2766 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2767 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2768 return FD->getType();
2769 }
2770 // If e is a function call or an invocation of an overloaded operator,
2771 // (parentheses around e are ignored), decltype(e) is defined as the
2772 // return type of that function.
2773 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2774 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002775
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002776 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002777
2778 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002779 // defined as T&, otherwise decltype(e) is defined as T.
John McCall7eb0a9e2010-11-24 05:12:34 +00002780 if (e->isLValue())
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002781 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002782
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002783 return T;
2784}
2785
Anders Carlsson395b4752009-06-24 19:06:50 +00002786/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2787/// DecltypeType AST's. The only motivation to unique these nodes would be
2788/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002789/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002790/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002791QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002792 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00002793
2794 // C++0x [temp.type]p2:
2795 // If an expression e involves a template parameter, decltype(e) denotes a
2796 // unique dependent type. Two such decltype-specifiers refer to the same
2797 // type only if their expressions are equivalent (14.5.6.1).
2798 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002799 llvm::FoldingSetNodeID ID;
2800 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002801
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002802 void *InsertPos = 0;
2803 DependentDecltypeType *Canon
2804 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2805 if (Canon) {
2806 // We already have a "canonical" version of an equivalent, dependent
2807 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002808 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002809 QualType((DecltypeType*)Canon, 0));
2810 }
2811 else {
2812 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002813 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002814 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2815 dt = Canon;
2816 }
2817 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002818 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002819 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002820 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002821 Types.push_back(dt);
2822 return QualType(dt, 0);
2823}
2824
Sean Huntca63c202011-05-24 22:41:36 +00002825/// getUnaryTransformationType - We don't unique these, since the memory
2826/// savings are minimal and these are rare.
2827QualType ASTContext::getUnaryTransformType(QualType BaseType,
2828 QualType UnderlyingType,
2829 UnaryTransformType::UTTKind Kind)
2830 const {
2831 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00002832 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2833 Kind,
2834 UnderlyingType->isDependentType() ?
2835 QualType() : UnderlyingType);
Sean Huntca63c202011-05-24 22:41:36 +00002836 Types.push_back(Ty);
2837 return QualType(Ty, 0);
2838}
2839
Richard Smith483b9f32011-02-21 20:05:19 +00002840/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00002841QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00002842 void *InsertPos = 0;
2843 if (!DeducedType.isNull()) {
2844 // Look in the folding set for an existing type.
2845 llvm::FoldingSetNodeID ID;
2846 AutoType::Profile(ID, DeducedType);
2847 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2848 return QualType(AT, 0);
2849 }
2850
2851 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2852 Types.push_back(AT);
2853 if (InsertPos)
2854 AutoTypes.InsertNode(AT, InsertPos);
2855 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00002856}
2857
Richard Smithad762fc2011-04-14 22:09:26 +00002858/// getAutoDeductType - Get type pattern for deducing against 'auto'.
2859QualType ASTContext::getAutoDeductType() const {
2860 if (AutoDeductTy.isNull())
2861 AutoDeductTy = getAutoType(QualType());
2862 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
2863 return AutoDeductTy;
2864}
2865
2866/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
2867QualType ASTContext::getAutoRRefDeductType() const {
2868 if (AutoRRefDeductTy.isNull())
2869 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
2870 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
2871 return AutoRRefDeductTy;
2872}
2873
Reid Spencer5f016e22007-07-11 17:01:13 +00002874/// getTagDeclType - Return the unique reference to the type for the
2875/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00002876QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00002877 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002878 // FIXME: What is the design on getTagDeclType when it requires casting
2879 // away const? mutable?
2880 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002881}
2882
Mike Stump1eb44332009-09-09 15:08:12 +00002883/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2884/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2885/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002886CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002887 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002888}
2889
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002890/// getSignedWCharType - Return the type of "signed wchar_t".
2891/// Used when in C++, as a GCC extension.
2892QualType ASTContext::getSignedWCharType() const {
2893 // FIXME: derive from "Target" ?
2894 return WCharTy;
2895}
2896
2897/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2898/// Used when in C++, as a GCC extension.
2899QualType ASTContext::getUnsignedWCharType() const {
2900 // FIXME: derive from "Target" ?
2901 return UnsignedIntTy;
2902}
2903
Chris Lattner8b9023b2007-07-13 03:05:23 +00002904/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2905/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2906QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002907 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002908}
2909
Chris Lattnere6327742008-04-02 05:18:44 +00002910//===----------------------------------------------------------------------===//
2911// Type Operators
2912//===----------------------------------------------------------------------===//
2913
Jay Foad4ba2a172011-01-12 09:06:06 +00002914CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00002915 // Push qualifiers into arrays, and then discard any remaining
2916 // qualifiers.
2917 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002918 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00002919 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00002920 QualType Result;
2921 if (isa<ArrayType>(Ty)) {
2922 Result = getArrayDecayedType(QualType(Ty,0));
2923 } else if (isa<FunctionType>(Ty)) {
2924 Result = getPointerType(QualType(Ty, 0));
2925 } else {
2926 Result = QualType(Ty, 0);
2927 }
2928
2929 return CanQualType::CreateUnsafe(Result);
2930}
2931
John McCall62c28c82011-01-18 07:41:22 +00002932QualType ASTContext::getUnqualifiedArrayType(QualType type,
2933 Qualifiers &quals) {
2934 SplitQualType splitType = type.getSplitUnqualifiedType();
2935
2936 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2937 // the unqualified desugared type and then drops it on the floor.
2938 // We then have to strip that sugar back off with
2939 // getUnqualifiedDesugaredType(), which is silly.
2940 const ArrayType *AT =
2941 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2942
2943 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00002944 if (!AT) {
John McCall62c28c82011-01-18 07:41:22 +00002945 quals = splitType.second;
2946 return QualType(splitType.first, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002947 }
2948
John McCall62c28c82011-01-18 07:41:22 +00002949 // Otherwise, recurse on the array's element type.
2950 QualType elementType = AT->getElementType();
2951 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2952
2953 // If that didn't change the element type, AT has no qualifiers, so we
2954 // can just use the results in splitType.
2955 if (elementType == unqualElementType) {
2956 assert(quals.empty()); // from the recursive call
2957 quals = splitType.second;
2958 return QualType(splitType.first, 0);
2959 }
2960
2961 // Otherwise, add in the qualifiers from the outermost type, then
2962 // build the type back up.
2963 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002964
Douglas Gregor9dadd942010-05-17 18:45:21 +00002965 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002966 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00002967 CAT->getSizeModifier(), 0);
2968 }
2969
Douglas Gregor9dadd942010-05-17 18:45:21 +00002970 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002971 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002972 }
2973
Douglas Gregor9dadd942010-05-17 18:45:21 +00002974 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002975 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00002976 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00002977 VAT->getSizeModifier(),
2978 VAT->getIndexTypeCVRQualifiers(),
2979 VAT->getBracketsRange());
2980 }
2981
2982 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00002983 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00002984 DSAT->getSizeModifier(), 0,
2985 SourceRange());
2986}
2987
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002988/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2989/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2990/// they point to and return true. If T1 and T2 aren't pointer types
2991/// or pointer-to-member types, or if they are not similar at this
2992/// level, returns false and leaves T1 and T2 unchanged. Top-level
2993/// qualifiers on T1 and T2 are ignored. This function will typically
2994/// be called in a loop that successively "unwraps" pointer and
2995/// pointer-to-member types to compare them at each level.
2996bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2997 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2998 *T2PtrType = T2->getAs<PointerType>();
2999 if (T1PtrType && T2PtrType) {
3000 T1 = T1PtrType->getPointeeType();
3001 T2 = T2PtrType->getPointeeType();
3002 return true;
3003 }
3004
3005 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3006 *T2MPType = T2->getAs<MemberPointerType>();
3007 if (T1MPType && T2MPType &&
3008 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3009 QualType(T2MPType->getClass(), 0))) {
3010 T1 = T1MPType->getPointeeType();
3011 T2 = T2MPType->getPointeeType();
3012 return true;
3013 }
3014
3015 if (getLangOptions().ObjC1) {
3016 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3017 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3018 if (T1OPType && T2OPType) {
3019 T1 = T1OPType->getPointeeType();
3020 T2 = T2OPType->getPointeeType();
3021 return true;
3022 }
3023 }
3024
3025 // FIXME: Block pointers, too?
3026
3027 return false;
3028}
3029
Jay Foad4ba2a172011-01-12 09:06:06 +00003030DeclarationNameInfo
3031ASTContext::getNameForTemplate(TemplateName Name,
3032 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003033 switch (Name.getKind()) {
3034 case TemplateName::QualifiedTemplate:
3035 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003036 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003037 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3038 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003039
John McCall14606042011-06-30 08:33:18 +00003040 case TemplateName::OverloadedTemplate: {
3041 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3042 // DNInfo work in progress: CHECKME: what about DNLoc?
3043 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3044 }
3045
3046 case TemplateName::DependentTemplate: {
3047 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003048 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003049 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003050 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3051 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003052 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003053 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3054 // DNInfo work in progress: FIXME: source locations?
3055 DeclarationNameLoc DNLoc;
3056 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3057 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3058 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003059 }
3060 }
3061
John McCall14606042011-06-30 08:33:18 +00003062 case TemplateName::SubstTemplateTemplateParm: {
3063 SubstTemplateTemplateParmStorage *subst
3064 = Name.getAsSubstTemplateTemplateParm();
3065 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3066 NameLoc);
3067 }
3068
3069 case TemplateName::SubstTemplateTemplateParmPack: {
3070 SubstTemplateTemplateParmPackStorage *subst
3071 = Name.getAsSubstTemplateTemplateParmPack();
3072 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3073 NameLoc);
3074 }
3075 }
3076
3077 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003078}
3079
Jay Foad4ba2a172011-01-12 09:06:06 +00003080TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003081 switch (Name.getKind()) {
3082 case TemplateName::QualifiedTemplate:
3083 case TemplateName::Template: {
3084 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003085 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003086 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003087 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3088
3089 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003090 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003091 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003092
John McCall14606042011-06-30 08:33:18 +00003093 case TemplateName::OverloadedTemplate:
3094 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003095
John McCall14606042011-06-30 08:33:18 +00003096 case TemplateName::DependentTemplate: {
3097 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3098 assert(DTN && "Non-dependent template names must refer to template decls.");
3099 return DTN->CanonicalTemplateName;
3100 }
3101
3102 case TemplateName::SubstTemplateTemplateParm: {
3103 SubstTemplateTemplateParmStorage *subst
3104 = Name.getAsSubstTemplateTemplateParm();
3105 return getCanonicalTemplateName(subst->getReplacement());
3106 }
3107
3108 case TemplateName::SubstTemplateTemplateParmPack: {
3109 SubstTemplateTemplateParmPackStorage *subst
3110 = Name.getAsSubstTemplateTemplateParmPack();
3111 TemplateTemplateParmDecl *canonParameter
3112 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3113 TemplateArgument canonArgPack
3114 = getCanonicalTemplateArgument(subst->getArgumentPack());
3115 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3116 }
3117 }
3118
3119 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003120}
3121
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003122bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3123 X = getCanonicalTemplateName(X);
3124 Y = getCanonicalTemplateName(Y);
3125 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3126}
3127
Mike Stump1eb44332009-09-09 15:08:12 +00003128TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003129ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003130 switch (Arg.getKind()) {
3131 case TemplateArgument::Null:
3132 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003133
Douglas Gregor1275ae02009-07-28 23:00:59 +00003134 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003135 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003136
Douglas Gregor1275ae02009-07-28 23:00:59 +00003137 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00003138 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003139
Douglas Gregor788cd062009-11-11 01:00:40 +00003140 case TemplateArgument::Template:
3141 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003142
3143 case TemplateArgument::TemplateExpansion:
3144 return TemplateArgument(getCanonicalTemplateName(
3145 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003146 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003147
Douglas Gregor1275ae02009-07-28 23:00:59 +00003148 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00003149 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003150 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003151
Douglas Gregor1275ae02009-07-28 23:00:59 +00003152 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003153 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003154
Douglas Gregor1275ae02009-07-28 23:00:59 +00003155 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003156 if (Arg.pack_size() == 0)
3157 return Arg;
3158
Douglas Gregor910f8002010-11-07 23:05:16 +00003159 TemplateArgument *CanonArgs
3160 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003161 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003162 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003163 AEnd = Arg.pack_end();
3164 A != AEnd; (void)++A, ++Idx)
3165 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003166
Douglas Gregor910f8002010-11-07 23:05:16 +00003167 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003168 }
3169 }
3170
3171 // Silence GCC warning
3172 assert(false && "Unhandled template argument kind");
3173 return TemplateArgument();
3174}
3175
Douglas Gregord57959a2009-03-27 23:10:48 +00003176NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003177ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003178 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003179 return 0;
3180
3181 switch (NNS->getKind()) {
3182 case NestedNameSpecifier::Identifier:
3183 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003184 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003185 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3186 NNS->getAsIdentifier());
3187
3188 case NestedNameSpecifier::Namespace:
3189 // A namespace is canonical; build a nested-name-specifier with
3190 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003191 return NestedNameSpecifier::Create(*this, 0,
3192 NNS->getAsNamespace()->getOriginalNamespace());
3193
3194 case NestedNameSpecifier::NamespaceAlias:
3195 // A namespace is canonical; build a nested-name-specifier with
3196 // this namespace and no prefix.
3197 return NestedNameSpecifier::Create(*this, 0,
3198 NNS->getAsNamespaceAlias()->getNamespace()
3199 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003200
3201 case NestedNameSpecifier::TypeSpec:
3202 case NestedNameSpecifier::TypeSpecWithTemplate: {
3203 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003204
3205 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3206 // break it apart into its prefix and identifier, then reconsititute those
3207 // as the canonical nested-name-specifier. This is required to canonicalize
3208 // a dependent nested-name-specifier involving typedefs of dependent-name
3209 // types, e.g.,
3210 // typedef typename T::type T1;
3211 // typedef typename T1::type T2;
3212 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3213 NestedNameSpecifier *Prefix
3214 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3215 return NestedNameSpecifier::Create(*this, Prefix,
3216 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3217 }
3218
Douglas Gregor643f8432010-11-04 00:14:23 +00003219 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor264bf662010-11-04 00:09:33 +00003220 if (const DependentTemplateSpecializationType *DTST
3221 = T->getAs<DependentTemplateSpecializationType>()) {
3222 NestedNameSpecifier *Prefix
3223 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003224
3225 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3226 Prefix, DTST->getIdentifier(),
3227 DTST->getNumArgs(),
3228 DTST->getArgs());
Douglas Gregor264bf662010-11-04 00:09:33 +00003229 T = getCanonicalType(T);
3230 }
3231
John McCall3b657512011-01-19 10:06:00 +00003232 return NestedNameSpecifier::Create(*this, 0, false,
3233 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003234 }
3235
3236 case NestedNameSpecifier::Global:
3237 // The global specifier is canonical and unique.
3238 return NNS;
3239 }
3240
3241 // Required to silence a GCC warning
3242 return 0;
3243}
3244
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003245
Jay Foad4ba2a172011-01-12 09:06:06 +00003246const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003247 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003248 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003249 // Handle the common positive case fast.
3250 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3251 return AT;
3252 }
Mike Stump1eb44332009-09-09 15:08:12 +00003253
John McCall0953e762009-09-24 19:53:00 +00003254 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003255 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003256 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003257
John McCall0953e762009-09-24 19:53:00 +00003258 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003259 // implements C99 6.7.3p8: "If the specification of an array type includes
3260 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003261
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003262 // If we get here, we either have type qualifiers on the type, or we have
3263 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003264 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003265
John McCall3b657512011-01-19 10:06:00 +00003266 SplitQualType split = T.getSplitDesugaredType();
3267 Qualifiers qs = split.second;
Mike Stump1eb44332009-09-09 15:08:12 +00003268
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003269 // If we have a simple case, just return now.
John McCall3b657512011-01-19 10:06:00 +00003270 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3271 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003272 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003273
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003274 // Otherwise, we have an array and we have qualifiers on it. Push the
3275 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003276 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003277
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003278 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3279 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3280 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003281 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003282 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3283 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3284 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003285 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003286
Mike Stump1eb44332009-09-09 15:08:12 +00003287 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003288 = dyn_cast<DependentSizedArrayType>(ATy))
3289 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003290 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003291 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003292 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003293 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003294 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003295
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003296 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003297 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003298 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003299 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003300 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003301 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003302}
3303
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003304QualType ASTContext::getAdjustedParameterType(QualType T) {
3305 // C99 6.7.5.3p7:
3306 // A declaration of a parameter as "array of type" shall be
3307 // adjusted to "qualified pointer to type", where the type
3308 // qualifiers (if any) are those specified within the [ and ] of
3309 // the array type derivation.
3310 if (T->isArrayType())
3311 return getArrayDecayedType(T);
3312
3313 // C99 6.7.5.3p8:
3314 // A declaration of a parameter as "function returning type"
3315 // shall be adjusted to "pointer to function returning type", as
3316 // in 6.3.2.1.
3317 if (T->isFunctionType())
3318 return getPointerType(T);
3319
3320 return T;
3321}
3322
3323QualType ASTContext::getSignatureParameterType(QualType T) {
3324 T = getVariableArrayDecayedType(T);
3325 T = getAdjustedParameterType(T);
3326 return T.getUnqualifiedType();
3327}
3328
Chris Lattnere6327742008-04-02 05:18:44 +00003329/// getArrayDecayedType - Return the properly qualified result of decaying the
3330/// specified array type to a pointer. This operation is non-trivial when
3331/// handling typedefs etc. The canonical type of "T" must be an array type,
3332/// this returns a pointer to a properly qualified element of the array.
3333///
3334/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003335QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003336 // Get the element type with 'getAsArrayType' so that we don't lose any
3337 // typedefs in the element type of the array. This also handles propagation
3338 // of type qualifiers from the array type into the element type if present
3339 // (C99 6.7.3p8).
3340 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3341 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003342
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003343 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003344
3345 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003346 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003347}
3348
John McCall3b657512011-01-19 10:06:00 +00003349QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3350 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003351}
3352
John McCall3b657512011-01-19 10:06:00 +00003353QualType ASTContext::getBaseElementType(QualType type) const {
3354 Qualifiers qs;
3355 while (true) {
3356 SplitQualType split = type.getSplitDesugaredType();
3357 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3358 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003359
John McCall3b657512011-01-19 10:06:00 +00003360 type = array->getElementType();
3361 qs.addConsistentQualifiers(split.second);
3362 }
Mike Stump1eb44332009-09-09 15:08:12 +00003363
John McCall3b657512011-01-19 10:06:00 +00003364 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003365}
3366
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003367/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003368uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003369ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3370 uint64_t ElementCount = 1;
3371 do {
3372 ElementCount *= CA->getSize().getZExtValue();
3373 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3374 } while (CA);
3375 return ElementCount;
3376}
3377
Reid Spencer5f016e22007-07-11 17:01:13 +00003378/// getFloatingRank - Return a relative rank for floating point types.
3379/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003380static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003381 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003382 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003383
John McCall183700f2009-09-21 23:43:11 +00003384 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3385 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00003386 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00003387 case BuiltinType::Float: return FloatRank;
3388 case BuiltinType::Double: return DoubleRank;
3389 case BuiltinType::LongDouble: return LongDoubleRank;
3390 }
3391}
3392
Mike Stump1eb44332009-09-09 15:08:12 +00003393/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3394/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003395/// 'typeDomain' is a real floating point or complex type.
3396/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003397QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3398 QualType Domain) const {
3399 FloatingRank EltRank = getFloatingRank(Size);
3400 if (Domain->isComplexType()) {
3401 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00003402 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00003403 case FloatRank: return FloatComplexTy;
3404 case DoubleRank: return DoubleComplexTy;
3405 case LongDoubleRank: return LongDoubleComplexTy;
3406 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003407 }
Chris Lattner1361b112008-04-06 23:58:54 +00003408
3409 assert(Domain->isRealFloatingType() && "Unknown domain!");
3410 switch (EltRank) {
3411 default: assert(0 && "getFloatingRank(): illegal value for rank");
3412 case FloatRank: return FloatTy;
3413 case DoubleRank: return DoubleTy;
3414 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003415 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003416}
3417
Chris Lattner7cfeb082008-04-06 23:55:33 +00003418/// getFloatingTypeOrder - Compare the rank of the two specified floating
3419/// point types, ignoring the domain of the type (i.e. 'double' ==
3420/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003421/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003422int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003423 FloatingRank LHSR = getFloatingRank(LHS);
3424 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003425
Chris Lattnera75cea32008-04-06 23:38:49 +00003426 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003427 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003428 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003429 return 1;
3430 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003431}
3432
Chris Lattnerf52ab252008-04-06 22:59:24 +00003433/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3434/// routine will assert if passed a built-in type that isn't an integer or enum,
3435/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003436unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003437 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCallf4c73712011-01-19 06:33:43 +00003438 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00003439 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00003440
Chris Lattner3f59c972010-12-25 23:25:43 +00003441 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3442 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmana3426752009-07-05 23:44:27 +00003443 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3444
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003445 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3446 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3447
3448 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3449 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3450
Chris Lattnerf52ab252008-04-06 22:59:24 +00003451 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00003452 default: assert(0 && "getIntegerRank(): not a built-in integer");
3453 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003454 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003455 case BuiltinType::Char_S:
3456 case BuiltinType::Char_U:
3457 case BuiltinType::SChar:
3458 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003459 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003460 case BuiltinType::Short:
3461 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003462 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003463 case BuiltinType::Int:
3464 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003465 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003466 case BuiltinType::Long:
3467 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003468 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003469 case BuiltinType::LongLong:
3470 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003471 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003472 case BuiltinType::Int128:
3473 case BuiltinType::UInt128:
3474 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003475 }
3476}
3477
Eli Friedman04e83572009-08-20 04:21:42 +00003478/// \brief Whether this is a promotable bitfield reference according
3479/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3480///
3481/// \returns the type this bit-field will promote to, or NULL if no
3482/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00003483QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003484 if (E->isTypeDependent() || E->isValueDependent())
3485 return QualType();
3486
Eli Friedman04e83572009-08-20 04:21:42 +00003487 FieldDecl *Field = E->getBitField();
3488 if (!Field)
3489 return QualType();
3490
3491 QualType FT = Field->getType();
3492
3493 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3494 uint64_t BitWidth = BitWidthAP.getZExtValue();
3495 uint64_t IntSize = getTypeSize(IntTy);
3496 // GCC extension compatibility: if the bit-field size is less than or equal
3497 // to the size of int, it gets promoted no matter what its type is.
3498 // For instance, unsigned long bf : 4 gets promoted to signed int.
3499 if (BitWidth < IntSize)
3500 return IntTy;
3501
3502 if (BitWidth == IntSize)
3503 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3504
3505 // Types bigger than int are not subject to promotions, and therefore act
3506 // like the base type.
3507 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3508 // is ridiculous.
3509 return QualType();
3510}
3511
Eli Friedmana95d7572009-08-19 07:44:53 +00003512/// getPromotedIntegerType - Returns the type that Promotable will
3513/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3514/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003515QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003516 assert(!Promotable.isNull());
3517 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003518 if (const EnumType *ET = Promotable->getAs<EnumType>())
3519 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00003520 if (Promotable->isSignedIntegerType())
3521 return IntTy;
3522 uint64_t PromotableSize = getTypeSize(Promotable);
3523 uint64_t IntSize = getTypeSize(IntTy);
3524 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3525 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3526}
3527
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003528/// \brief Recurses in pointer/array types until it finds an objc retainable
3529/// type and returns its ownership.
3530Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3531 while (!T.isNull()) {
3532 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3533 return T.getObjCLifetime();
3534 if (T->isArrayType())
3535 T = getBaseElementType(T);
3536 else if (const PointerType *PT = T->getAs<PointerType>())
3537 T = PT->getPointeeType();
3538 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00003539 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003540 else
3541 break;
3542 }
3543
3544 return Qualifiers::OCL_None;
3545}
3546
Mike Stump1eb44332009-09-09 15:08:12 +00003547/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003548/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003549/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003550int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00003551 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3552 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003553 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003554
Chris Lattnerf52ab252008-04-06 22:59:24 +00003555 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3556 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003557
Chris Lattner7cfeb082008-04-06 23:55:33 +00003558 unsigned LHSRank = getIntegerRank(LHSC);
3559 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003560
Chris Lattner7cfeb082008-04-06 23:55:33 +00003561 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3562 if (LHSRank == RHSRank) return 0;
3563 return LHSRank > RHSRank ? 1 : -1;
3564 }
Mike Stump1eb44332009-09-09 15:08:12 +00003565
Chris Lattner7cfeb082008-04-06 23:55:33 +00003566 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3567 if (LHSUnsigned) {
3568 // If the unsigned [LHS] type is larger, return it.
3569 if (LHSRank >= RHSRank)
3570 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003571
Chris Lattner7cfeb082008-04-06 23:55:33 +00003572 // If the signed type can represent all values of the unsigned type, it
3573 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003574 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003575 return -1;
3576 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003577
Chris Lattner7cfeb082008-04-06 23:55:33 +00003578 // If the unsigned [RHS] type is larger, return it.
3579 if (RHSRank >= LHSRank)
3580 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003581
Chris Lattner7cfeb082008-04-06 23:55:33 +00003582 // If the signed type can represent all values of the unsigned type, it
3583 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003584 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003585 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003586}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003587
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003588static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003589CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3590 DeclContext *DC, IdentifierInfo *Id) {
3591 SourceLocation Loc;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003592 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003593 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003594 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003595 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003596}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003597
Mike Stump1eb44332009-09-09 15:08:12 +00003598// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003599QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003600 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003601 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003602 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003603 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003604 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003605
Anders Carlssonf06273f2007-11-19 00:25:30 +00003606 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003607
Anders Carlsson71993dd2007-08-17 05:31:46 +00003608 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003609 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003610 // int flags;
3611 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003612 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003613 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003614 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003615 FieldTypes[3] = LongTy;
3616
Anders Carlsson71993dd2007-08-17 05:31:46 +00003617 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003618 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003619 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003620 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00003621 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003622 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003623 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003624 /*Mutable=*/false,
3625 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003626 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003627 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003628 }
3629
Douglas Gregor838db382010-02-11 01:19:42 +00003630 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003631 }
Mike Stump1eb44332009-09-09 15:08:12 +00003632
Anders Carlsson71993dd2007-08-17 05:31:46 +00003633 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003634}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003635
Douglas Gregor319ac892009-04-23 22:29:11 +00003636void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003637 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003638 assert(Rec && "Invalid CFConstantStringType");
3639 CFConstantStringTypeDecl = Rec->getDecl();
3640}
3641
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003642// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003643QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003644 if (!NSConstantStringTypeDecl) {
3645 NSConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003646 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003647 &Idents.get("__builtin_NSString"));
3648 NSConstantStringTypeDecl->startDefinition();
3649
3650 QualType FieldTypes[3];
3651
3652 // const int *isa;
3653 FieldTypes[0] = getPointerType(IntTy.withConst());
3654 // const char *str;
3655 FieldTypes[1] = getPointerType(CharTy.withConst());
3656 // unsigned int length;
3657 FieldTypes[2] = UnsignedIntTy;
3658
3659 // Create fields
3660 for (unsigned i = 0; i < 3; ++i) {
3661 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003662 SourceLocation(),
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003663 SourceLocation(), 0,
3664 FieldTypes[i], /*TInfo=*/0,
3665 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003666 /*Mutable=*/false,
3667 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003668 Field->setAccess(AS_public);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003669 NSConstantStringTypeDecl->addDecl(Field);
3670 }
3671
3672 NSConstantStringTypeDecl->completeDefinition();
3673 }
3674
3675 return getTagDeclType(NSConstantStringTypeDecl);
3676}
3677
3678void ASTContext::setNSConstantStringType(QualType T) {
3679 const RecordType *Rec = T->getAs<RecordType>();
3680 assert(Rec && "Invalid NSConstantStringType");
3681 NSConstantStringTypeDecl = Rec->getDecl();
3682}
3683
Jay Foad4ba2a172011-01-12 09:06:06 +00003684QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003685 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003686 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003687 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003688 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00003689 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003690
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003691 QualType FieldTypes[] = {
3692 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00003693 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003694 getPointerType(UnsignedLongTy),
3695 getConstantArrayType(UnsignedLongTy,
3696 llvm::APInt(32, 5), ArrayType::Normal, 0)
3697 };
Mike Stump1eb44332009-09-09 15:08:12 +00003698
Douglas Gregor44b43212008-12-11 16:49:14 +00003699 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003700 FieldDecl *Field = FieldDecl::Create(*this,
3701 ObjCFastEnumerationStateTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003702 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00003703 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003704 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003705 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003706 /*Mutable=*/false,
3707 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003708 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003709 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003710 }
Mike Stump1eb44332009-09-09 15:08:12 +00003711
Douglas Gregor838db382010-02-11 01:19:42 +00003712 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003713 }
Mike Stump1eb44332009-09-09 15:08:12 +00003714
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003715 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3716}
3717
Jay Foad4ba2a172011-01-12 09:06:06 +00003718QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00003719 if (BlockDescriptorType)
3720 return getTagDeclType(BlockDescriptorType);
3721
3722 RecordDecl *T;
3723 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003724 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003725 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003726 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003727
3728 QualType FieldTypes[] = {
3729 UnsignedLongTy,
3730 UnsignedLongTy,
3731 };
3732
3733 const char *FieldNames[] = {
3734 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003735 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003736 };
3737
3738 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003739 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003740 SourceLocation(),
3741 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003742 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003743 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003744 /*Mutable=*/false,
3745 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003746 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003747 T->addDecl(Field);
3748 }
3749
Douglas Gregor838db382010-02-11 01:19:42 +00003750 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003751
3752 BlockDescriptorType = T;
3753
3754 return getTagDeclType(BlockDescriptorType);
3755}
3756
3757void ASTContext::setBlockDescriptorType(QualType T) {
3758 const RecordType *Rec = T->getAs<RecordType>();
3759 assert(Rec && "Invalid BlockDescriptorType");
3760 BlockDescriptorType = Rec->getDecl();
3761}
3762
Jay Foad4ba2a172011-01-12 09:06:06 +00003763QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00003764 if (BlockDescriptorExtendedType)
3765 return getTagDeclType(BlockDescriptorExtendedType);
3766
3767 RecordDecl *T;
3768 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003769 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003770 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003771 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003772
3773 QualType FieldTypes[] = {
3774 UnsignedLongTy,
3775 UnsignedLongTy,
3776 getPointerType(VoidPtrTy),
3777 getPointerType(VoidPtrTy)
3778 };
3779
3780 const char *FieldNames[] = {
3781 "reserved",
3782 "Size",
3783 "CopyFuncPtr",
3784 "DestroyFuncPtr"
3785 };
3786
3787 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003788 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00003789 SourceLocation(),
3790 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003791 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003792 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003793 /*Mutable=*/false,
3794 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003795 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003796 T->addDecl(Field);
3797 }
3798
Douglas Gregor838db382010-02-11 01:19:42 +00003799 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003800
3801 BlockDescriptorExtendedType = T;
3802
3803 return getTagDeclType(BlockDescriptorExtendedType);
3804}
3805
3806void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3807 const RecordType *Rec = T->getAs<RecordType>();
3808 assert(Rec && "Invalid BlockDescriptorType");
3809 BlockDescriptorExtendedType = Rec->getDecl();
3810}
3811
Jay Foad4ba2a172011-01-12 09:06:06 +00003812bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCallf85e1932011-06-15 23:02:42 +00003813 if (Ty->isObjCRetainableType())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003814 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003815 if (getLangOptions().CPlusPlus) {
3816 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3817 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Huntffe37fd2011-05-25 20:50:04 +00003818 return RD->hasConstCopyConstructor();
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003819
3820 }
3821 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003822 return false;
3823}
3824
Jay Foad4ba2a172011-01-12 09:06:06 +00003825QualType
Chris Lattner5f9e2722011-07-23 10:55:15 +00003826ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003827 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003828 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003829 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003830 // unsigned int __flags;
3831 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003832 // void *__copy_helper; // as needed
3833 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003834 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003835 // } *
3836
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003837 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3838
3839 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003840 llvm::SmallString<36> Name;
3841 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3842 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003843 RecordDecl *T;
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003844 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003845 T->startDefinition();
3846 QualType Int32Ty = IntTy;
3847 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3848 QualType FieldTypes[] = {
3849 getPointerType(VoidPtrTy),
3850 getPointerType(getTagDeclType(T)),
3851 Int32Ty,
3852 Int32Ty,
3853 getPointerType(VoidPtrTy),
3854 getPointerType(VoidPtrTy),
3855 Ty
3856 };
3857
Chris Lattner5f9e2722011-07-23 10:55:15 +00003858 StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003859 "__isa",
3860 "__forwarding",
3861 "__flags",
3862 "__size",
3863 "__copy_helper",
3864 "__destroy_helper",
3865 DeclName,
3866 };
3867
3868 for (size_t i = 0; i < 7; ++i) {
3869 if (!HasCopyAndDispose && i >=4 && i <= 5)
3870 continue;
3871 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003872 SourceLocation(),
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003873 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003874 FieldTypes[i], /*TInfo=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003875 /*BitWidth=*/0, /*Mutable=*/false,
3876 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003877 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003878 T->addDecl(Field);
3879 }
3880
Douglas Gregor838db382010-02-11 01:19:42 +00003881 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003882
3883 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003884}
3885
Douglas Gregor319ac892009-04-23 22:29:11 +00003886void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003887 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003888 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3889 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3890}
3891
Anders Carlssone8c49532007-10-29 06:33:42 +00003892// This returns true if a type has been typedefed to BOOL:
3893// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003894static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003895 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003896 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3897 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003898
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003899 return false;
3900}
3901
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003902/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003903/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00003904CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00003905 if (!type->isIncompleteArrayType() && type->isIncompleteType())
3906 return CharUnits::Zero();
3907
Ken Dyck199c3d62010-01-11 17:06:35 +00003908 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003909
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003910 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003911 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003912 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003913 // Treat arrays as pointers, since that's how they're passed in.
3914 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003915 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003916 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003917}
3918
3919static inline
3920std::string charUnitsToString(const CharUnits &CU) {
3921 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003922}
3923
John McCall6b5a61b2011-02-07 10:33:21 +00003924/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003925/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00003926std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3927 std::string S;
3928
David Chisnall5e530af2009-11-17 19:33:30 +00003929 const BlockDecl *Decl = Expr->getBlockDecl();
3930 QualType BlockTy =
3931 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3932 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003933 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003934 // Compute size of all parameters.
3935 // Start with computing size of a pointer in number of bytes.
3936 // FIXME: There might(should) be a better way of doing this computation!
3937 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003938 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3939 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003940 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003941 E = Decl->param_end(); PI != E; ++PI) {
3942 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003943 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003944 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003945 ParmOffset += sz;
3946 }
3947 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003948 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003949 // Block pointer and offset.
3950 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00003951
3952 // Argument types.
3953 ParmOffset = PtrSize;
3954 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3955 Decl->param_end(); PI != E; ++PI) {
3956 ParmVarDecl *PVDecl = *PI;
3957 QualType PType = PVDecl->getOriginalType();
3958 if (const ArrayType *AT =
3959 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3960 // Use array's original type only if it has known number of
3961 // elements.
3962 if (!isa<ConstantArrayType>(AT))
3963 PType = PVDecl->getType();
3964 } else if (PType->isFunctionType())
3965 PType = PVDecl->getType();
3966 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003967 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003968 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003969 }
John McCall6b5a61b2011-02-07 10:33:21 +00003970
3971 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00003972}
3973
Douglas Gregorf968d832011-05-27 01:19:52 +00003974bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00003975 std::string& S) {
3976 // Encode result type.
3977 getObjCEncodingForType(Decl->getResultType(), S);
3978 CharUnits ParmOffset;
3979 // Compute size of all parameters.
3980 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3981 E = Decl->param_end(); PI != E; ++PI) {
3982 QualType PType = (*PI)->getType();
3983 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00003984 if (sz.isZero())
3985 return true;
3986
David Chisnall5389f482010-12-30 14:05:53 +00003987 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00003988 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00003989 ParmOffset += sz;
3990 }
3991 S += charUnitsToString(ParmOffset);
3992 ParmOffset = CharUnits::Zero();
3993
3994 // Argument types.
3995 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3996 E = Decl->param_end(); PI != E; ++PI) {
3997 ParmVarDecl *PVDecl = *PI;
3998 QualType PType = PVDecl->getOriginalType();
3999 if (const ArrayType *AT =
4000 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4001 // Use array's original type only if it has known number of
4002 // elements.
4003 if (!isa<ConstantArrayType>(AT))
4004 PType = PVDecl->getType();
4005 } else if (PType->isFunctionType())
4006 PType = PVDecl->getType();
4007 getObjCEncodingForType(PType, S);
4008 S += charUnitsToString(ParmOffset);
4009 ParmOffset += getObjCEncodingTypeSize(PType);
4010 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004011
4012 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004013}
4014
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004015/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004016/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004017bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00004018 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004019 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004020 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004021 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004022 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004023 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004024 // Compute size of all parameters.
4025 // Start with computing size of a pointer in number of bytes.
4026 // FIXME: There might(should) be a better way of doing this computation!
4027 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004028 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004029 // The first two arguments (self and _cmd) are pointers; account for
4030 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004031 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00004032 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004033 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004034 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004035 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004036 if (sz.isZero())
4037 return true;
4038
Ken Dyck199c3d62010-01-11 17:06:35 +00004039 assert (sz.isPositive() &&
4040 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004041 ParmOffset += sz;
4042 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004043 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004044 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004045 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004046
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004047 // Argument types.
4048 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00004049 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004050 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004051 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004052 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004053 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004054 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4055 // Use array's original type only if it has known number of
4056 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004057 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004058 PType = PVDecl->getType();
4059 } else if (PType->isFunctionType())
4060 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004061 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004062 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004063 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004064 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004065 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004066 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004067 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004068
4069 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004070}
4071
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004072/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004073/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004074/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4075/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004076/// Property attributes are stored as a comma-delimited C string. The simple
4077/// attributes readonly and bycopy are encoded as single characters. The
4078/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4079/// encoded as single characters, followed by an identifier. Property types
4080/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004081/// these attributes are defined by the following enumeration:
4082/// @code
4083/// enum PropertyAttributes {
4084/// kPropertyReadOnly = 'R', // property is read-only.
4085/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4086/// kPropertyByref = '&', // property is a reference to the value last assigned
4087/// kPropertyDynamic = 'D', // property is dynamic
4088/// kPropertyGetter = 'G', // followed by getter selector name
4089/// kPropertySetter = 'S', // followed by setter selector name
4090/// kPropertyInstanceVariable = 'V' // followed by instance variable name
4091/// kPropertyType = 't' // followed by old-style type encoding.
4092/// kPropertyWeak = 'W' // 'weak' property
4093/// kPropertyStrong = 'P' // property GC'able
4094/// kPropertyNonAtomic = 'N' // property non-atomic
4095/// };
4096/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004097void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004098 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004099 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004100 // Collect information from the property implementation decl(s).
4101 bool Dynamic = false;
4102 ObjCPropertyImplDecl *SynthesizePID = 0;
4103
4104 // FIXME: Duplicated code due to poor abstraction.
4105 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004106 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004107 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4108 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004109 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004110 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004111 ObjCPropertyImplDecl *PID = *i;
4112 if (PID->getPropertyDecl() == PD) {
4113 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4114 Dynamic = true;
4115 } else {
4116 SynthesizePID = PID;
4117 }
4118 }
4119 }
4120 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004121 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004122 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004123 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004124 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004125 ObjCPropertyImplDecl *PID = *i;
4126 if (PID->getPropertyDecl() == PD) {
4127 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4128 Dynamic = true;
4129 } else {
4130 SynthesizePID = PID;
4131 }
4132 }
Mike Stump1eb44332009-09-09 15:08:12 +00004133 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004134 }
4135 }
4136
4137 // FIXME: This is not very efficient.
4138 S = "T";
4139
4140 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004141 // GCC has some special rules regarding encoding of properties which
4142 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004143 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004144 true /* outermost type */,
4145 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004146
4147 if (PD->isReadOnly()) {
4148 S += ",R";
4149 } else {
4150 switch (PD->getSetterKind()) {
4151 case ObjCPropertyDecl::Assign: break;
4152 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004153 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004154 }
4155 }
4156
4157 // It really isn't clear at all what this means, since properties
4158 // are "dynamic by default".
4159 if (Dynamic)
4160 S += ",D";
4161
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004162 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4163 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004164
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004165 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4166 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004167 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004168 }
4169
4170 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4171 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004172 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004173 }
4174
4175 if (SynthesizePID) {
4176 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4177 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004178 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004179 }
4180
4181 // FIXME: OBJCGC: weak & strong
4182}
4183
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004184/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004185/// Another legacy compatibility encoding: 32-bit longs are encoded as
4186/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004187/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4188///
4189void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004190 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004191 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004192 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004193 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004194 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004195 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004196 PointeeTy = IntTy;
4197 }
4198 }
4199}
4200
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004201void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004202 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004203 // We follow the behavior of gcc, expanding structures which are
4204 // directly pointed to, and expanding embedded structures. Note that
4205 // these rules are sufficient to prevent recursive encoding of the
4206 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004207 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004208 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004209}
4210
David Chisnall64fd7e82010-06-04 01:10:52 +00004211static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4212 switch (T->getAs<BuiltinType>()->getKind()) {
4213 default: assert(0 && "Unhandled builtin type kind");
4214 case BuiltinType::Void: return 'v';
4215 case BuiltinType::Bool: return 'B';
4216 case BuiltinType::Char_U:
4217 case BuiltinType::UChar: return 'C';
4218 case BuiltinType::UShort: return 'S';
4219 case BuiltinType::UInt: return 'I';
4220 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00004221 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004222 case BuiltinType::UInt128: return 'T';
4223 case BuiltinType::ULongLong: return 'Q';
4224 case BuiltinType::Char_S:
4225 case BuiltinType::SChar: return 'c';
4226 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004227 case BuiltinType::WChar_S:
4228 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004229 case BuiltinType::Int: return 'i';
4230 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00004231 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004232 case BuiltinType::LongLong: return 'q';
4233 case BuiltinType::Int128: return 't';
4234 case BuiltinType::Float: return 'f';
4235 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004236 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004237 }
4238}
4239
Jay Foad4ba2a172011-01-12 09:06:06 +00004240static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004241 QualType T, const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004242 const Expr *E = FD->getBitWidth();
4243 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004244 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004245 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4246 // The GNU runtime requires more information; bitfields are encoded as b,
4247 // then the offset (in bits) of the first element, then the type of the
4248 // bitfield, then the size in bits. For example, in this structure:
4249 //
4250 // struct
4251 // {
4252 // int integer;
4253 // int flags:2;
4254 // };
4255 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4256 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4257 // information is not especially sensible, but we're stuck with it for
4258 // compatibility with GCC, although providing it breaks anything that
4259 // actually uses runtime introspection and wants to work on both runtimes...
4260 if (!Ctx->getLangOptions().NeXTRuntime) {
4261 const RecordDecl *RD = FD->getParent();
4262 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004263 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
David Chisnallc7ff82c2010-12-26 20:12:30 +00004264 if (T->isEnumeralType())
4265 S += 'i';
4266 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004267 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004268 }
4269 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004270 S += llvm::utostr(N);
4271}
4272
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004273// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004274void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4275 bool ExpandPointedToStructures,
4276 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004277 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004278 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004279 bool EncodingProperty,
4280 bool StructField) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004281 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004282 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004283 return EncodeBitField(this, S, T, FD);
4284 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004285 return;
4286 }
Mike Stump1eb44332009-09-09 15:08:12 +00004287
John McCall183700f2009-09-21 23:43:11 +00004288 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004289 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004290 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004291 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004292 return;
4293 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004294
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004295 // encoding for pointer or r3eference types.
4296 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004297 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004298 if (PT->isObjCSelType()) {
4299 S += ':';
4300 return;
4301 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004302 PointeeTy = PT->getPointeeType();
4303 }
4304 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4305 PointeeTy = RT->getPointeeType();
4306 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004307 bool isReadOnly = false;
4308 // For historical/compatibility reasons, the read-only qualifier of the
4309 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4310 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004311 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004312 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004313 if (OutermostType && T.isConstQualified()) {
4314 isReadOnly = true;
4315 S += 'r';
4316 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004317 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004318 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004319 while (P->getAs<PointerType>())
4320 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004321 if (P.isConstQualified()) {
4322 isReadOnly = true;
4323 S += 'r';
4324 }
4325 }
4326 if (isReadOnly) {
4327 // Another legacy compatibility encoding. Some ObjC qualifier and type
4328 // combinations need to be rearranged.
4329 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00004330 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00004331 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004332 }
Mike Stump1eb44332009-09-09 15:08:12 +00004333
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004334 if (PointeeTy->isCharType()) {
4335 // char pointer types should be encoded as '*' unless it is a
4336 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004337 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004338 S += '*';
4339 return;
4340 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004341 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004342 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4343 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4344 S += '#';
4345 return;
4346 }
4347 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4348 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4349 S += '@';
4350 return;
4351 }
4352 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004353 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004354 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004355 getLegacyIntegralTypeEncoding(PointeeTy);
4356
Mike Stump1eb44332009-09-09 15:08:12 +00004357 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004358 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004359 return;
4360 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004361
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004362 if (const ArrayType *AT =
4363 // Ignore type qualifiers etc.
4364 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004365 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004366 // Incomplete arrays are encoded as a pointer to the array element.
4367 S += '^';
4368
Mike Stump1eb44332009-09-09 15:08:12 +00004369 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004370 false, ExpandStructures, FD);
4371 } else {
4372 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004373
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004374 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4375 if (getTypeSize(CAT->getElementType()) == 0)
4376 S += '0';
4377 else
4378 S += llvm::utostr(CAT->getSize().getZExtValue());
4379 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00004380 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004381 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4382 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00004383 S += '0';
4384 }
Mike Stump1eb44332009-09-09 15:08:12 +00004385
4386 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004387 false, ExpandStructures, FD);
4388 S += ']';
4389 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004390 return;
4391 }
Mike Stump1eb44332009-09-09 15:08:12 +00004392
John McCall183700f2009-09-21 23:43:11 +00004393 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004394 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004395 return;
4396 }
Mike Stump1eb44332009-09-09 15:08:12 +00004397
Ted Kremenek6217b802009-07-29 21:53:49 +00004398 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004399 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004400 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004401 // Anonymous structures print as '?'
4402 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4403 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004404 if (ClassTemplateSpecializationDecl *Spec
4405 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4406 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4407 std::string TemplateArgsStr
4408 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004409 TemplateArgs.data(),
4410 TemplateArgs.size(),
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004411 (*this).PrintingPolicy);
4412
4413 S += TemplateArgsStr;
4414 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004415 } else {
4416 S += '?';
4417 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004418 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004419 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004420 if (!RDecl->isUnion()) {
4421 getObjCEncodingForStructureImpl(RDecl, S, FD);
4422 } else {
4423 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4424 FieldEnd = RDecl->field_end();
4425 Field != FieldEnd; ++Field) {
4426 if (FD) {
4427 S += '"';
4428 S += Field->getNameAsString();
4429 S += '"';
4430 }
Mike Stump1eb44332009-09-09 15:08:12 +00004431
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004432 // Special case bit-fields.
4433 if (Field->isBitField()) {
4434 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4435 (*Field));
4436 } else {
4437 QualType qt = Field->getType();
4438 getLegacyIntegralTypeEncoding(qt);
4439 getObjCEncodingForTypeImpl(qt, S, false, true,
4440 FD, /*OutermostType*/false,
4441 /*EncodingProperty*/false,
4442 /*StructField*/true);
4443 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004444 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004445 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004446 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004447 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004448 return;
4449 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004450
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004451 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004452 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004453 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004454 else
4455 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004456 return;
4457 }
Mike Stump1eb44332009-09-09 15:08:12 +00004458
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004459 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004460 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004461 return;
4462 }
Mike Stump1eb44332009-09-09 15:08:12 +00004463
John McCallc12c5bb2010-05-15 11:32:37 +00004464 // Ignore protocol qualifiers when mangling at this level.
4465 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4466 T = OT->getBaseType();
4467
John McCall0953e762009-09-24 19:53:00 +00004468 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004469 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004470 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004471 S += '{';
4472 const IdentifierInfo *II = OI->getIdentifier();
4473 S += II->getName();
4474 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00004475 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004476 DeepCollectObjCIvars(OI, true, Ivars);
4477 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00004478 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004479 if (Field->isBitField())
4480 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004481 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004482 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004483 }
4484 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004485 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004486 }
Mike Stump1eb44332009-09-09 15:08:12 +00004487
John McCall183700f2009-09-21 23:43:11 +00004488 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004489 if (OPT->isObjCIdType()) {
4490 S += '@';
4491 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004492 }
Mike Stump1eb44332009-09-09 15:08:12 +00004493
Steve Naroff27d20a22009-10-28 22:03:49 +00004494 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4495 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4496 // Since this is a binary compatibility issue, need to consult with runtime
4497 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004498 S += '#';
4499 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004500 }
Mike Stump1eb44332009-09-09 15:08:12 +00004501
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004502 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004503 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004504 ExpandPointedToStructures,
4505 ExpandStructures, FD);
4506 if (FD || EncodingProperty) {
4507 // Note that we do extended encoding of protocol qualifer list
4508 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004509 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004510 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4511 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004512 S += '<';
4513 S += (*I)->getNameAsString();
4514 S += '>';
4515 }
4516 S += '"';
4517 }
4518 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004519 }
Mike Stump1eb44332009-09-09 15:08:12 +00004520
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004521 QualType PointeeTy = OPT->getPointeeType();
4522 if (!EncodingProperty &&
4523 isa<TypedefType>(PointeeTy.getTypePtr())) {
4524 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004525 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004526 // {...};
4527 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004528 getObjCEncodingForTypeImpl(PointeeTy, S,
4529 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004530 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004531 return;
4532 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004533
4534 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00004535 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004536 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004537 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004538 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4539 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004540 S += '<';
4541 S += (*I)->getNameAsString();
4542 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004543 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004544 S += '"';
4545 }
4546 return;
4547 }
Mike Stump1eb44332009-09-09 15:08:12 +00004548
John McCall532ec7b2010-05-17 23:56:34 +00004549 // gcc just blithely ignores member pointers.
4550 // TODO: maybe there should be a mangling for these
4551 if (T->getAs<MemberPointerType>())
4552 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004553
4554 if (T->isVectorType()) {
4555 // This matches gcc's encoding, even though technically it is
4556 // insufficient.
4557 // FIXME. We should do a better job than gcc.
4558 return;
4559 }
4560
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004561 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004562}
4563
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004564void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4565 std::string &S,
4566 const FieldDecl *FD,
4567 bool includeVBases) const {
4568 assert(RDecl && "Expected non-null RecordDecl");
4569 assert(!RDecl->isUnion() && "Should not be called for unions");
4570 if (!RDecl->getDefinition())
4571 return;
4572
4573 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4574 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4575 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4576
4577 if (CXXRec) {
4578 for (CXXRecordDecl::base_class_iterator
4579 BI = CXXRec->bases_begin(),
4580 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4581 if (!BI->isVirtual()) {
4582 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004583 if (base->isEmpty())
4584 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004585 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4586 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4587 std::make_pair(offs, base));
4588 }
4589 }
4590 }
4591
4592 unsigned i = 0;
4593 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4594 FieldEnd = RDecl->field_end();
4595 Field != FieldEnd; ++Field, ++i) {
4596 uint64_t offs = layout.getFieldOffset(i);
4597 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4598 std::make_pair(offs, *Field));
4599 }
4600
4601 if (CXXRec && includeVBases) {
4602 for (CXXRecordDecl::base_class_iterator
4603 BI = CXXRec->vbases_begin(),
4604 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4605 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004606 if (base->isEmpty())
4607 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004608 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
4609 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4610 std::make_pair(offs, base));
4611 }
4612 }
4613
4614 CharUnits size;
4615 if (CXXRec) {
4616 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4617 } else {
4618 size = layout.getSize();
4619 }
4620
4621 uint64_t CurOffs = 0;
4622 std::multimap<uint64_t, NamedDecl *>::iterator
4623 CurLayObj = FieldOrBaseOffsets.begin();
4624
4625 if (CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) {
4626 assert(CXXRec && CXXRec->isDynamicClass() &&
4627 "Offset 0 was empty but no VTable ?");
4628 if (FD) {
4629 S += "\"_vptr$";
4630 std::string recname = CXXRec->getNameAsString();
4631 if (recname.empty()) recname = "?";
4632 S += recname;
4633 S += '"';
4634 }
4635 S += "^^?";
4636 CurOffs += getTypeSize(VoidPtrTy);
4637 }
4638
4639 if (!RDecl->hasFlexibleArrayMember()) {
4640 // Mark the end of the structure.
4641 uint64_t offs = toBits(size);
4642 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4643 std::make_pair(offs, (NamedDecl*)0));
4644 }
4645
4646 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4647 assert(CurOffs <= CurLayObj->first);
4648
4649 if (CurOffs < CurLayObj->first) {
4650 uint64_t padding = CurLayObj->first - CurOffs;
4651 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4652 // packing/alignment of members is different that normal, in which case
4653 // the encoding will be out-of-sync with the real layout.
4654 // If the runtime switches to just consider the size of types without
4655 // taking into account alignment, we could make padding explicit in the
4656 // encoding (e.g. using arrays of chars). The encoding strings would be
4657 // longer then though.
4658 CurOffs += padding;
4659 }
4660
4661 NamedDecl *dcl = CurLayObj->second;
4662 if (dcl == 0)
4663 break; // reached end of structure.
4664
4665 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4666 // We expand the bases without their virtual bases since those are going
4667 // in the initial structure. Note that this differs from gcc which
4668 // expands virtual bases each time one is encountered in the hierarchy,
4669 // making the encoding type bigger than it really is.
4670 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004671 assert(!base->isEmpty());
4672 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004673 } else {
4674 FieldDecl *field = cast<FieldDecl>(dcl);
4675 if (FD) {
4676 S += '"';
4677 S += field->getNameAsString();
4678 S += '"';
4679 }
4680
4681 if (field->isBitField()) {
4682 EncodeBitField(this, S, field->getType(), field);
4683 CurOffs += field->getBitWidth()->EvaluateAsInt(*this).getZExtValue();
4684 } else {
4685 QualType qt = field->getType();
4686 getLegacyIntegralTypeEncoding(qt);
4687 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4688 /*OutermostType*/false,
4689 /*EncodingProperty*/false,
4690 /*StructField*/true);
4691 CurOffs += getTypeSize(field->getType());
4692 }
4693 }
4694 }
4695}
4696
Mike Stump1eb44332009-09-09 15:08:12 +00004697void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004698 std::string& S) const {
4699 if (QT & Decl::OBJC_TQ_In)
4700 S += 'n';
4701 if (QT & Decl::OBJC_TQ_Inout)
4702 S += 'N';
4703 if (QT & Decl::OBJC_TQ_Out)
4704 S += 'o';
4705 if (QT & Decl::OBJC_TQ_Bycopy)
4706 S += 'O';
4707 if (QT & Decl::OBJC_TQ_Byref)
4708 S += 'R';
4709 if (QT & Decl::OBJC_TQ_Oneway)
4710 S += 'V';
4711}
4712
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004713void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004714 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004715
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004716 BuiltinVaListType = T;
4717}
4718
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004719void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004720 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00004721}
4722
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004723void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00004724 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004725}
4726
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004727void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004728 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00004729}
4730
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004731void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004732 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004733}
4734
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004735void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004736 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004737 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004738
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004739 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004740}
4741
John McCall0bd6feb2009-12-02 08:04:21 +00004742/// \brief Retrieve the template name that corresponds to a non-empty
4743/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00004744TemplateName
4745ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4746 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00004747 unsigned size = End - Begin;
4748 assert(size > 1 && "set is not overloaded!");
4749
4750 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4751 size * sizeof(FunctionTemplateDecl*));
4752 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4753
4754 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004755 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004756 NamedDecl *D = *I;
4757 assert(isa<FunctionTemplateDecl>(D) ||
4758 (isa<UsingShadowDecl>(D) &&
4759 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4760 *Storage++ = D;
4761 }
4762
4763 return TemplateName(OT);
4764}
4765
Douglas Gregor7532dc62009-03-30 22:58:21 +00004766/// \brief Retrieve the template name that represents a qualified
4767/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00004768TemplateName
4769ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4770 bool TemplateKeyword,
4771 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00004772 assert(NNS && "Missing nested-name-specifier in qualified template name");
4773
Douglas Gregor789b1f62010-02-04 18:10:26 +00004774 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004775 llvm::FoldingSetNodeID ID;
4776 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4777
4778 void *InsertPos = 0;
4779 QualifiedTemplateName *QTN =
4780 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4781 if (!QTN) {
4782 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4783 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4784 }
4785
4786 return TemplateName(QTN);
4787}
4788
4789/// \brief Retrieve the template name that represents a dependent
4790/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00004791TemplateName
4792ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4793 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004794 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004795 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004796
4797 llvm::FoldingSetNodeID ID;
4798 DependentTemplateName::Profile(ID, NNS, Name);
4799
4800 void *InsertPos = 0;
4801 DependentTemplateName *QTN =
4802 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4803
4804 if (QTN)
4805 return TemplateName(QTN);
4806
4807 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4808 if (CanonNNS == NNS) {
4809 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4810 } else {
4811 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4812 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004813 DependentTemplateName *CheckQTN =
4814 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4815 assert(!CheckQTN && "Dependent type name canonicalization broken");
4816 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004817 }
4818
4819 DependentTemplateNames.InsertNode(QTN, InsertPos);
4820 return TemplateName(QTN);
4821}
4822
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004823/// \brief Retrieve the template name that represents a dependent
4824/// template name such as \c MetaFun::template operator+.
4825TemplateName
4826ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00004827 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004828 assert((!NNS || NNS->isDependent()) &&
4829 "Nested name specifier must be dependent");
4830
4831 llvm::FoldingSetNodeID ID;
4832 DependentTemplateName::Profile(ID, NNS, Operator);
4833
4834 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004835 DependentTemplateName *QTN
4836 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004837
4838 if (QTN)
4839 return TemplateName(QTN);
4840
4841 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4842 if (CanonNNS == NNS) {
4843 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4844 } else {
4845 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4846 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004847
4848 DependentTemplateName *CheckQTN
4849 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4850 assert(!CheckQTN && "Dependent template name canonicalization broken");
4851 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004852 }
4853
4854 DependentTemplateNames.InsertNode(QTN, InsertPos);
4855 return TemplateName(QTN);
4856}
4857
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004858TemplateName
John McCall14606042011-06-30 08:33:18 +00004859ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
4860 TemplateName replacement) const {
4861 llvm::FoldingSetNodeID ID;
4862 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
4863
4864 void *insertPos = 0;
4865 SubstTemplateTemplateParmStorage *subst
4866 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
4867
4868 if (!subst) {
4869 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
4870 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
4871 }
4872
4873 return TemplateName(subst);
4874}
4875
4876TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004877ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4878 const TemplateArgument &ArgPack) const {
4879 ASTContext &Self = const_cast<ASTContext &>(*this);
4880 llvm::FoldingSetNodeID ID;
4881 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4882
4883 void *InsertPos = 0;
4884 SubstTemplateTemplateParmPackStorage *Subst
4885 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4886
4887 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00004888 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004889 ArgPack.pack_size(),
4890 ArgPack.pack_begin());
4891 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4892 }
4893
4894 return TemplateName(Subst);
4895}
4896
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004897/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004898/// TargetInfo, produce the corresponding type. The unsigned @p Type
4899/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004900CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004901 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004902 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004903 case TargetInfo::SignedShort: return ShortTy;
4904 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4905 case TargetInfo::SignedInt: return IntTy;
4906 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4907 case TargetInfo::SignedLong: return LongTy;
4908 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4909 case TargetInfo::SignedLongLong: return LongLongTy;
4910 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4911 }
4912
4913 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004914 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004915}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004916
4917//===----------------------------------------------------------------------===//
4918// Type Predicates.
4919//===----------------------------------------------------------------------===//
4920
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004921/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4922/// garbage collection attribute.
4923///
John McCallae278a32011-01-12 00:34:59 +00004924Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4925 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4926 return Qualifiers::GCNone;
4927
4928 assert(getLangOptions().ObjC1);
4929 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4930
4931 // Default behaviour under objective-C's gc is for ObjC pointers
4932 // (or pointers to them) be treated as though they were declared
4933 // as __strong.
4934 if (GCAttrs == Qualifiers::GCNone) {
4935 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4936 return Qualifiers::Strong;
4937 else if (Ty->isPointerType())
4938 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4939 } else {
4940 // It's not valid to set GC attributes on anything that isn't a
4941 // pointer.
4942#ifndef NDEBUG
4943 QualType CT = Ty->getCanonicalTypeInternal();
4944 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4945 CT = AT->getElementType();
4946 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4947#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004948 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004949 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004950}
4951
Chris Lattner6ac46a42008-04-07 06:51:04 +00004952//===----------------------------------------------------------------------===//
4953// Type Compatibility Testing
4954//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004955
Mike Stump1eb44332009-09-09 15:08:12 +00004956/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004957/// compatible.
4958static bool areCompatVectorTypes(const VectorType *LHS,
4959 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004960 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004961 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004962 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004963}
4964
Douglas Gregor255210e2010-08-06 10:14:59 +00004965bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4966 QualType SecondVec) {
4967 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4968 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4969
4970 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4971 return true;
4972
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004973 // Treat Neon vector types and most AltiVec vector types as if they are the
4974 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00004975 const VectorType *First = FirstVec->getAs<VectorType>();
4976 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004977 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00004978 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004979 First->getVectorKind() != VectorType::AltiVecPixel &&
4980 First->getVectorKind() != VectorType::AltiVecBool &&
4981 Second->getVectorKind() != VectorType::AltiVecPixel &&
4982 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00004983 return true;
4984
4985 return false;
4986}
4987
Steve Naroff4084c302009-07-23 01:01:38 +00004988//===----------------------------------------------------------------------===//
4989// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4990//===----------------------------------------------------------------------===//
4991
4992/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4993/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00004994bool
4995ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4996 ObjCProtocolDecl *rProto) const {
Steve Naroff4084c302009-07-23 01:01:38 +00004997 if (lProto == rProto)
4998 return true;
4999 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5000 E = rProto->protocol_end(); PI != E; ++PI)
5001 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5002 return true;
5003 return false;
5004}
5005
Steve Naroff4084c302009-07-23 01:01:38 +00005006/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5007/// return true if lhs's protocols conform to rhs's protocol; false
5008/// otherwise.
5009bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5010 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5011 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5012 return false;
5013}
5014
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005015/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5016/// Class<p1, ...>.
5017bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5018 QualType rhs) {
5019 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5020 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5021 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5022
5023 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5024 E = lhsQID->qual_end(); I != E; ++I) {
5025 bool match = false;
5026 ObjCProtocolDecl *lhsProto = *I;
5027 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5028 E = rhsOPT->qual_end(); J != E; ++J) {
5029 ObjCProtocolDecl *rhsProto = *J;
5030 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5031 match = true;
5032 break;
5033 }
5034 }
5035 if (!match)
5036 return false;
5037 }
5038 return true;
5039}
5040
Steve Naroff4084c302009-07-23 01:01:38 +00005041/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5042/// ObjCQualifiedIDType.
5043bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5044 bool compare) {
5045 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00005046 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005047 lhs->isObjCIdType() || lhs->isObjCClassType())
5048 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005049 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005050 rhs->isObjCIdType() || rhs->isObjCClassType())
5051 return true;
5052
5053 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00005054 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005055
Steve Naroff4084c302009-07-23 01:01:38 +00005056 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005057
Steve Naroff4084c302009-07-23 01:01:38 +00005058 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005059 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00005060 // make sure we check the class hierarchy.
5061 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5062 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5063 E = lhsQID->qual_end(); I != E; ++I) {
5064 // when comparing an id<P> on lhs with a static type on rhs,
5065 // see if static class implements all of id's protocols, directly or
5066 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005067 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00005068 return false;
5069 }
5070 }
5071 // If there are no qualifiers and no interface, we have an 'id'.
5072 return true;
5073 }
Mike Stump1eb44332009-09-09 15:08:12 +00005074 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005075 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5076 E = lhsQID->qual_end(); I != E; ++I) {
5077 ObjCProtocolDecl *lhsProto = *I;
5078 bool match = false;
5079
5080 // when comparing an id<P> on lhs with a static type on rhs,
5081 // see if static class implements all of id's protocols, directly or
5082 // through its super class and categories.
5083 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5084 E = rhsOPT->qual_end(); J != E; ++J) {
5085 ObjCProtocolDecl *rhsProto = *J;
5086 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5087 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5088 match = true;
5089 break;
5090 }
5091 }
Mike Stump1eb44332009-09-09 15:08:12 +00005092 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00005093 // make sure we check the class hierarchy.
5094 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5095 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5096 E = lhsQID->qual_end(); I != E; ++I) {
5097 // when comparing an id<P> on lhs with a static type on rhs,
5098 // see if static class implements all of id's protocols, directly or
5099 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005100 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00005101 match = true;
5102 break;
5103 }
5104 }
5105 }
5106 if (!match)
5107 return false;
5108 }
Mike Stump1eb44332009-09-09 15:08:12 +00005109
Steve Naroff4084c302009-07-23 01:01:38 +00005110 return true;
5111 }
Mike Stump1eb44332009-09-09 15:08:12 +00005112
Steve Naroff4084c302009-07-23 01:01:38 +00005113 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5114 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5115
Mike Stump1eb44332009-09-09 15:08:12 +00005116 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00005117 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005118 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005119 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5120 E = lhsOPT->qual_end(); I != E; ++I) {
5121 ObjCProtocolDecl *lhsProto = *I;
5122 bool match = false;
5123
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005124 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00005125 // see if static class implements all of id's protocols, directly or
5126 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005127 // First, lhs protocols in the qualifier list must be found, direct
5128 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00005129 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5130 E = rhsQID->qual_end(); J != E; ++J) {
5131 ObjCProtocolDecl *rhsProto = *J;
5132 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5133 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5134 match = true;
5135 break;
5136 }
5137 }
5138 if (!match)
5139 return false;
5140 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005141
5142 // Static class's protocols, or its super class or category protocols
5143 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5144 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5145 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5146 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5147 // This is rather dubious but matches gcc's behavior. If lhs has
5148 // no type qualifier and its class has no static protocol(s)
5149 // assume that it is mismatch.
5150 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5151 return false;
5152 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5153 LHSInheritedProtocols.begin(),
5154 E = LHSInheritedProtocols.end(); I != E; ++I) {
5155 bool match = false;
5156 ObjCProtocolDecl *lhsProto = (*I);
5157 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5158 E = rhsQID->qual_end(); J != E; ++J) {
5159 ObjCProtocolDecl *rhsProto = *J;
5160 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5161 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5162 match = true;
5163 break;
5164 }
5165 }
5166 if (!match)
5167 return false;
5168 }
5169 }
Steve Naroff4084c302009-07-23 01:01:38 +00005170 return true;
5171 }
5172 return false;
5173}
5174
Eli Friedman3d815e72008-08-22 00:56:42 +00005175/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005176/// compatible for assignment from RHS to LHS. This handles validation of any
5177/// protocol qualifiers on the LHS or RHS.
5178///
Steve Naroff14108da2009-07-10 23:34:53 +00005179bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5180 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00005181 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5182 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5183
Steve Naroffde2e22d2009-07-15 18:40:39 +00005184 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00005185 if (LHS->isObjCUnqualifiedIdOrClass() ||
5186 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00005187 return true;
5188
John McCallc12c5bb2010-05-15 11:32:37 +00005189 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00005190 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5191 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00005192 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005193
5194 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5195 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5196 QualType(RHSOPT,0));
5197
John McCallc12c5bb2010-05-15 11:32:37 +00005198 // If we have 2 user-defined types, fall into that path.
5199 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00005200 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00005201
Steve Naroff4084c302009-07-23 01:01:38 +00005202 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005203}
5204
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005205/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00005206/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005207/// arguments in block literals. When passed as arguments, passing 'A*' where
5208/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5209/// not OK. For the return type, the opposite is not OK.
5210bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5211 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005212 const ObjCObjectPointerType *RHSOPT,
5213 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005214 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005215 return true;
5216
5217 if (LHSOPT->isObjCBuiltinType()) {
5218 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5219 }
5220
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005221 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005222 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5223 QualType(RHSOPT,0),
5224 false);
5225
5226 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5227 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5228 if (LHS && RHS) { // We have 2 user-defined types.
5229 if (LHS != RHS) {
5230 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005231 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005232 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005233 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005234 }
5235 else
5236 return true;
5237 }
5238 return false;
5239}
5240
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005241/// getIntersectionOfProtocols - This routine finds the intersection of set
5242/// of protocols inherited from two distinct objective-c pointer objects.
5243/// It is used to build composite qualifier list of the composite type of
5244/// the conditional expression involving two objective-c pointer objects.
5245static
5246void getIntersectionOfProtocols(ASTContext &Context,
5247 const ObjCObjectPointerType *LHSOPT,
5248 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005249 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005250
John McCallc12c5bb2010-05-15 11:32:37 +00005251 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5252 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5253 assert(LHS->getInterface() && "LHS must have an interface base");
5254 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005255
5256 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5257 unsigned LHSNumProtocols = LHS->getNumProtocols();
5258 if (LHSNumProtocols > 0)
5259 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5260 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005261 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005262 Context.CollectInheritedProtocols(LHS->getInterface(),
5263 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005264 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5265 LHSInheritedProtocols.end());
5266 }
5267
5268 unsigned RHSNumProtocols = RHS->getNumProtocols();
5269 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00005270 ObjCProtocolDecl **RHSProtocols =
5271 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005272 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5273 if (InheritedProtocolSet.count(RHSProtocols[i]))
5274 IntersectionOfProtocols.push_back(RHSProtocols[i]);
5275 }
5276 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005277 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005278 Context.CollectInheritedProtocols(RHS->getInterface(),
5279 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005280 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5281 RHSInheritedProtocols.begin(),
5282 E = RHSInheritedProtocols.end(); I != E; ++I)
5283 if (InheritedProtocolSet.count((*I)))
5284 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005285 }
5286}
5287
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005288/// areCommonBaseCompatible - Returns common base class of the two classes if
5289/// one found. Note that this is O'2 algorithm. But it will be called as the
5290/// last type comparison in a ?-exp of ObjC pointer types before a
5291/// warning is issued. So, its invokation is extremely rare.
5292QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00005293 const ObjCObjectPointerType *Lptr,
5294 const ObjCObjectPointerType *Rptr) {
5295 const ObjCObjectType *LHS = Lptr->getObjectType();
5296 const ObjCObjectType *RHS = Rptr->getObjectType();
5297 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5298 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005299 if (!LDecl || !RDecl || (LDecl == RDecl))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005300 return QualType();
5301
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005302 do {
John McCallc12c5bb2010-05-15 11:32:37 +00005303 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005304 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005305 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005306 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5307
5308 QualType Result = QualType(LHS, 0);
5309 if (!Protocols.empty())
5310 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5311 Result = getObjCObjectPointerType(Result);
5312 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005313 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005314 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005315
5316 return QualType();
5317}
5318
John McCallc12c5bb2010-05-15 11:32:37 +00005319bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5320 const ObjCObjectType *RHS) {
5321 assert(LHS->getInterface() && "LHS is not an interface type");
5322 assert(RHS->getInterface() && "RHS is not an interface type");
5323
Chris Lattner6ac46a42008-04-07 06:51:04 +00005324 // Verify that the base decls are compatible: the RHS must be a subclass of
5325 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00005326 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00005327 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005328
Chris Lattner6ac46a42008-04-07 06:51:04 +00005329 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5330 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00005331 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00005332 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005333
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005334 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5335 // more detailed analysis is required.
5336 if (RHS->getNumProtocols() == 0) {
5337 // OK, if LHS is a superclass of RHS *and*
5338 // this superclass is assignment compatible with LHS.
5339 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005340 bool IsSuperClass =
5341 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5342 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005343 // OK if conversion of LHS to SuperClass results in narrowing of types
5344 // ; i.e., SuperClass may implement at least one of the protocols
5345 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5346 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5347 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005348 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005349 // If super class has no protocols, it is not a match.
5350 if (SuperClassInheritedProtocols.empty())
5351 return false;
5352
5353 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5354 LHSPE = LHS->qual_end();
5355 LHSPI != LHSPE; LHSPI++) {
5356 bool SuperImplementsProtocol = false;
5357 ObjCProtocolDecl *LHSProto = (*LHSPI);
5358
5359 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5360 SuperClassInheritedProtocols.begin(),
5361 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5362 ObjCProtocolDecl *SuperClassProto = (*I);
5363 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5364 SuperImplementsProtocol = true;
5365 break;
5366 }
5367 }
5368 if (!SuperImplementsProtocol)
5369 return false;
5370 }
5371 return true;
5372 }
5373 return false;
5374 }
Mike Stump1eb44332009-09-09 15:08:12 +00005375
John McCallc12c5bb2010-05-15 11:32:37 +00005376 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5377 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005378 LHSPI != LHSPE; LHSPI++) {
5379 bool RHSImplementsProtocol = false;
5380
5381 // If the RHS doesn't implement the protocol on the left, the types
5382 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00005383 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5384 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00005385 RHSPI != RHSPE; RHSPI++) {
5386 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005387 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00005388 break;
5389 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005390 }
5391 // FIXME: For better diagnostics, consider passing back the protocol name.
5392 if (!RHSImplementsProtocol)
5393 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005394 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005395 // The RHS implements all protocols listed on the LHS.
5396 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005397}
5398
Steve Naroff389bf462009-02-12 17:52:19 +00005399bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5400 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00005401 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5402 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005403
Steve Naroff14108da2009-07-10 23:34:53 +00005404 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00005405 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005406
5407 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5408 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00005409}
5410
Douglas Gregor569c3162010-08-07 11:51:51 +00005411bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5412 return canAssignObjCInterfaces(
5413 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5414 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5415}
5416
Mike Stump1eb44332009-09-09 15:08:12 +00005417/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00005418/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00005419/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00005420/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00005421bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5422 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005423 if (getLangOptions().CPlusPlus)
5424 return hasSameType(LHS, RHS);
5425
Douglas Gregor447234d2010-07-29 15:18:02 +00005426 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00005427}
5428
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005429bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00005430 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005431}
5432
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005433bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5434 return !mergeTypes(LHS, RHS, true).isNull();
5435}
5436
Peter Collingbourne48466752010-10-24 18:30:18 +00005437/// mergeTransparentUnionType - if T is a transparent union type and a member
5438/// of T is compatible with SubType, return the merged type, else return
5439/// QualType()
5440QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5441 bool OfBlockPointer,
5442 bool Unqualified) {
5443 if (const RecordType *UT = T->getAsUnionType()) {
5444 RecordDecl *UD = UT->getDecl();
5445 if (UD->hasAttr<TransparentUnionAttr>()) {
5446 for (RecordDecl::field_iterator it = UD->field_begin(),
5447 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00005448 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005449 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5450 if (!MT.isNull())
5451 return MT;
5452 }
5453 }
5454 }
5455
5456 return QualType();
5457}
5458
5459/// mergeFunctionArgumentTypes - merge two types which appear as function
5460/// argument types
5461QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5462 bool OfBlockPointer,
5463 bool Unqualified) {
5464 // GNU extension: two types are compatible if they appear as a function
5465 // argument, one of the types is a transparent union type and the other
5466 // type is compatible with a union member
5467 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5468 Unqualified);
5469 if (!lmerge.isNull())
5470 return lmerge;
5471
5472 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5473 Unqualified);
5474 if (!rmerge.isNull())
5475 return rmerge;
5476
5477 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5478}
5479
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005480QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00005481 bool OfBlockPointer,
5482 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00005483 const FunctionType *lbase = lhs->getAs<FunctionType>();
5484 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00005485 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5486 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00005487 bool allLTypes = true;
5488 bool allRTypes = true;
5489
5490 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005491 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005492 if (OfBlockPointer) {
5493 QualType RHS = rbase->getResultType();
5494 QualType LHS = lbase->getResultType();
5495 bool UnqualifiedResult = Unqualified;
5496 if (!UnqualifiedResult)
5497 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005498 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005499 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005500 else
John McCall8cc246c2010-12-15 01:06:38 +00005501 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5502 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005503 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005504
5505 if (Unqualified)
5506 retType = retType.getUnqualifiedType();
5507
5508 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5509 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5510 if (Unqualified) {
5511 LRetType = LRetType.getUnqualifiedType();
5512 RRetType = RRetType.getUnqualifiedType();
5513 }
5514
5515 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005516 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00005517 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005518 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005519
Daniel Dunbar6a15c852010-04-28 16:20:58 +00005520 // FIXME: double check this
5521 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5522 // rbase->getRegParmAttr() != 0 &&
5523 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00005524 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5525 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00005526
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005527 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00005528 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005529 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005530
John McCall8cc246c2010-12-15 01:06:38 +00005531 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00005532 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5533 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00005534 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5535 return QualType();
5536
John McCallf85e1932011-06-15 23:02:42 +00005537 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5538 return QualType();
5539
John McCall8cc246c2010-12-15 01:06:38 +00005540 // It's noreturn if either type is.
5541 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5542 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5543 if (NoReturn != lbaseInfo.getNoReturn())
5544 allLTypes = false;
5545 if (NoReturn != rbaseInfo.getNoReturn())
5546 allRTypes = false;
5547
John McCallf85e1932011-06-15 23:02:42 +00005548 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00005549
Eli Friedman3d815e72008-08-22 00:56:42 +00005550 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00005551 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5552 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005553 unsigned lproto_nargs = lproto->getNumArgs();
5554 unsigned rproto_nargs = rproto->getNumArgs();
5555
5556 // Compatible functions must have the same number of arguments
5557 if (lproto_nargs != rproto_nargs)
5558 return QualType();
5559
5560 // Variadic and non-variadic functions aren't compatible
5561 if (lproto->isVariadic() != rproto->isVariadic())
5562 return QualType();
5563
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00005564 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5565 return QualType();
5566
Eli Friedman3d815e72008-08-22 00:56:42 +00005567 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00005568 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00005569 for (unsigned i = 0; i < lproto_nargs; i++) {
5570 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5571 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005572 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5573 OfBlockPointer,
5574 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005575 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005576
5577 if (Unqualified)
5578 argtype = argtype.getUnqualifiedType();
5579
Eli Friedman3d815e72008-08-22 00:56:42 +00005580 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00005581 if (Unqualified) {
5582 largtype = largtype.getUnqualifiedType();
5583 rargtype = rargtype.getUnqualifiedType();
5584 }
5585
Chris Lattner61710852008-10-05 17:34:18 +00005586 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5587 allLTypes = false;
5588 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5589 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00005590 }
5591 if (allLTypes) return lhs;
5592 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005593
5594 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5595 EPI.ExtInfo = einfo;
5596 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005597 }
5598
5599 if (lproto) allRTypes = false;
5600 if (rproto) allLTypes = false;
5601
Douglas Gregor72564e72009-02-26 23:50:07 +00005602 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00005603 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00005604 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005605 if (proto->isVariadic()) return QualType();
5606 // Check that the types are compatible with the types that
5607 // would result from default argument promotions (C99 6.7.5.3p15).
5608 // The only types actually affected are promotable integer
5609 // types and floats, which would be passed as a different
5610 // type depending on whether the prototype is visible.
5611 unsigned proto_nargs = proto->getNumArgs();
5612 for (unsigned i = 0; i < proto_nargs; ++i) {
5613 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00005614
5615 // Look at the promotion type of enum types, since that is the type used
5616 // to pass enum values.
5617 if (const EnumType *Enum = argTy->getAs<EnumType>())
5618 argTy = Enum->getDecl()->getPromotionType();
5619
Eli Friedman3d815e72008-08-22 00:56:42 +00005620 if (argTy->isPromotableIntegerType() ||
5621 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5622 return QualType();
5623 }
5624
5625 if (allLTypes) return lhs;
5626 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005627
5628 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5629 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00005630 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005631 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005632 }
5633
5634 if (allLTypes) return lhs;
5635 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00005636 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00005637}
5638
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005639QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00005640 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005641 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00005642 // C++ [expr]: If an expression initially has the type "reference to T", the
5643 // type is adjusted to "T" prior to any further analysis, the expression
5644 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005645 // expression is an lvalue unless the reference is an rvalue reference and
5646 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005647 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5648 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00005649
5650 if (Unqualified) {
5651 LHS = LHS.getUnqualifiedType();
5652 RHS = RHS.getUnqualifiedType();
5653 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005654
Eli Friedman3d815e72008-08-22 00:56:42 +00005655 QualType LHSCan = getCanonicalType(LHS),
5656 RHSCan = getCanonicalType(RHS);
5657
5658 // If two types are identical, they are compatible.
5659 if (LHSCan == RHSCan)
5660 return LHS;
5661
John McCall0953e762009-09-24 19:53:00 +00005662 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005663 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5664 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00005665 if (LQuals != RQuals) {
5666 // If any of these qualifiers are different, we have a type
5667 // mismatch.
5668 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00005669 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5670 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00005671 return QualType();
5672
5673 // Exactly one GC qualifier difference is allowed: __strong is
5674 // okay if the other type has no GC qualifier but is an Objective
5675 // C object pointer (i.e. implicitly strong by default). We fix
5676 // this by pretending that the unqualified type was actually
5677 // qualified __strong.
5678 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5679 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5680 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5681
5682 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5683 return QualType();
5684
5685 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5686 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5687 }
5688 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5689 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5690 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005691 return QualType();
John McCall0953e762009-09-24 19:53:00 +00005692 }
5693
5694 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00005695
Eli Friedman852d63b2009-06-01 01:22:52 +00005696 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5697 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00005698
Chris Lattner1adb8832008-01-14 05:45:46 +00005699 // We want to consider the two function types to be the same for these
5700 // comparisons, just force one to the other.
5701 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5702 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00005703
5704 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00005705 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5706 LHSClass = Type::ConstantArray;
5707 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5708 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00005709
John McCallc12c5bb2010-05-15 11:32:37 +00005710 // ObjCInterfaces are just specialized ObjCObjects.
5711 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5712 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5713
Nate Begeman213541a2008-04-18 23:10:10 +00005714 // Canonicalize ExtVector -> Vector.
5715 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5716 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00005717
Chris Lattnera36a61f2008-04-07 05:43:21 +00005718 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005719 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00005720 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00005721 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00005722 // Compatibility is based on the underlying type, not the promotion
5723 // type.
John McCall183700f2009-09-21 23:43:11 +00005724 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005725 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5726 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005727 }
John McCall183700f2009-09-21 23:43:11 +00005728 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005729 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5730 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005731 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005732
Eli Friedman3d815e72008-08-22 00:56:42 +00005733 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005734 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005735
Steve Naroff4a746782008-01-09 22:43:08 +00005736 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005737 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00005738#define TYPE(Class, Base)
5739#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00005740#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00005741#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5742#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5743#include "clang/AST/TypeNodes.def"
5744 assert(false && "Non-canonical and dependent types shouldn't get here");
5745 return QualType();
5746
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005747 case Type::LValueReference:
5748 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00005749 case Type::MemberPointer:
5750 assert(false && "C++ should never be in mergeTypes");
5751 return QualType();
5752
John McCallc12c5bb2010-05-15 11:32:37 +00005753 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00005754 case Type::IncompleteArray:
5755 case Type::VariableArray:
5756 case Type::FunctionProto:
5757 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00005758 assert(false && "Types are eliminated above");
5759 return QualType();
5760
Chris Lattner1adb8832008-01-14 05:45:46 +00005761 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00005762 {
5763 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005764 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5765 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005766 if (Unqualified) {
5767 LHSPointee = LHSPointee.getUnqualifiedType();
5768 RHSPointee = RHSPointee.getUnqualifiedType();
5769 }
5770 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5771 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005772 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00005773 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005774 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00005775 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005776 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005777 return getPointerType(ResultType);
5778 }
Steve Naroffc0febd52008-12-10 17:49:55 +00005779 case Type::BlockPointer:
5780 {
5781 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005782 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5783 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005784 if (Unqualified) {
5785 LHSPointee = LHSPointee.getUnqualifiedType();
5786 RHSPointee = RHSPointee.getUnqualifiedType();
5787 }
5788 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5789 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00005790 if (ResultType.isNull()) return QualType();
5791 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5792 return LHS;
5793 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5794 return RHS;
5795 return getBlockPointerType(ResultType);
5796 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005797 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00005798 {
5799 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5800 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5801 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5802 return QualType();
5803
5804 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5805 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005806 if (Unqualified) {
5807 LHSElem = LHSElem.getUnqualifiedType();
5808 RHSElem = RHSElem.getUnqualifiedType();
5809 }
5810
5811 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005812 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00005813 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5814 return LHS;
5815 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5816 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00005817 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5818 ArrayType::ArraySizeModifier(), 0);
5819 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5820 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005821 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5822 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00005823 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5824 return LHS;
5825 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5826 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005827 if (LVAT) {
5828 // FIXME: This isn't correct! But tricky to implement because
5829 // the array's size has to be the size of LHS, but the type
5830 // has to be different.
5831 return LHS;
5832 }
5833 if (RVAT) {
5834 // FIXME: This isn't correct! But tricky to implement because
5835 // the array's size has to be the size of RHS, but the type
5836 // has to be different.
5837 return RHS;
5838 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00005839 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5840 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00005841 return getIncompleteArrayType(ResultType,
5842 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005843 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005844 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00005845 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00005846 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00005847 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00005848 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00005849 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005850 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00005851 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00005852 case Type::Complex:
5853 // Distinct complex types are incompatible.
5854 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005855 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005856 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00005857 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5858 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005859 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00005860 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00005861 case Type::ObjCObject: {
5862 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005863 // FIXME: This should be type compatibility, e.g. whether
5864 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00005865 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5866 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5867 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00005868 return LHS;
5869
Eli Friedman3d815e72008-08-22 00:56:42 +00005870 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00005871 }
Steve Naroff14108da2009-07-10 23:34:53 +00005872 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005873 if (OfBlockPointer) {
5874 if (canAssignObjCInterfacesInBlockPointer(
5875 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005876 RHS->getAs<ObjCObjectPointerType>(),
5877 BlockReturnType))
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005878 return LHS;
5879 return QualType();
5880 }
John McCall183700f2009-09-21 23:43:11 +00005881 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5882 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00005883 return LHS;
5884
Steve Naroffbc76dd02008-12-10 22:14:21 +00005885 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005886 }
Steve Naroffec0550f2007-10-15 20:41:53 +00005887 }
Douglas Gregor72564e72009-02-26 23:50:07 +00005888
5889 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005890}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00005891
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005892/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5893/// 'RHS' attributes and returns the merged version; including for function
5894/// return types.
5895QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5896 QualType LHSCan = getCanonicalType(LHS),
5897 RHSCan = getCanonicalType(RHS);
5898 // If two types are identical, they are compatible.
5899 if (LHSCan == RHSCan)
5900 return LHS;
5901 if (RHSCan->isFunctionType()) {
5902 if (!LHSCan->isFunctionType())
5903 return QualType();
5904 QualType OldReturnType =
5905 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5906 QualType NewReturnType =
5907 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5908 QualType ResReturnType =
5909 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5910 if (ResReturnType.isNull())
5911 return QualType();
5912 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5913 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5914 // In either case, use OldReturnType to build the new function type.
5915 const FunctionType *F = LHS->getAs<FunctionType>();
5916 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00005917 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5918 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005919 QualType ResultType
5920 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005921 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005922 return ResultType;
5923 }
5924 }
5925 return QualType();
5926 }
5927
5928 // If the qualifiers are different, the types can still be merged.
5929 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5930 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5931 if (LQuals != RQuals) {
5932 // If any of these qualifiers are different, we have a type mismatch.
5933 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5934 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5935 return QualType();
5936
5937 // Exactly one GC qualifier difference is allowed: __strong is
5938 // okay if the other type has no GC qualifier but is an Objective
5939 // C object pointer (i.e. implicitly strong by default). We fix
5940 // this by pretending that the unqualified type was actually
5941 // qualified __strong.
5942 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5943 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5944 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5945
5946 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5947 return QualType();
5948
5949 if (GC_L == Qualifiers::Strong)
5950 return LHS;
5951 if (GC_R == Qualifiers::Strong)
5952 return RHS;
5953 return QualType();
5954 }
5955
5956 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5957 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5958 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5959 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5960 if (ResQT == LHSBaseQT)
5961 return LHS;
5962 if (ResQT == RHSBaseQT)
5963 return RHS;
5964 }
5965 return QualType();
5966}
5967
Chris Lattner5426bf62008-04-07 07:01:58 +00005968//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00005969// Integer Predicates
5970//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00005971
Jay Foad4ba2a172011-01-12 09:06:06 +00005972unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00005973 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00005974 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005975 if (T->isBooleanType())
5976 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00005977 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00005978 return (unsigned)getTypeSize(T);
5979}
5980
5981QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00005982 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00005983
5984 // Turn <4 x signed int> -> <4 x unsigned int>
5985 if (const VectorType *VTy = T->getAs<VectorType>())
5986 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00005987 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00005988
5989 // For enums, we return the unsigned version of the base type.
5990 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00005991 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00005992
5993 const BuiltinType *BTy = T->getAs<BuiltinType>();
5994 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00005995 switch (BTy->getKind()) {
5996 case BuiltinType::Char_S:
5997 case BuiltinType::SChar:
5998 return UnsignedCharTy;
5999 case BuiltinType::Short:
6000 return UnsignedShortTy;
6001 case BuiltinType::Int:
6002 return UnsignedIntTy;
6003 case BuiltinType::Long:
6004 return UnsignedLongTy;
6005 case BuiltinType::LongLong:
6006 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00006007 case BuiltinType::Int128:
6008 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00006009 default:
6010 assert(0 && "Unexpected signed integer type");
6011 return QualType();
6012 }
6013}
6014
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00006015ASTMutationListener::~ASTMutationListener() { }
6016
Chris Lattner86df27b2009-06-14 00:45:47 +00006017
6018//===----------------------------------------------------------------------===//
6019// Builtin Type Computation
6020//===----------------------------------------------------------------------===//
6021
6022/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00006023/// pointer over the consumed characters. This returns the resultant type. If
6024/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6025/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6026/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00006027///
6028/// RequiresICE is filled in on return to indicate whether the value is required
6029/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00006030static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00006031 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00006032 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00006033 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00006034 // Modifiers.
6035 int HowLong = 0;
6036 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00006037 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006038
Chris Lattner33daae62010-10-01 22:42:38 +00006039 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00006040 bool Done = false;
6041 while (!Done) {
6042 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00006043 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006044 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00006045 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006046 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006047 case 'S':
6048 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6049 assert(!Signed && "Can't use 'S' modifier multiple times!");
6050 Signed = true;
6051 break;
6052 case 'U':
6053 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6054 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6055 Unsigned = true;
6056 break;
6057 case 'L':
6058 assert(HowLong <= 2 && "Can't have LLLL modifier");
6059 ++HowLong;
6060 break;
6061 }
6062 }
6063
6064 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00006065
Chris Lattner86df27b2009-06-14 00:45:47 +00006066 // Read the base type.
6067 switch (*Str++) {
6068 default: assert(0 && "Unknown builtin type letter!");
6069 case 'v':
6070 assert(HowLong == 0 && !Signed && !Unsigned &&
6071 "Bad modifiers used with 'v'!");
6072 Type = Context.VoidTy;
6073 break;
6074 case 'f':
6075 assert(HowLong == 0 && !Signed && !Unsigned &&
6076 "Bad modifiers used with 'f'!");
6077 Type = Context.FloatTy;
6078 break;
6079 case 'd':
6080 assert(HowLong < 2 && !Signed && !Unsigned &&
6081 "Bad modifiers used with 'd'!");
6082 if (HowLong)
6083 Type = Context.LongDoubleTy;
6084 else
6085 Type = Context.DoubleTy;
6086 break;
6087 case 's':
6088 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6089 if (Unsigned)
6090 Type = Context.UnsignedShortTy;
6091 else
6092 Type = Context.ShortTy;
6093 break;
6094 case 'i':
6095 if (HowLong == 3)
6096 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6097 else if (HowLong == 2)
6098 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6099 else if (HowLong == 1)
6100 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6101 else
6102 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6103 break;
6104 case 'c':
6105 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6106 if (Signed)
6107 Type = Context.SignedCharTy;
6108 else if (Unsigned)
6109 Type = Context.UnsignedCharTy;
6110 else
6111 Type = Context.CharTy;
6112 break;
6113 case 'b': // boolean
6114 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6115 Type = Context.BoolTy;
6116 break;
6117 case 'z': // size_t.
6118 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6119 Type = Context.getSizeType();
6120 break;
6121 case 'F':
6122 Type = Context.getCFConstantStringType();
6123 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00006124 case 'G':
6125 Type = Context.getObjCIdType();
6126 break;
6127 case 'H':
6128 Type = Context.getObjCSelType();
6129 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006130 case 'a':
6131 Type = Context.getBuiltinVaListType();
6132 assert(!Type.isNull() && "builtin va list type not initialized!");
6133 break;
6134 case 'A':
6135 // This is a "reference" to a va_list; however, what exactly
6136 // this means depends on how va_list is defined. There are two
6137 // different kinds of va_list: ones passed by value, and ones
6138 // passed by reference. An example of a by-value va_list is
6139 // x86, where va_list is a char*. An example of by-ref va_list
6140 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6141 // we want this argument to be a char*&; for x86-64, we want
6142 // it to be a __va_list_tag*.
6143 Type = Context.getBuiltinVaListType();
6144 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00006145 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00006146 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00006147 else
Chris Lattner86df27b2009-06-14 00:45:47 +00006148 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00006149 break;
6150 case 'V': {
6151 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00006152 unsigned NumElements = strtoul(Str, &End, 10);
6153 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00006154 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00006155
Chris Lattner14e0e742010-10-01 22:53:11 +00006156 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6157 RequiresICE, false);
6158 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00006159
6160 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00006161 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00006162 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00006163 break;
6164 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00006165 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00006166 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6167 false);
6168 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00006169 Type = Context.getComplexType(ElementType);
6170 break;
6171 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006172 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00006173 Type = Context.getFILEType();
6174 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006175 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00006176 return QualType();
6177 }
Mike Stumpfd612db2009-07-28 23:47:15 +00006178 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006179 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00006180 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00006181 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00006182 else
6183 Type = Context.getjmp_bufType();
6184
Mike Stumpfd612db2009-07-28 23:47:15 +00006185 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006186 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00006187 return QualType();
6188 }
6189 break;
Mike Stump782fa302009-07-28 02:25:19 +00006190 }
Mike Stump1eb44332009-09-09 15:08:12 +00006191
Chris Lattner33daae62010-10-01 22:42:38 +00006192 // If there are modifiers and if we're allowed to parse them, go for it.
6193 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00006194 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00006195 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00006196 default: Done = true; --Str; break;
6197 case '*':
6198 case '&': {
6199 // Both pointers and references can have their pointee types
6200 // qualified with an address space.
6201 char *End;
6202 unsigned AddrSpace = strtoul(Str, &End, 10);
6203 if (End != Str && AddrSpace != 0) {
6204 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6205 Str = End;
6206 }
6207 if (c == '*')
6208 Type = Context.getPointerType(Type);
6209 else
6210 Type = Context.getLValueReferenceType(Type);
6211 break;
6212 }
6213 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6214 case 'C':
6215 Type = Type.withConst();
6216 break;
6217 case 'D':
6218 Type = Context.getVolatileType(Type);
6219 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006220 }
6221 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00006222
Chris Lattner14e0e742010-10-01 22:53:11 +00006223 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00006224 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00006225
Chris Lattner86df27b2009-06-14 00:45:47 +00006226 return Type;
6227}
6228
6229/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00006230QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00006231 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00006232 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00006233 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00006234
Chris Lattner5f9e2722011-07-23 10:55:15 +00006235 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00006236
Chris Lattner14e0e742010-10-01 22:53:11 +00006237 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00006238 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00006239 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6240 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006241 if (Error != GE_None)
6242 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00006243
6244 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6245
Chris Lattner86df27b2009-06-14 00:45:47 +00006246 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00006247 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006248 if (Error != GE_None)
6249 return QualType();
6250
Chris Lattner14e0e742010-10-01 22:53:11 +00006251 // If this argument is required to be an IntegerConstantExpression and the
6252 // caller cares, fill in the bitmask we return.
6253 if (RequiresICE && IntegerConstantArgs)
6254 *IntegerConstantArgs |= 1 << ArgTypes.size();
6255
Chris Lattner86df27b2009-06-14 00:45:47 +00006256 // Do array -> pointer decay. The builtin should use the decayed type.
6257 if (Ty->isArrayType())
6258 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00006259
Chris Lattner86df27b2009-06-14 00:45:47 +00006260 ArgTypes.push_back(Ty);
6261 }
6262
6263 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6264 "'.' should only occur at end of builtin type list!");
6265
John McCall00ccbef2010-12-21 00:44:39 +00006266 FunctionType::ExtInfo EI;
6267 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6268
6269 bool Variadic = (TypeStr[0] == '.');
6270
6271 // We really shouldn't be making a no-proto type here, especially in C++.
6272 if (ArgTypes.empty() && Variadic)
6273 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00006274
John McCalle23cf432010-12-14 08:05:40 +00006275 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00006276 EPI.ExtInfo = EI;
6277 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00006278
6279 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00006280}
Eli Friedmana95d7572009-08-19 07:44:53 +00006281
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006282GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6283 GVALinkage External = GVA_StrongExternal;
6284
6285 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006286 switch (L) {
6287 case NoLinkage:
6288 case InternalLinkage:
6289 case UniqueExternalLinkage:
6290 return GVA_Internal;
6291
6292 case ExternalLinkage:
6293 switch (FD->getTemplateSpecializationKind()) {
6294 case TSK_Undeclared:
6295 case TSK_ExplicitSpecialization:
6296 External = GVA_StrongExternal;
6297 break;
6298
6299 case TSK_ExplicitInstantiationDefinition:
6300 return GVA_ExplicitTemplateInstantiation;
6301
6302 case TSK_ExplicitInstantiationDeclaration:
6303 case TSK_ImplicitInstantiation:
6304 External = GVA_TemplateInstantiation;
6305 break;
6306 }
6307 }
6308
6309 if (!FD->isInlined())
6310 return External;
6311
6312 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6313 // GNU or C99 inline semantics. Determine whether this symbol should be
6314 // externally visible.
6315 if (FD->isInlineDefinitionExternallyVisible())
6316 return External;
6317
6318 // C99 inline semantics, where the symbol is not externally visible.
6319 return GVA_C99Inline;
6320 }
6321
6322 // C++0x [temp.explicit]p9:
6323 // [ Note: The intent is that an inline function that is the subject of
6324 // an explicit instantiation declaration will still be implicitly
6325 // instantiated when used so that the body can be considered for
6326 // inlining, but that no out-of-line copy of the inline function would be
6327 // generated in the translation unit. -- end note ]
6328 if (FD->getTemplateSpecializationKind()
6329 == TSK_ExplicitInstantiationDeclaration)
6330 return GVA_C99Inline;
6331
6332 return GVA_CXXInline;
6333}
6334
6335GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6336 // If this is a static data member, compute the kind of template
6337 // specialization. Otherwise, this variable is not part of a
6338 // template.
6339 TemplateSpecializationKind TSK = TSK_Undeclared;
6340 if (VD->isStaticDataMember())
6341 TSK = VD->getTemplateSpecializationKind();
6342
6343 Linkage L = VD->getLinkage();
6344 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6345 VD->getType()->getLinkage() == UniqueExternalLinkage)
6346 L = UniqueExternalLinkage;
6347
6348 switch (L) {
6349 case NoLinkage:
6350 case InternalLinkage:
6351 case UniqueExternalLinkage:
6352 return GVA_Internal;
6353
6354 case ExternalLinkage:
6355 switch (TSK) {
6356 case TSK_Undeclared:
6357 case TSK_ExplicitSpecialization:
6358 return GVA_StrongExternal;
6359
6360 case TSK_ExplicitInstantiationDeclaration:
6361 llvm_unreachable("Variable should not be instantiated");
6362 // Fall through to treat this like any other instantiation.
6363
6364 case TSK_ExplicitInstantiationDefinition:
6365 return GVA_ExplicitTemplateInstantiation;
6366
6367 case TSK_ImplicitInstantiation:
6368 return GVA_TemplateInstantiation;
6369 }
6370 }
6371
6372 return GVA_StrongExternal;
6373}
6374
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00006375bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006376 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6377 if (!VD->isFileVarDecl())
6378 return false;
6379 } else if (!isa<FunctionDecl>(D))
6380 return false;
6381
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006382 // Weak references don't produce any output by themselves.
6383 if (D->hasAttr<WeakRefAttr>())
6384 return false;
6385
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006386 // Aliases and used decls are required.
6387 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6388 return true;
6389
6390 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6391 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00006392 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00006393 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006394
6395 // Constructors and destructors are required.
6396 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6397 return true;
6398
6399 // The key function for a class is required.
6400 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6401 const CXXRecordDecl *RD = MD->getParent();
6402 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6403 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6404 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6405 return true;
6406 }
6407 }
6408
6409 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6410
6411 // static, static inline, always_inline, and extern inline functions can
6412 // always be deferred. Normal inline functions can be deferred in C99/C++.
6413 // Implicit template instantiations can also be deferred in C++.
6414 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6415 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6416 return false;
6417 return true;
6418 }
6419
6420 const VarDecl *VD = cast<VarDecl>(D);
6421 assert(VD->isFileVarDecl() && "Expected file scoped var");
6422
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006423 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6424 return false;
6425
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006426 // Structs that have non-trivial constructors or destructors are required.
6427
6428 // FIXME: Handle references.
Sean Hunt023df372011-05-09 18:22:59 +00006429 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006430 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6431 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Sean Hunt023df372011-05-09 18:22:59 +00006432 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6433 RD->hasTrivialCopyConstructor() &&
6434 RD->hasTrivialMoveConstructor() &&
6435 RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006436 return true;
6437 }
6438 }
6439
6440 GVALinkage L = GetGVALinkageForVariable(VD);
6441 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6442 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6443 return false;
6444 }
6445
6446 return true;
6447}
Charles Davis071cc7d2010-08-16 03:33:14 +00006448
Charles Davisee743f92010-11-09 18:04:24 +00006449CallingConv ASTContext::getDefaultMethodCallConv() {
6450 // Pass through to the C++ ABI object
6451 return ABI->getDefaultMethodCallConv();
6452}
6453
Jay Foad4ba2a172011-01-12 09:06:06 +00006454bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00006455 // Pass through to the C++ ABI object
6456 return ABI->isNearlyEmpty(RD);
6457}
6458
Peter Collingbourne14110472011-01-13 18:57:25 +00006459MangleContext *ASTContext::createMangleContext() {
6460 switch (Target.getCXXABI()) {
6461 case CXXABI_ARM:
6462 case CXXABI_Itanium:
6463 return createItaniumMangleContext(*this, getDiagnostics());
6464 case CXXABI_Microsoft:
6465 return createMicrosoftMangleContext(*this, getDiagnostics());
6466 }
6467 assert(0 && "Unsupported ABI");
6468 return 0;
6469}
6470
Charles Davis071cc7d2010-08-16 03:33:14 +00006471CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00006472
6473size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00006474 return ASTRecordLayouts.getMemorySize()
6475 + llvm::capacity_in_bytes(ObjCLayouts)
6476 + llvm::capacity_in_bytes(KeyFunctions)
6477 + llvm::capacity_in_bytes(ObjCImpls)
6478 + llvm::capacity_in_bytes(BlockVarCopyInits)
6479 + llvm::capacity_in_bytes(DeclAttrs)
6480 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6481 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6482 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6483 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6484 + llvm::capacity_in_bytes(OverriddenMethods)
6485 + llvm::capacity_in_bytes(Types)
6486 + llvm::capacity_in_bytes(VariableArrayTypes);
Ted Kremenekba29bd22011-04-28 04:53:38 +00006487}