blob: c30089445697f2c3616e45db3ae4c412f4229f38 [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
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000199static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000200 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 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000209 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000210 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000211 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000212 }
213}
214
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000215ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +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 Gregorbcfd1f52011-09-02 00:18:52 +0000219 unsigned size_reserve,
220 bool DelayInitialization)
221 : FunctionProtoTypes(this_()),
222 TemplateSpecializationTypes(this_()),
223 DependentTemplateSpecializationTypes(this_()),
224 SubstTemplateTemplateParmPacks(this_()),
225 GlobalNestedNameSpecifier(0),
226 Int128Decl(0), UInt128Decl(0),
227 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0),
228 CFConstantStringTypeDecl(0),
229 FILEDecl(0),
230 jmp_bufDecl(0), sigjmp_bufDecl(0), BlockDescriptorType(0),
231 BlockDescriptorExtendedType(0), cudaConfigureCallDecl(0),
232 NullTypeSourceInfo(QualType()),
233 SourceMgr(SM), LangOpts(LOpts),
234 AddrSpaceMap(0), Target(t),
235 Idents(idents), Selectors(sels),
236 BuiltinInfo(builtins),
237 DeclarationNames(*this),
238 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
239 LastSDM(0, 0),
240 UniqueBlockByRefTypeID(0)
241{
Mike Stump1eb44332009-09-09 15:08:12 +0000242 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000243 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000244
245 if (!DelayInitialization) {
246 assert(t && "No target supplied for ASTContext initialization");
247 InitBuiltinTypes(*t);
248 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000249}
250
Reid Spencer5f016e22007-07-11 17:01:13 +0000251ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000252 // Release the DenseMaps associated with DeclContext objects.
253 // FIXME: Is this the ideal solution?
254 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000255
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000256 // Call all of the deallocation functions.
257 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
258 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000259
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000260 // Release all of the memory associated with overridden C++ methods.
261 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
262 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
263 OM != OMEnd; ++OM)
264 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +0000265
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000266 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000267 // because they can contain DenseMaps.
268 for (llvm::DenseMap<const ObjCContainerDecl*,
269 const ASTRecordLayout*>::iterator
270 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
271 // Increment in loop to prevent using deallocated memory.
272 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
273 R->Destroy(*this);
274
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000275 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
276 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
277 // Increment in loop to prevent using deallocated memory.
278 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
279 R->Destroy(*this);
280 }
Douglas Gregor63200642010-08-30 16:49:28 +0000281
282 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
283 AEnd = DeclAttrs.end();
284 A != AEnd; ++A)
285 A->second->~AttrVec();
286}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000287
Douglas Gregor00545312010-05-23 18:26:36 +0000288void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
289 Deallocations.push_back(std::make_pair(Callback, Data));
290}
291
Mike Stump1eb44332009-09-09 15:08:12 +0000292void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000293ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
294 ExternalSource.reset(Source.take());
295}
296
Reid Spencer5f016e22007-07-11 17:01:13 +0000297void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000298 llvm::errs() << "\n*** AST Context Stats:\n";
299 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000300
Douglas Gregordbe833d2009-05-26 14:40:08 +0000301 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000302#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000303#define ABSTRACT_TYPE(Name, Parent)
304#include "clang/AST/TypeNodes.def"
305 0 // Extra
306 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000307
Reid Spencer5f016e22007-07-11 17:01:13 +0000308 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
309 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000310 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000311 }
312
Douglas Gregordbe833d2009-05-26 14:40:08 +0000313 unsigned Idx = 0;
314 unsigned TotalBytes = 0;
315#define TYPE(Name, Parent) \
316 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000317 llvm::errs() << " " << counts[Idx] << " " << #Name \
318 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000319 TotalBytes += counts[Idx] * sizeof(Name##Type); \
320 ++Idx;
321#define ABSTRACT_TYPE(Name, Parent)
322#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Chandler Carruthcd92a652011-07-04 05:32:14 +0000324 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
325
Douglas Gregor4923aa22010-07-02 20:37:36 +0000326 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000327 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
328 << NumImplicitDefaultConstructors
329 << " implicit default constructors created\n";
330 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
331 << NumImplicitCopyConstructors
332 << " implicit copy constructors created\n";
Sean Huntffe37fd2011-05-25 20:50:04 +0000333 if (getLangOptions().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000334 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
335 << NumImplicitMoveConstructors
336 << " implicit move constructors created\n";
337 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
338 << NumImplicitCopyAssignmentOperators
339 << " implicit copy assignment operators created\n";
Sean Huntffe37fd2011-05-25 20:50:04 +0000340 if (getLangOptions().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000341 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
342 << NumImplicitMoveAssignmentOperators
343 << " implicit move assignment operators created\n";
344 llvm::errs() << NumImplicitDestructorsDeclared << "/"
345 << NumImplicitDestructors
346 << " implicit destructors created\n";
347
Douglas Gregor2cf26342009-04-09 22:27:44 +0000348 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000349 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000350 ExternalSource->PrintStats();
351 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000352
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000353 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000354}
355
Douglas Gregor772eeae2011-08-12 06:49:56 +0000356TypedefDecl *ASTContext::getInt128Decl() const {
357 if (!Int128Decl) {
358 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
359 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
360 getTranslationUnitDecl(),
361 SourceLocation(),
362 SourceLocation(),
363 &Idents.get("__int128_t"),
364 TInfo);
365 }
366
367 return Int128Decl;
368}
369
370TypedefDecl *ASTContext::getUInt128Decl() const {
371 if (!UInt128Decl) {
372 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
373 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
374 getTranslationUnitDecl(),
375 SourceLocation(),
376 SourceLocation(),
377 &Idents.get("__uint128_t"),
378 TInfo);
379 }
380
381 return UInt128Decl;
382}
Reid Spencer5f016e22007-07-11 17:01:13 +0000383
John McCalle27ec8a2009-10-23 23:03:21 +0000384void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000385 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000386 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000387 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000388}
389
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000390void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
391 assert((!this->Target || this->Target == &Target) &&
392 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000393 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000395 this->Target = &Target;
396
397 ABI.reset(createCXXABI(Target));
398 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
399
Reid Spencer5f016e22007-07-11 17:01:13 +0000400 // C99 6.2.5p19.
401 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Reid Spencer5f016e22007-07-11 17:01:13 +0000403 // C99 6.2.5p2.
404 InitBuiltinType(BoolTy, BuiltinType::Bool);
405 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000406 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000407 InitBuiltinType(CharTy, BuiltinType::Char_S);
408 else
409 InitBuiltinType(CharTy, BuiltinType::Char_U);
410 // C99 6.2.5p4.
411 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
412 InitBuiltinType(ShortTy, BuiltinType::Short);
413 InitBuiltinType(IntTy, BuiltinType::Int);
414 InitBuiltinType(LongTy, BuiltinType::Long);
415 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000416
Reid Spencer5f016e22007-07-11 17:01:13 +0000417 // C99 6.2.5p6.
418 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
419 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
420 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
421 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
422 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Reid Spencer5f016e22007-07-11 17:01:13 +0000424 // C99 6.2.5p10.
425 InitBuiltinType(FloatTy, BuiltinType::Float);
426 InitBuiltinType(DoubleTy, BuiltinType::Double);
427 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000428
Chris Lattner2df9ced2009-04-30 02:43:43 +0000429 // GNU extension, 128-bit integers.
430 InitBuiltinType(Int128Ty, BuiltinType::Int128);
431 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
432
Chris Lattner3f59c972010-12-25 23:25:43 +0000433 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedmand3d77cd2011-04-30 19:24:24 +0000434 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattner3f59c972010-12-25 23:25:43 +0000435 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
436 else // -fshort-wchar makes wchar_t be unsigned.
437 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
438 } else // C99
Chris Lattner3a250322009-02-26 23:43:47 +0000439 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000440
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000441 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
442 InitBuiltinType(Char16Ty, BuiltinType::Char16);
443 else // C99
444 Char16Ty = getFromTargetType(Target.getChar16Type());
445
446 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
447 InitBuiltinType(Char32Ty, BuiltinType::Char32);
448 else // C99
449 Char32Ty = getFromTargetType(Target.getChar32Type());
450
Douglas Gregor898574e2008-12-05 23:32:09 +0000451 // Placeholder type for type-dependent expressions whose type is
452 // completely unknown. No code should ever check a type against
453 // DependentTy and users should never see it; however, it is here to
454 // help diagnose failures to properly check for type-dependent
455 // expressions.
456 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000457
John McCall2a984ca2010-10-12 00:20:44 +0000458 // Placeholder type for functions.
459 InitBuiltinType(OverloadTy, BuiltinType::Overload);
460
John McCall864c0412011-04-26 20:42:42 +0000461 // Placeholder type for bound members.
462 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
463
John McCall1de4d4e2011-04-07 08:22:57 +0000464 // "any" type; useful for debugger-like clients.
465 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
466
Reid Spencer5f016e22007-07-11 17:01:13 +0000467 // C99 6.2.5p11.
468 FloatComplexTy = getComplexType(FloatTy);
469 DoubleComplexTy = getComplexType(DoubleTy);
470 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000471
Steve Naroff7e219e42007-10-15 14:41:52 +0000472 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000474 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000475 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
476 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000477 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000478
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000479 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000481 // void * type
482 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000483
484 // nullptr type (C++0x 2.14.7)
485 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000486}
487
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000488Diagnostic &ASTContext::getDiagnostics() const {
489 return SourceMgr.getDiagnostics();
490}
491
Douglas Gregor63200642010-08-30 16:49:28 +0000492AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
493 AttrVec *&Result = DeclAttrs[D];
494 if (!Result) {
495 void *Mem = Allocate(sizeof(AttrVec));
496 Result = new (Mem) AttrVec;
497 }
498
499 return *Result;
500}
501
502/// \brief Erase the attributes corresponding to the given declaration.
503void ASTContext::eraseDeclAttrs(const Decl *D) {
504 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
505 if (Pos != DeclAttrs.end()) {
506 Pos->second->~AttrVec();
507 DeclAttrs.erase(Pos);
508 }
509}
510
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000511MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000512ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000513 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000514 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000515 = InstantiatedFromStaticDataMember.find(Var);
516 if (Pos == InstantiatedFromStaticDataMember.end())
517 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000518
Douglas Gregor7caa6822009-07-24 20:34:43 +0000519 return Pos->second;
520}
521
Mike Stump1eb44332009-09-09 15:08:12 +0000522void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000523ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000524 TemplateSpecializationKind TSK,
525 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000526 assert(Inst->isStaticDataMember() && "Not a static data member");
527 assert(Tmpl->isStaticDataMember() && "Not a static data member");
528 assert(!InstantiatedFromStaticDataMember[Inst] &&
529 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000530 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000531 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000532}
533
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000534FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
535 const FunctionDecl *FD){
536 assert(FD && "Specialization is 0");
537 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000538 = ClassScopeSpecializationPattern.find(FD);
539 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000540 return 0;
541
542 return Pos->second;
543}
544
545void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
546 FunctionDecl *Pattern) {
547 assert(FD && "Specialization is 0");
548 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000549 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000550}
551
John McCall7ba107a2009-11-18 02:36:19 +0000552NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000553ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000554 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000555 = InstantiatedFromUsingDecl.find(UUD);
556 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000557 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000558
Anders Carlsson0d8df782009-08-29 19:37:28 +0000559 return Pos->second;
560}
561
562void
John McCalled976492009-12-04 22:46:56 +0000563ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
564 assert((isa<UsingDecl>(Pattern) ||
565 isa<UnresolvedUsingValueDecl>(Pattern) ||
566 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
567 "pattern decl is not a using decl");
568 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
569 InstantiatedFromUsingDecl[Inst] = Pattern;
570}
571
572UsingShadowDecl *
573ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
574 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
575 = InstantiatedFromUsingShadowDecl.find(Inst);
576 if (Pos == InstantiatedFromUsingShadowDecl.end())
577 return 0;
578
579 return Pos->second;
580}
581
582void
583ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
584 UsingShadowDecl *Pattern) {
585 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
586 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000587}
588
Anders Carlssond8b285f2009-09-01 04:26:58 +0000589FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
590 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
591 = InstantiatedFromUnnamedFieldDecl.find(Field);
592 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
593 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000594
Anders Carlssond8b285f2009-09-01 04:26:58 +0000595 return Pos->second;
596}
597
598void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
599 FieldDecl *Tmpl) {
600 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
601 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
602 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
603 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000604
Anders Carlssond8b285f2009-09-01 04:26:58 +0000605 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
606}
607
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000608bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
609 const FieldDecl *LastFD) const {
610 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Chad Rosier682b7f82011-08-04 21:50:29 +0000611 FD->getBitWidth()->EvaluateAsInt(*this).getZExtValue() == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000612}
613
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000614bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
615 const FieldDecl *LastFD) const {
616 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Chad Rosier682b7f82011-08-04 21:50:29 +0000617 FD->getBitWidth()->EvaluateAsInt(*this).getZExtValue() == 0 &&
618 LastFD->getBitWidth()->EvaluateAsInt(*this).getZExtValue() != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000619}
620
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000621bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
622 const FieldDecl *LastFD) const {
623 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Chad Rosier682b7f82011-08-04 21:50:29 +0000624 FD->getBitWidth()->EvaluateAsInt(*this).getZExtValue() &&
625 LastFD->getBitWidth()->EvaluateAsInt(*this).getZExtValue());
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000626}
627
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000628bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000629 const FieldDecl *LastFD) const {
630 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Chad Rosier682b7f82011-08-04 21:50:29 +0000631 LastFD->getBitWidth()->EvaluateAsInt(*this).getZExtValue());
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000632}
633
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000634bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000635 const FieldDecl *LastFD) const {
636 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Chad Rosier682b7f82011-08-04 21:50:29 +0000637 FD->getBitWidth()->EvaluateAsInt(*this).getZExtValue());
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000638}
639
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000640ASTContext::overridden_cxx_method_iterator
641ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
642 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
643 = OverriddenMethods.find(Method);
644 if (Pos == OverriddenMethods.end())
645 return 0;
646
647 return Pos->second.begin();
648}
649
650ASTContext::overridden_cxx_method_iterator
651ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
652 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
653 = OverriddenMethods.find(Method);
654 if (Pos == OverriddenMethods.end())
655 return 0;
656
657 return Pos->second.end();
658}
659
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000660unsigned
661ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
662 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
663 = OverriddenMethods.find(Method);
664 if (Pos == OverriddenMethods.end())
665 return 0;
666
667 return Pos->second.size();
668}
669
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000670void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
671 const CXXMethodDecl *Overridden) {
672 OverriddenMethods[Method].push_back(Overridden);
673}
674
Chris Lattner464175b2007-07-18 17:52:12 +0000675//===----------------------------------------------------------------------===//
676// Type Sizing and Analysis
677//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000678
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000679/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
680/// scalar floating point type.
681const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000682 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000683 assert(BT && "Not a floating point type!");
684 switch (BT->getKind()) {
685 default: assert(0 && "Not a floating point type!");
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000686 case BuiltinType::Float: return Target->getFloatFormat();
687 case BuiltinType::Double: return Target->getDoubleFormat();
688 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000689 }
690}
691
Ken Dyck8b752f12010-01-27 17:10:57 +0000692/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000693/// specified decl. Note that bitfields do not have a valid alignment, so
694/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000695/// If @p RefAsPointee, references are treated like their underlying type
696/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +0000697CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000698 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +0000699
John McCall4081a5c2010-10-08 18:24:19 +0000700 bool UseAlignAttrOnly = false;
701 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
702 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +0000703
John McCall4081a5c2010-10-08 18:24:19 +0000704 // __attribute__((aligned)) can increase or decrease alignment
705 // *except* on a struct or struct member, where it only increases
706 // alignment unless 'packed' is also specified.
707 //
708 // It is an error for [[align]] to decrease alignment, so we can
709 // ignore that possibility; Sema should diagnose it.
710 if (isa<FieldDecl>(D)) {
711 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
712 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
713 } else {
714 UseAlignAttrOnly = true;
715 }
716 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +0000717 else if (isa<FieldDecl>(D))
718 UseAlignAttrOnly =
719 D->hasAttr<PackedAttr>() ||
720 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +0000721
John McCallba4f5d52011-01-20 07:57:12 +0000722 // If we're using the align attribute only, just ignore everything
723 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +0000724 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +0000725 // do nothing
726
John McCall4081a5c2010-10-08 18:24:19 +0000727 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +0000728 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000729 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000730 if (RefAsPointee)
731 T = RT->getPointeeType();
732 else
733 T = getPointerType(RT->getPointeeType());
734 }
735 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +0000736 // Adjust alignments of declarations with array type by the
737 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000738 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +0000739 const ArrayType *arrayType;
740 if (MinWidth && (arrayType = getAsArrayType(T))) {
741 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000742 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +0000743 else if (isa<ConstantArrayType>(arrayType) &&
744 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000745 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000746
John McCall3b657512011-01-19 10:06:00 +0000747 // Walk through any array types while we're at it.
748 T = getBaseElementType(arrayType);
749 }
Chad Rosier9f1210c2011-07-26 07:03:04 +0000750 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedmandcdafb62009-02-22 02:56:25 +0000751 }
John McCallba4f5d52011-01-20 07:57:12 +0000752
753 // Fields can be subject to extra alignment constraints, like if
754 // the field is packed, the struct is packed, or the struct has a
755 // a max-field-alignment constraint (#pragma pack). So calculate
756 // the actual alignment of the field within the struct, and then
757 // (as we're expected to) constrain that by the alignment of the type.
758 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
759 // So calculate the alignment of the field.
760 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
761
762 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +0000763 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +0000764
765 // Use the GCD of that and the offset within the record.
766 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
767 if (offset > 0) {
768 // Alignment is always a power of 2, so the GCD will be a power of 2,
769 // which means we get to do this crazy thing instead of Euclid's.
770 uint64_t lowBitOfOffset = offset & (~offset + 1);
771 if (lowBitOfOffset < fieldAlign)
772 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
773 }
774
775 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +0000776 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000777 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000778
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000779 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +0000780}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000781
John McCallea1471e2010-05-20 01:18:31 +0000782std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000783ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +0000784 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000785 return std::make_pair(toCharUnitsFromBits(Info.first),
786 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +0000787}
788
789std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000790ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +0000791 return getTypeInfoInChars(T.getTypePtr());
792}
793
Chris Lattnera7674d82007-07-13 22:13:22 +0000794/// getTypeSize - Return the size of the specified type, in bits. This method
795/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000796///
797/// FIXME: Pointers into different addr spaces could have different sizes and
798/// alignment requirements: getPointerInfo should take an AddrSpace, this
799/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000800std::pair<uint64_t, unsigned>
Jay Foad4ba2a172011-01-12 09:06:06 +0000801ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +0000802 uint64_t Width=0;
803 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000804 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000805#define TYPE(Class, Base)
806#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000807#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000808#define DEPENDENT_TYPE(Class, Base) case Type::Class:
809#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +0000810 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000811 break;
812
Chris Lattner692233e2007-07-13 22:27:08 +0000813 case Type::FunctionNoProto:
814 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000815 // GCC extension: alignof(function) = 32 bits
816 Width = 0;
817 Align = 32;
818 break;
819
Douglas Gregor72564e72009-02-26 23:50:07 +0000820 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000821 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000822 Width = 0;
823 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
824 break;
825
Steve Narofffb22d962007-08-30 01:06:46 +0000826 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000827 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000828
Chris Lattner98be4942008-03-05 18:54:05 +0000829 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000830 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000831 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +0000832 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000833 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000834 }
Nate Begeman213541a2008-04-18 23:10:10 +0000835 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000836 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000837 const VectorType *VT = cast<VectorType>(T);
838 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
839 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000840 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000841 // If the alignment is not a power of 2, round up to the next power of 2.
842 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000843 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000844 Align = llvm::NextPowerOf2(Align);
845 Width = llvm::RoundUpToAlignment(Width, Align);
846 }
Chris Lattner030d8842007-07-19 22:06:24 +0000847 break;
848 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000849
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000850 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000851 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000852 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000853 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000854 // GCC extension: alignof(void) = 8 bits.
855 Width = 0;
856 Align = 8;
857 break;
858
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000859 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000860 Width = Target->getBoolWidth();
861 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000862 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000863 case BuiltinType::Char_S:
864 case BuiltinType::Char_U:
865 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000866 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000867 Width = Target->getCharWidth();
868 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000869 break;
Chris Lattner3f59c972010-12-25 23:25:43 +0000870 case BuiltinType::WChar_S:
871 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000872 Width = Target->getWCharWidth();
873 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000874 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000875 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000876 Width = Target->getChar16Width();
877 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000878 break;
879 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000880 Width = Target->getChar32Width();
881 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000882 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000883 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000884 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000885 Width = Target->getShortWidth();
886 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000887 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000888 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000889 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000890 Width = Target->getIntWidth();
891 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000892 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000893 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000894 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000895 Width = Target->getLongWidth();
896 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000897 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000898 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000899 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000900 Width = Target->getLongLongWidth();
901 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000902 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000903 case BuiltinType::Int128:
904 case BuiltinType::UInt128:
905 Width = 128;
906 Align = 128; // int128_t is 128-bit aligned on all targets.
907 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000908 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000909 Width = Target->getFloatWidth();
910 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000911 break;
912 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000913 Width = Target->getDoubleWidth();
914 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000915 break;
916 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000917 Width = Target->getLongDoubleWidth();
918 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000919 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000920 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000921 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
922 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000923 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000924 case BuiltinType::ObjCId:
925 case BuiltinType::ObjCClass:
926 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000927 Width = Target->getPointerWidth(0);
928 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000929 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000930 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000931 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000932 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000933 Width = Target->getPointerWidth(0);
934 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000935 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000936 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000937 unsigned AS = getTargetAddressSpace(
938 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000939 Width = Target->getPointerWidth(AS);
940 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +0000941 break;
942 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000943 case Type::LValueReference:
944 case Type::RValueReference: {
945 // alignof and sizeof should never enter this code path here, so we go
946 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000947 unsigned AS = getTargetAddressSpace(
948 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000949 Width = Target->getPointerWidth(AS);
950 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +0000951 break;
952 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000953 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000954 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000955 Width = Target->getPointerWidth(AS);
956 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000957 break;
958 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000959 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +0000960 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000961 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000962 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +0000963 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000964 Align = PtrDiffInfo.second;
965 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000966 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000967 case Type::Complex: {
968 // Complex types have the same alignment as their elements, but twice the
969 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000970 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000971 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000972 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000973 Align = EltInfo.second;
974 break;
975 }
John McCallc12c5bb2010-05-15 11:32:37 +0000976 case Type::ObjCObject:
977 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000978 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000979 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000980 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +0000981 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +0000982 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +0000983 break;
984 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000985 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000986 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000987 const TagType *TT = cast<TagType>(T);
988
989 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +0000990 Width = 8;
991 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +0000992 break;
993 }
Mike Stump1eb44332009-09-09 15:08:12 +0000994
Daniel Dunbar1d751182008-11-08 05:48:37 +0000995 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000996 return getTypeInfo(ET->getDecl()->getIntegerType());
997
Daniel Dunbar1d751182008-11-08 05:48:37 +0000998 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000999 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001000 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001001 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001002 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001003 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001004
Chris Lattner9fcfe922009-10-22 05:17:15 +00001005 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001006 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1007 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001008
Richard Smith34b41d92011-02-20 03:19:35 +00001009 case Type::Auto: {
1010 const AutoType *A = cast<AutoType>(T);
1011 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001012 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001013 }
1014
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001015 case Type::Paren:
1016 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1017
Douglas Gregor18857642009-04-30 17:32:17 +00001018 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001019 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001020 std::pair<uint64_t, unsigned> Info
1021 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001022 // If the typedef has an aligned attribute on it, it overrides any computed
1023 // alignment we have. This violates the GCC documentation (which says that
1024 // attribute(aligned) can only round up) but matches its implementation.
1025 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1026 Align = AttrAlign;
1027 else
1028 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001029 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001030 break;
Chris Lattner71763312008-04-06 22:05:18 +00001031 }
Douglas Gregor18857642009-04-30 17:32:17 +00001032
1033 case Type::TypeOfExpr:
1034 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1035 .getTypePtr());
1036
1037 case Type::TypeOf:
1038 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1039
Anders Carlsson395b4752009-06-24 19:06:50 +00001040 case Type::Decltype:
1041 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1042 .getTypePtr());
1043
Sean Huntca63c202011-05-24 22:41:36 +00001044 case Type::UnaryTransform:
1045 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1046
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001047 case Type::Elaborated:
1048 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001049
John McCall9d156a72011-01-06 01:58:22 +00001050 case Type::Attributed:
1051 return getTypeInfo(
1052 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1053
Richard Smith3e4c6c42011-05-05 21:57:07 +00001054 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001055 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001056 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001057 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1058 // A type alias template specialization may refer to a typedef with the
1059 // aligned attribute on it.
1060 if (TST->isTypeAlias())
1061 return getTypeInfo(TST->getAliasedType().getTypePtr());
1062 else
1063 return getTypeInfo(getCanonicalType(T));
1064 }
1065
Douglas Gregor18857642009-04-30 17:32:17 +00001066 }
Mike Stump1eb44332009-09-09 15:08:12 +00001067
Chris Lattner464175b2007-07-18 17:52:12 +00001068 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001069 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001070}
1071
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001072/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1073CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1074 return CharUnits::fromQuantity(BitSize / getCharWidth());
1075}
1076
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001077/// toBits - Convert a size in characters to a size in characters.
1078int64_t ASTContext::toBits(CharUnits CharSize) const {
1079 return CharSize.getQuantity() * getCharWidth();
1080}
1081
Ken Dyckbdc601b2009-12-22 14:23:30 +00001082/// getTypeSizeInChars - Return the size of the specified type, in characters.
1083/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001084CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001085 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001086}
Jay Foad4ba2a172011-01-12 09:06:06 +00001087CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001088 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001089}
1090
Ken Dyck16e20cc2010-01-26 17:25:18 +00001091/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001092/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001093CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001094 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001095}
Jay Foad4ba2a172011-01-12 09:06:06 +00001096CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001097 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001098}
1099
Chris Lattner34ebde42009-01-27 18:08:34 +00001100/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1101/// type for the current target in bits. This can be different than the ABI
1102/// alignment in cases where it is beneficial for performance to overalign
1103/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001104unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001105 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001106
1107 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001108 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001109 T = CT->getElementType().getTypePtr();
1110 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1111 T->isSpecificBuiltinType(BuiltinType::LongLong))
1112 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1113
Chris Lattner34ebde42009-01-27 18:08:34 +00001114 return ABIAlign;
1115}
1116
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001117/// DeepCollectObjCIvars -
1118/// This routine first collects all declared, but not synthesized, ivars in
1119/// super class and then collects all ivars, including those synthesized for
1120/// current class. This routine is used for implementation of current class
1121/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001122///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001123void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1124 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001125 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001126 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1127 DeepCollectObjCIvars(SuperClass, false, Ivars);
1128 if (!leafClass) {
1129 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1130 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanian11062e12010-02-19 00:31:17 +00001131 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001132 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001133 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001134 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001135 Iv= Iv->getNextIvar())
1136 Ivars.push_back(Iv);
1137 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001138}
1139
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001140/// CollectInheritedProtocols - Collect all protocols in current class and
1141/// those inherited by it.
1142void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001143 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001144 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001145 // We can use protocol_iterator here instead of
1146 // all_referenced_protocol_iterator since we are walking all categories.
1147 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1148 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001149 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001150 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001151 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001152 PE = Proto->protocol_end(); P != PE; ++P) {
1153 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001154 CollectInheritedProtocols(*P, Protocols);
1155 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001156 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001157
1158 // Categories of this Interface.
1159 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1160 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1161 CollectInheritedProtocols(CDeclChain, Protocols);
1162 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1163 while (SD) {
1164 CollectInheritedProtocols(SD, Protocols);
1165 SD = SD->getSuperClass();
1166 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001167 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001168 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001169 PE = OC->protocol_end(); P != PE; ++P) {
1170 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001171 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001172 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1173 PE = Proto->protocol_end(); P != PE; ++P)
1174 CollectInheritedProtocols(*P, Protocols);
1175 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001176 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001177 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1178 PE = OP->protocol_end(); P != PE; ++P) {
1179 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001180 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001181 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1182 PE = Proto->protocol_end(); P != PE; ++P)
1183 CollectInheritedProtocols(*P, Protocols);
1184 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001185 }
1186}
1187
Jay Foad4ba2a172011-01-12 09:06:06 +00001188unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001189 unsigned count = 0;
1190 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001191 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1192 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001193 count += CDecl->ivar_size();
1194
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001195 // Count ivar defined in this class's implementation. This
1196 // includes synthesized ivars.
1197 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001198 count += ImplDecl->ivar_size();
1199
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001200 return count;
1201}
1202
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001203/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1204ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1205 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1206 I = ObjCImpls.find(D);
1207 if (I != ObjCImpls.end())
1208 return cast<ObjCImplementationDecl>(I->second);
1209 return 0;
1210}
1211/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1212ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1213 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1214 I = ObjCImpls.find(D);
1215 if (I != ObjCImpls.end())
1216 return cast<ObjCCategoryImplDecl>(I->second);
1217 return 0;
1218}
1219
1220/// \brief Set the implementation of ObjCInterfaceDecl.
1221void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1222 ObjCImplementationDecl *ImplD) {
1223 assert(IFaceD && ImplD && "Passed null params");
1224 ObjCImpls[IFaceD] = ImplD;
1225}
1226/// \brief Set the implementation of ObjCCategoryDecl.
1227void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1228 ObjCCategoryImplDecl *ImplD) {
1229 assert(CatD && ImplD && "Passed null params");
1230 ObjCImpls[CatD] = ImplD;
1231}
1232
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001233/// \brief Get the copy initialization expression of VarDecl,or NULL if
1234/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001235Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001236 assert(VD && "Passed null params");
1237 assert(VD->hasAttr<BlocksAttr>() &&
1238 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001239 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001240 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001241 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1242}
1243
1244/// \brief Set the copy inialization expression of a block var decl.
1245void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1246 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001247 assert(VD->hasAttr<BlocksAttr>() &&
1248 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001249 BlockVarCopyInits[VD] = Init;
1250}
1251
John McCalla93c9342009-12-07 02:54:59 +00001252/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001253///
John McCalla93c9342009-12-07 02:54:59 +00001254/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001255/// the TypeLoc wrappers.
1256///
1257/// \param T the type that will be the basis for type source info. This type
1258/// should refer to how the declarator was written in source code, not to
1259/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001260TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001261 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001262 if (!DataSize)
1263 DataSize = TypeLoc::getFullDataSizeForType(T);
1264 else
1265 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001266 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001267
John McCalla93c9342009-12-07 02:54:59 +00001268 TypeSourceInfo *TInfo =
1269 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1270 new (TInfo) TypeSourceInfo(T);
1271 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001272}
1273
John McCalla93c9342009-12-07 02:54:59 +00001274TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001275 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001276 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001277 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001278 return DI;
1279}
1280
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001281const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001282ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001283 return getObjCLayout(D, 0);
1284}
1285
1286const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001287ASTContext::getASTObjCImplementationLayout(
1288 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001289 return getObjCLayout(D->getClassInterface(), D);
1290}
1291
Chris Lattnera7674d82007-07-13 22:13:22 +00001292//===----------------------------------------------------------------------===//
1293// Type creation/memoization methods
1294//===----------------------------------------------------------------------===//
1295
Jay Foad4ba2a172011-01-12 09:06:06 +00001296QualType
John McCall3b657512011-01-19 10:06:00 +00001297ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1298 unsigned fastQuals = quals.getFastQualifiers();
1299 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001300
1301 // Check if we've already instantiated this type.
1302 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001303 ExtQuals::Profile(ID, baseType, quals);
1304 void *insertPos = 0;
1305 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1306 assert(eq->getQualifiers() == quals);
1307 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001308 }
1309
John McCall3b657512011-01-19 10:06:00 +00001310 // If the base type is not canonical, make the appropriate canonical type.
1311 QualType canon;
1312 if (!baseType->isCanonicalUnqualified()) {
1313 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1314 canonSplit.second.addConsistentQualifiers(quals);
1315 canon = getExtQualType(canonSplit.first, canonSplit.second);
1316
1317 // Re-find the insert position.
1318 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1319 }
1320
1321 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1322 ExtQualNodes.InsertNode(eq, insertPos);
1323 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001324}
1325
Jay Foad4ba2a172011-01-12 09:06:06 +00001326QualType
1327ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001328 QualType CanT = getCanonicalType(T);
1329 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001330 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001331
John McCall0953e762009-09-24 19:53:00 +00001332 // If we are composing extended qualifiers together, merge together
1333 // into one ExtQuals node.
1334 QualifierCollector Quals;
1335 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001336
John McCall0953e762009-09-24 19:53:00 +00001337 // If this type already has an address space specified, it cannot get
1338 // another one.
1339 assert(!Quals.hasAddressSpace() &&
1340 "Type cannot be in multiple addr spaces!");
1341 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001342
John McCall0953e762009-09-24 19:53:00 +00001343 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001344}
1345
Chris Lattnerb7d25532009-02-18 22:53:11 +00001346QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001347 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001348 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001349 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001350 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001351
John McCall7f040a92010-12-24 02:08:15 +00001352 if (const PointerType *ptr = T->getAs<PointerType>()) {
1353 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001354 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001355 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1356 return getPointerType(ResultType);
1357 }
1358 }
Mike Stump1eb44332009-09-09 15:08:12 +00001359
John McCall0953e762009-09-24 19:53:00 +00001360 // If we are composing extended qualifiers together, merge together
1361 // into one ExtQuals node.
1362 QualifierCollector Quals;
1363 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001364
John McCall0953e762009-09-24 19:53:00 +00001365 // If this type already has an ObjCGC specified, it cannot get
1366 // another one.
1367 assert(!Quals.hasObjCGCAttr() &&
1368 "Type cannot have multiple ObjCGCs!");
1369 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001370
John McCall0953e762009-09-24 19:53:00 +00001371 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001372}
Chris Lattnera7674d82007-07-13 22:13:22 +00001373
John McCalle6a365d2010-12-19 02:44:49 +00001374const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1375 FunctionType::ExtInfo Info) {
1376 if (T->getExtInfo() == Info)
1377 return T;
1378
1379 QualType Result;
1380 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1381 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1382 } else {
1383 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1384 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1385 EPI.ExtInfo = Info;
1386 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1387 FPT->getNumArgs(), EPI);
1388 }
1389
1390 return cast<FunctionType>(Result.getTypePtr());
1391}
1392
Reid Spencer5f016e22007-07-11 17:01:13 +00001393/// getComplexType - Return the uniqued reference to the type for a complex
1394/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001395QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001396 // Unique pointers, to guarantee there is only one pointer of a particular
1397 // structure.
1398 llvm::FoldingSetNodeID ID;
1399 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001400
Reid Spencer5f016e22007-07-11 17:01:13 +00001401 void *InsertPos = 0;
1402 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1403 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001404
Reid Spencer5f016e22007-07-11 17:01:13 +00001405 // If the pointee type isn't canonical, this won't be a canonical type either,
1406 // so fill in the canonical type field.
1407 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001408 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001409 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001410
Reid Spencer5f016e22007-07-11 17:01:13 +00001411 // Get the new insert position for the node we care about.
1412 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001413 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001414 }
John McCall6b304a02009-09-24 23:30:46 +00001415 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001416 Types.push_back(New);
1417 ComplexTypes.InsertNode(New, InsertPos);
1418 return QualType(New, 0);
1419}
1420
Reid Spencer5f016e22007-07-11 17:01:13 +00001421/// getPointerType - Return the uniqued reference to the type for a pointer to
1422/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001423QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001424 // Unique pointers, to guarantee there is only one pointer of a particular
1425 // structure.
1426 llvm::FoldingSetNodeID ID;
1427 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001428
Reid Spencer5f016e22007-07-11 17:01:13 +00001429 void *InsertPos = 0;
1430 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1431 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001432
Reid Spencer5f016e22007-07-11 17:01:13 +00001433 // If the pointee type isn't canonical, this won't be a canonical type either,
1434 // so fill in the canonical type field.
1435 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001436 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001437 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001438
Reid Spencer5f016e22007-07-11 17:01:13 +00001439 // Get the new insert position for the node we care about.
1440 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001441 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001442 }
John McCall6b304a02009-09-24 23:30:46 +00001443 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001444 Types.push_back(New);
1445 PointerTypes.InsertNode(New, InsertPos);
1446 return QualType(New, 0);
1447}
1448
Mike Stump1eb44332009-09-09 15:08:12 +00001449/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001450/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001451QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001452 assert(T->isFunctionType() && "block of function types only");
1453 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001454 // structure.
1455 llvm::FoldingSetNodeID ID;
1456 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001457
Steve Naroff5618bd42008-08-27 16:04:49 +00001458 void *InsertPos = 0;
1459 if (BlockPointerType *PT =
1460 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1461 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001462
1463 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001464 // type either so fill in the canonical type field.
1465 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001466 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001467 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Steve Naroff5618bd42008-08-27 16:04:49 +00001469 // Get the new insert position for the node we care about.
1470 BlockPointerType *NewIP =
1471 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001472 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001473 }
John McCall6b304a02009-09-24 23:30:46 +00001474 BlockPointerType *New
1475 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001476 Types.push_back(New);
1477 BlockPointerTypes.InsertNode(New, InsertPos);
1478 return QualType(New, 0);
1479}
1480
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001481/// getLValueReferenceType - Return the uniqued reference to the type for an
1482/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001483QualType
1484ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00001485 assert(getCanonicalType(T) != OverloadTy &&
1486 "Unresolved overloaded function type");
1487
Reid Spencer5f016e22007-07-11 17:01:13 +00001488 // Unique pointers, to guarantee there is only one pointer of a particular
1489 // structure.
1490 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001491 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001492
1493 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001494 if (LValueReferenceType *RT =
1495 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001496 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001497
John McCall54e14c42009-10-22 22:37:11 +00001498 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1499
Reid Spencer5f016e22007-07-11 17:01:13 +00001500 // If the referencee type isn't canonical, this won't be a canonical type
1501 // either, so fill in the canonical type field.
1502 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001503 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1504 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1505 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001506
Reid Spencer5f016e22007-07-11 17:01:13 +00001507 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001508 LValueReferenceType *NewIP =
1509 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001510 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001511 }
1512
John McCall6b304a02009-09-24 23:30:46 +00001513 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001514 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1515 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001516 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001517 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001518
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001519 return QualType(New, 0);
1520}
1521
1522/// getRValueReferenceType - Return the uniqued reference to the type for an
1523/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001524QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001525 // Unique pointers, to guarantee there is only one pointer of a particular
1526 // structure.
1527 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001528 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001529
1530 void *InsertPos = 0;
1531 if (RValueReferenceType *RT =
1532 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1533 return QualType(RT, 0);
1534
John McCall54e14c42009-10-22 22:37:11 +00001535 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1536
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001537 // If the referencee type isn't canonical, this won't be a canonical type
1538 // either, so fill in the canonical type field.
1539 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001540 if (InnerRef || !T.isCanonical()) {
1541 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1542 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001543
1544 // Get the new insert position for the node we care about.
1545 RValueReferenceType *NewIP =
1546 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001547 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001548 }
1549
John McCall6b304a02009-09-24 23:30:46 +00001550 RValueReferenceType *New
1551 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001552 Types.push_back(New);
1553 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001554 return QualType(New, 0);
1555}
1556
Sebastian Redlf30208a2009-01-24 21:16:55 +00001557/// getMemberPointerType - Return the uniqued reference to the type for a
1558/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00001559QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001560 // Unique pointers, to guarantee there is only one pointer of a particular
1561 // structure.
1562 llvm::FoldingSetNodeID ID;
1563 MemberPointerType::Profile(ID, T, Cls);
1564
1565 void *InsertPos = 0;
1566 if (MemberPointerType *PT =
1567 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1568 return QualType(PT, 0);
1569
1570 // If the pointee or class type isn't canonical, this won't be a canonical
1571 // type either, so fill in the canonical type field.
1572 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001573 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001574 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1575
1576 // Get the new insert position for the node we care about.
1577 MemberPointerType *NewIP =
1578 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001579 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001580 }
John McCall6b304a02009-09-24 23:30:46 +00001581 MemberPointerType *New
1582 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001583 Types.push_back(New);
1584 MemberPointerTypes.InsertNode(New, InsertPos);
1585 return QualType(New, 0);
1586}
1587
Mike Stump1eb44332009-09-09 15:08:12 +00001588/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001589/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001590QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001591 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001592 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001593 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001594 assert((EltTy->isDependentType() ||
1595 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001596 "Constant array of VLAs is illegal!");
1597
Chris Lattner38aeec72009-05-13 04:12:56 +00001598 // Convert the array size into a canonical width matching the pointer size for
1599 // the target.
1600 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001601 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001602 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00001603
Reid Spencer5f016e22007-07-11 17:01:13 +00001604 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001605 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001606
Reid Spencer5f016e22007-07-11 17:01:13 +00001607 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001608 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001609 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001610 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001611
John McCall3b657512011-01-19 10:06:00 +00001612 // If the element type isn't canonical or has qualifiers, this won't
1613 // be a canonical type either, so fill in the canonical type field.
1614 QualType Canon;
1615 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1616 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1617 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001618 ASM, IndexTypeQuals);
John McCall3b657512011-01-19 10:06:00 +00001619 Canon = getQualifiedType(Canon, canonSplit.second);
1620
Reid Spencer5f016e22007-07-11 17:01:13 +00001621 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001622 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001623 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001624 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001625 }
Mike Stump1eb44332009-09-09 15:08:12 +00001626
John McCall6b304a02009-09-24 23:30:46 +00001627 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001628 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001629 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001630 Types.push_back(New);
1631 return QualType(New, 0);
1632}
1633
John McCallce889032011-01-18 08:40:38 +00001634/// getVariableArrayDecayedType - Turns the given type, which may be
1635/// variably-modified, into the corresponding type with all the known
1636/// sizes replaced with [*].
1637QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1638 // Vastly most common case.
1639 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001640
John McCallce889032011-01-18 08:40:38 +00001641 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001642
John McCallce889032011-01-18 08:40:38 +00001643 SplitQualType split = type.getSplitDesugaredType();
1644 const Type *ty = split.first;
1645 switch (ty->getTypeClass()) {
1646#define TYPE(Class, Base)
1647#define ABSTRACT_TYPE(Class, Base)
1648#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1649#include "clang/AST/TypeNodes.def"
1650 llvm_unreachable("didn't desugar past all non-canonical types?");
1651
1652 // These types should never be variably-modified.
1653 case Type::Builtin:
1654 case Type::Complex:
1655 case Type::Vector:
1656 case Type::ExtVector:
1657 case Type::DependentSizedExtVector:
1658 case Type::ObjCObject:
1659 case Type::ObjCInterface:
1660 case Type::ObjCObjectPointer:
1661 case Type::Record:
1662 case Type::Enum:
1663 case Type::UnresolvedUsing:
1664 case Type::TypeOfExpr:
1665 case Type::TypeOf:
1666 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00001667 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00001668 case Type::DependentName:
1669 case Type::InjectedClassName:
1670 case Type::TemplateSpecialization:
1671 case Type::DependentTemplateSpecialization:
1672 case Type::TemplateTypeParm:
1673 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00001674 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00001675 case Type::PackExpansion:
1676 llvm_unreachable("type should never be variably-modified");
1677
1678 // These types can be variably-modified but should never need to
1679 // further decay.
1680 case Type::FunctionNoProto:
1681 case Type::FunctionProto:
1682 case Type::BlockPointer:
1683 case Type::MemberPointer:
1684 return type;
1685
1686 // These types can be variably-modified. All these modifications
1687 // preserve structure except as noted by comments.
1688 // TODO: if we ever care about optimizing VLAs, there are no-op
1689 // optimizations available here.
1690 case Type::Pointer:
1691 result = getPointerType(getVariableArrayDecayedType(
1692 cast<PointerType>(ty)->getPointeeType()));
1693 break;
1694
1695 case Type::LValueReference: {
1696 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1697 result = getLValueReferenceType(
1698 getVariableArrayDecayedType(lv->getPointeeType()),
1699 lv->isSpelledAsLValue());
1700 break;
1701 }
1702
1703 case Type::RValueReference: {
1704 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1705 result = getRValueReferenceType(
1706 getVariableArrayDecayedType(lv->getPointeeType()));
1707 break;
1708 }
1709
1710 case Type::ConstantArray: {
1711 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1712 result = getConstantArrayType(
1713 getVariableArrayDecayedType(cat->getElementType()),
1714 cat->getSize(),
1715 cat->getSizeModifier(),
1716 cat->getIndexTypeCVRQualifiers());
1717 break;
1718 }
1719
1720 case Type::DependentSizedArray: {
1721 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1722 result = getDependentSizedArrayType(
1723 getVariableArrayDecayedType(dat->getElementType()),
1724 dat->getSizeExpr(),
1725 dat->getSizeModifier(),
1726 dat->getIndexTypeCVRQualifiers(),
1727 dat->getBracketsRange());
1728 break;
1729 }
1730
1731 // Turn incomplete types into [*] types.
1732 case Type::IncompleteArray: {
1733 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1734 result = getVariableArrayType(
1735 getVariableArrayDecayedType(iat->getElementType()),
1736 /*size*/ 0,
1737 ArrayType::Normal,
1738 iat->getIndexTypeCVRQualifiers(),
1739 SourceRange());
1740 break;
1741 }
1742
1743 // Turn VLA types into [*] types.
1744 case Type::VariableArray: {
1745 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1746 result = getVariableArrayType(
1747 getVariableArrayDecayedType(vat->getElementType()),
1748 /*size*/ 0,
1749 ArrayType::Star,
1750 vat->getIndexTypeCVRQualifiers(),
1751 vat->getBracketsRange());
1752 break;
1753 }
1754 }
1755
1756 // Apply the top-level qualifiers from the original.
1757 return getQualifiedType(result, split.second);
1758}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001759
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001760/// getVariableArrayType - Returns a non-unique reference to the type for a
1761/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001762QualType ASTContext::getVariableArrayType(QualType EltTy,
1763 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001764 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001765 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00001766 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001767 // Since we don't unique expressions, it isn't possible to unique VLA's
1768 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00001769 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00001770
John McCall3b657512011-01-19 10:06:00 +00001771 // Be sure to pull qualifiers off the element type.
1772 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1773 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1774 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001775 IndexTypeQuals, Brackets);
John McCall3b657512011-01-19 10:06:00 +00001776 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor715e9c82010-05-23 16:10:32 +00001777 }
1778
John McCall6b304a02009-09-24 23:30:46 +00001779 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001780 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001781
1782 VariableArrayTypes.push_back(New);
1783 Types.push_back(New);
1784 return QualType(New, 0);
1785}
1786
Douglas Gregor898574e2008-12-05 23:32:09 +00001787/// getDependentSizedArrayType - Returns a non-unique reference to
1788/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001789/// type.
John McCall3b657512011-01-19 10:06:00 +00001790QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1791 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00001792 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001793 unsigned elementTypeQuals,
1794 SourceRange brackets) const {
1795 assert((!numElements || numElements->isTypeDependent() ||
1796 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001797 "Size must be type- or value-dependent!");
1798
John McCall3b657512011-01-19 10:06:00 +00001799 // Dependently-sized array types that do not have a specified number
1800 // of elements will have their sizes deduced from a dependent
1801 // initializer. We do no canonicalization here at all, which is okay
1802 // because they can't be used in most locations.
1803 if (!numElements) {
1804 DependentSizedArrayType *newType
1805 = new (*this, TypeAlignment)
1806 DependentSizedArrayType(*this, elementType, QualType(),
1807 numElements, ASM, elementTypeQuals,
1808 brackets);
1809 Types.push_back(newType);
1810 return QualType(newType, 0);
1811 }
1812
1813 // Otherwise, we actually build a new type every time, but we
1814 // also build a canonical type.
1815
1816 SplitQualType canonElementType = getCanonicalType(elementType).split();
1817
1818 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001819 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001820 DependentSizedArrayType::Profile(ID, *this,
1821 QualType(canonElementType.first, 0),
1822 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001823
John McCall3b657512011-01-19 10:06:00 +00001824 // Look for an existing type with these properties.
1825 DependentSizedArrayType *canonTy =
1826 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001827
John McCall3b657512011-01-19 10:06:00 +00001828 // If we don't have one, build one.
1829 if (!canonTy) {
1830 canonTy = new (*this, TypeAlignment)
1831 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1832 QualType(), numElements, ASM, elementTypeQuals,
1833 brackets);
1834 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1835 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001836 }
1837
John McCall3b657512011-01-19 10:06:00 +00001838 // Apply qualifiers from the element type to the array.
1839 QualType canon = getQualifiedType(QualType(canonTy,0),
1840 canonElementType.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001841
John McCall3b657512011-01-19 10:06:00 +00001842 // If we didn't need extra canonicalization for the element type,
1843 // then just use that as our result.
1844 if (QualType(canonElementType.first, 0) == elementType)
1845 return canon;
1846
1847 // Otherwise, we need to build a type which follows the spelling
1848 // of the element type.
1849 DependentSizedArrayType *sugaredType
1850 = new (*this, TypeAlignment)
1851 DependentSizedArrayType(*this, elementType, canon, numElements,
1852 ASM, elementTypeQuals, brackets);
1853 Types.push_back(sugaredType);
1854 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00001855}
1856
John McCall3b657512011-01-19 10:06:00 +00001857QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00001858 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001859 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001860 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001861 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001862
John McCall3b657512011-01-19 10:06:00 +00001863 void *insertPos = 0;
1864 if (IncompleteArrayType *iat =
1865 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1866 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001867
1868 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00001869 // either, so fill in the canonical type field. We also have to pull
1870 // qualifiers off the element type.
1871 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00001872
John McCall3b657512011-01-19 10:06:00 +00001873 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1874 SplitQualType canonSplit = getCanonicalType(elementType).split();
1875 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1876 ASM, elementTypeQuals);
1877 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001878
1879 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00001880 IncompleteArrayType *existing =
1881 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1882 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001883 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001884
John McCall3b657512011-01-19 10:06:00 +00001885 IncompleteArrayType *newType = new (*this, TypeAlignment)
1886 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001887
John McCall3b657512011-01-19 10:06:00 +00001888 IncompleteArrayTypes.InsertNode(newType, insertPos);
1889 Types.push_back(newType);
1890 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001891}
1892
Steve Naroff73322922007-07-18 18:00:27 +00001893/// getVectorType - Return the unique reference to a vector type of
1894/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001895QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00001896 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00001897 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001898
Reid Spencer5f016e22007-07-11 17:01:13 +00001899 // Check if we've already instantiated a vector of this type.
1900 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00001901 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00001902
Reid Spencer5f016e22007-07-11 17:01:13 +00001903 void *InsertPos = 0;
1904 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1905 return QualType(VTP, 0);
1906
1907 // If the element type isn't canonical, this won't be a canonical type either,
1908 // so fill in the canonical type field.
1909 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00001910 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00001911 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00001912
Reid Spencer5f016e22007-07-11 17:01:13 +00001913 // Get the new insert position for the node we care about.
1914 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001915 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001916 }
John McCall6b304a02009-09-24 23:30:46 +00001917 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00001918 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001919 VectorTypes.InsertNode(New, InsertPos);
1920 Types.push_back(New);
1921 return QualType(New, 0);
1922}
1923
Nate Begeman213541a2008-04-18 23:10:10 +00001924/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001925/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001926QualType
1927ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00001928 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00001929
Steve Naroff73322922007-07-18 18:00:27 +00001930 // Check if we've already instantiated a vector of this type.
1931 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001932 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001933 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00001934 void *InsertPos = 0;
1935 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1936 return QualType(VTP, 0);
1937
1938 // If the element type isn't canonical, this won't be a canonical type either,
1939 // so fill in the canonical type field.
1940 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001941 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001942 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001943
Steve Naroff73322922007-07-18 18:00:27 +00001944 // Get the new insert position for the node we care about.
1945 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001946 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001947 }
John McCall6b304a02009-09-24 23:30:46 +00001948 ExtVectorType *New = new (*this, TypeAlignment)
1949 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001950 VectorTypes.InsertNode(New, InsertPos);
1951 Types.push_back(New);
1952 return QualType(New, 0);
1953}
1954
Jay Foad4ba2a172011-01-12 09:06:06 +00001955QualType
1956ASTContext::getDependentSizedExtVectorType(QualType vecType,
1957 Expr *SizeExpr,
1958 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001959 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001960 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001961 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001962
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001963 void *InsertPos = 0;
1964 DependentSizedExtVectorType *Canon
1965 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1966 DependentSizedExtVectorType *New;
1967 if (Canon) {
1968 // We already have a canonical version of this array type; use it as
1969 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001970 New = new (*this, TypeAlignment)
1971 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1972 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001973 } else {
1974 QualType CanonVecTy = getCanonicalType(vecType);
1975 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001976 New = new (*this, TypeAlignment)
1977 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1978 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001979
1980 DependentSizedExtVectorType *CanonCheck
1981 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1982 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1983 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001984 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1985 } else {
1986 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1987 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001988 New = new (*this, TypeAlignment)
1989 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001990 }
1991 }
Mike Stump1eb44332009-09-09 15:08:12 +00001992
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001993 Types.push_back(New);
1994 return QualType(New, 0);
1995}
1996
Douglas Gregor72564e72009-02-26 23:50:07 +00001997/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001998///
Jay Foad4ba2a172011-01-12 09:06:06 +00001999QualType
2000ASTContext::getFunctionNoProtoType(QualType ResultTy,
2001 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002002 const CallingConv DefaultCC = Info.getCC();
2003 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2004 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002005 // Unique functions, to guarantee there is only one function of a particular
2006 // structure.
2007 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002008 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002009
Reid Spencer5f016e22007-07-11 17:01:13 +00002010 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002011 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002012 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002013 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002014
Reid Spencer5f016e22007-07-11 17:01:13 +00002015 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002016 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002017 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002018 Canonical =
2019 getFunctionNoProtoType(getCanonicalType(ResultTy),
2020 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002021
Reid Spencer5f016e22007-07-11 17:01:13 +00002022 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002023 FunctionNoProtoType *NewIP =
2024 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002025 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002026 }
Mike Stump1eb44332009-09-09 15:08:12 +00002027
Roman Divackycfe9af22011-03-01 17:40:53 +00002028 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002029 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002030 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002031 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002032 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002033 return QualType(New, 0);
2034}
2035
2036/// getFunctionType - Return a normal function type with a typed argument
2037/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002038QualType
2039ASTContext::getFunctionType(QualType ResultTy,
2040 const QualType *ArgArray, unsigned NumArgs,
2041 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002042 // Unique functions, to guarantee there is only one function of a particular
2043 // structure.
2044 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002045 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002046
2047 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002048 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002049 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002050 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002051
2052 // Determine whether the type being created is already canonical or not.
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002053 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00002054 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002055 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002056 isCanonical = false;
2057
Roman Divackycfe9af22011-03-01 17:40:53 +00002058 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2059 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2060 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002061
Reid Spencer5f016e22007-07-11 17:01:13 +00002062 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002063 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002064 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002065 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002066 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002067 CanonicalArgs.reserve(NumArgs);
2068 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002069 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002070
John McCalle23cf432010-12-14 08:05:40 +00002071 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002072 CanonicalEPI.ExceptionSpecType = EST_None;
2073 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002074 CanonicalEPI.ExtInfo
2075 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2076
Chris Lattnerf52ab252008-04-06 22:59:24 +00002077 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00002078 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002079 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002080
Reid Spencer5f016e22007-07-11 17:01:13 +00002081 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002082 FunctionProtoType *NewIP =
2083 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002084 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002085 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002086
John McCallf85e1932011-06-15 23:02:42 +00002087 // FunctionProtoType objects are allocated with extra bytes after
2088 // them for three variable size arrays at the end:
2089 // - parameter types
2090 // - exception types
2091 // - consumed-arguments flags
2092 // Instead of the exception types, there could be a noexcept
2093 // expression.
John McCalle23cf432010-12-14 08:05:40 +00002094 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002095 NumArgs * sizeof(QualType);
2096 if (EPI.ExceptionSpecType == EST_Dynamic)
2097 Size += EPI.NumExceptions * sizeof(QualType);
2098 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002099 Size += sizeof(Expr*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002100 }
John McCallf85e1932011-06-15 23:02:42 +00002101 if (EPI.ConsumedArguments)
2102 Size += NumArgs * sizeof(bool);
2103
John McCalle23cf432010-12-14 08:05:40 +00002104 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002105 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2106 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002107 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002108 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002109 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002110 return QualType(FTP, 0);
2111}
2112
John McCall3cb0ebd2010-03-10 03:28:59 +00002113#ifndef NDEBUG
2114static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2115 if (!isa<CXXRecordDecl>(D)) return false;
2116 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2117 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2118 return true;
2119 if (RD->getDescribedClassTemplate() &&
2120 !isa<ClassTemplateSpecializationDecl>(RD))
2121 return true;
2122 return false;
2123}
2124#endif
2125
2126/// getInjectedClassNameType - Return the unique reference to the
2127/// injected class name type for the specified templated declaration.
2128QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002129 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002130 assert(NeedsInjectedClassNameType(Decl));
2131 if (Decl->TypeForDecl) {
2132 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00002133 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002134 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2135 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2136 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2137 } else {
John McCallf4c73712011-01-19 06:33:43 +00002138 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002139 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002140 Decl->TypeForDecl = newType;
2141 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002142 }
2143 return QualType(Decl->TypeForDecl, 0);
2144}
2145
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002146/// getTypeDeclType - Return the unique reference to the type for the
2147/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002148QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002149 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002150 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002151
Richard Smith162e1c12011-04-15 14:24:37 +00002152 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002153 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002154
John McCallbecb8d52010-03-10 06:48:02 +00002155 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2156 "Template type parameter types are always available.");
2157
John McCall19c85762010-02-16 03:57:14 +00002158 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002159 assert(!Record->getPreviousDeclaration() &&
2160 "struct/union has previous declaration");
2161 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002162 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002163 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002164 assert(!Enum->getPreviousDeclaration() &&
2165 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002166 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002167 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002168 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002169 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2170 Decl->TypeForDecl = newType;
2171 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002172 } else
John McCallbecb8d52010-03-10 06:48:02 +00002173 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002174
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002175 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002176}
2177
Reid Spencer5f016e22007-07-11 17:01:13 +00002178/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002179/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002180QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002181ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2182 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002183 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002184
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002185 if (Canonical.isNull())
2186 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002187 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002188 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002189 Decl->TypeForDecl = newType;
2190 Types.push_back(newType);
2191 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002192}
2193
Jay Foad4ba2a172011-01-12 09:06:06 +00002194QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002195 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2196
2197 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2198 if (PrevDecl->TypeForDecl)
2199 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2200
John McCallf4c73712011-01-19 06:33:43 +00002201 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2202 Decl->TypeForDecl = newType;
2203 Types.push_back(newType);
2204 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002205}
2206
Jay Foad4ba2a172011-01-12 09:06:06 +00002207QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002208 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2209
2210 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2211 if (PrevDecl->TypeForDecl)
2212 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2213
John McCallf4c73712011-01-19 06:33:43 +00002214 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2215 Decl->TypeForDecl = newType;
2216 Types.push_back(newType);
2217 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002218}
2219
John McCall9d156a72011-01-06 01:58:22 +00002220QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2221 QualType modifiedType,
2222 QualType equivalentType) {
2223 llvm::FoldingSetNodeID id;
2224 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2225
2226 void *insertPos = 0;
2227 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2228 if (type) return QualType(type, 0);
2229
2230 QualType canon = getCanonicalType(equivalentType);
2231 type = new (*this, TypeAlignment)
2232 AttributedType(canon, attrKind, modifiedType, equivalentType);
2233
2234 Types.push_back(type);
2235 AttributedTypes.InsertNode(type, insertPos);
2236
2237 return QualType(type, 0);
2238}
2239
2240
John McCall49a832b2009-10-18 09:09:24 +00002241/// \brief Retrieve a substitution-result type.
2242QualType
2243ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002244 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002245 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002246 && "replacement types must always be canonical");
2247
2248 llvm::FoldingSetNodeID ID;
2249 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2250 void *InsertPos = 0;
2251 SubstTemplateTypeParmType *SubstParm
2252 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2253
2254 if (!SubstParm) {
2255 SubstParm = new (*this, TypeAlignment)
2256 SubstTemplateTypeParmType(Parm, Replacement);
2257 Types.push_back(SubstParm);
2258 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2259 }
2260
2261 return QualType(SubstParm, 0);
2262}
2263
Douglas Gregorc3069d62011-01-14 02:55:32 +00002264/// \brief Retrieve a
2265QualType ASTContext::getSubstTemplateTypeParmPackType(
2266 const TemplateTypeParmType *Parm,
2267 const TemplateArgument &ArgPack) {
2268#ifndef NDEBUG
2269 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2270 PEnd = ArgPack.pack_end();
2271 P != PEnd; ++P) {
2272 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2273 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2274 }
2275#endif
2276
2277 llvm::FoldingSetNodeID ID;
2278 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2279 void *InsertPos = 0;
2280 if (SubstTemplateTypeParmPackType *SubstParm
2281 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2282 return QualType(SubstParm, 0);
2283
2284 QualType Canon;
2285 if (!Parm->isCanonicalUnqualified()) {
2286 Canon = getCanonicalType(QualType(Parm, 0));
2287 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2288 ArgPack);
2289 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2290 }
2291
2292 SubstTemplateTypeParmPackType *SubstParm
2293 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2294 ArgPack);
2295 Types.push_back(SubstParm);
2296 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2297 return QualType(SubstParm, 0);
2298}
2299
Douglas Gregorfab9d672009-02-05 23:33:38 +00002300/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002301/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002302/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002303QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002304 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002305 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002306 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002307 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002308 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002309 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002310 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2311
2312 if (TypeParm)
2313 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002314
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002315 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002316 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002317 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002318
2319 TemplateTypeParmType *TypeCheck
2320 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2321 assert(!TypeCheck && "Template type parameter canonical type broken");
2322 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002323 } else
John McCall6b304a02009-09-24 23:30:46 +00002324 TypeParm = new (*this, TypeAlignment)
2325 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002326
2327 Types.push_back(TypeParm);
2328 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2329
2330 return QualType(TypeParm, 0);
2331}
2332
John McCall3cb0ebd2010-03-10 03:28:59 +00002333TypeSourceInfo *
2334ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2335 SourceLocation NameLoc,
2336 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002337 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002338 assert(!Name.getAsDependentTemplateName() &&
2339 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002340 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002341
2342 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2343 TemplateSpecializationTypeLoc TL
2344 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2345 TL.setTemplateNameLoc(NameLoc);
2346 TL.setLAngleLoc(Args.getLAngleLoc());
2347 TL.setRAngleLoc(Args.getRAngleLoc());
2348 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2349 TL.setArgLocInfo(i, Args[i].getLocInfo());
2350 return DI;
2351}
2352
Mike Stump1eb44332009-09-09 15:08:12 +00002353QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002354ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002355 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002356 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002357 assert(!Template.getAsDependentTemplateName() &&
2358 "No dependent template names here!");
2359
John McCalld5532b62009-11-23 01:53:49 +00002360 unsigned NumArgs = Args.size();
2361
Chris Lattner5f9e2722011-07-23 10:55:15 +00002362 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002363 ArgVec.reserve(NumArgs);
2364 for (unsigned i = 0; i != NumArgs; ++i)
2365 ArgVec.push_back(Args[i].getArgument());
2366
John McCall31f17ec2010-04-27 00:57:59 +00002367 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002368 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002369}
2370
2371QualType
2372ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002373 const TemplateArgument *Args,
2374 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002375 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002376 assert(!Template.getAsDependentTemplateName() &&
2377 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002378 // Look through qualified template names.
2379 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2380 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002381
Richard Smith3e4c6c42011-05-05 21:57:07 +00002382 bool isTypeAlias =
2383 Template.getAsTemplateDecl() &&
2384 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2385
2386 QualType CanonType;
2387 if (!Underlying.isNull())
2388 CanonType = getCanonicalType(Underlying);
2389 else {
2390 assert(!isTypeAlias &&
2391 "Underlying type for template alias must be computed by caller");
2392 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2393 NumArgs);
2394 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002395
Douglas Gregor1275ae02009-07-28 23:00:59 +00002396 // Allocate the (non-canonical) template specialization type, but don't
2397 // try to unique it: these types typically have location information that
2398 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002399 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2400 sizeof(TemplateArgument) * NumArgs +
2401 (isTypeAlias ? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00002402 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002403 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00002404 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00002405 Args, NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002406 CanonType,
2407 isTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00002408
Douglas Gregor55f6b142009-02-09 18:46:07 +00002409 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002410 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002411}
2412
Mike Stump1eb44332009-09-09 15:08:12 +00002413QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002414ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2415 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002416 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002417 assert(!Template.getAsDependentTemplateName() &&
2418 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002419 assert((!Template.getAsTemplateDecl() ||
2420 !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2421 "Underlying type for template alias must be computed by caller");
2422
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002423 // Look through qualified template names.
2424 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2425 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002426
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002427 // Build the canonical template specialization type.
2428 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002429 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002430 CanonArgs.reserve(NumArgs);
2431 for (unsigned I = 0; I != NumArgs; ++I)
2432 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2433
2434 // Determine whether this canonical template specialization type already
2435 // exists.
2436 llvm::FoldingSetNodeID ID;
2437 TemplateSpecializationType::Profile(ID, CanonTemplate,
2438 CanonArgs.data(), NumArgs, *this);
2439
2440 void *InsertPos = 0;
2441 TemplateSpecializationType *Spec
2442 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2443
2444 if (!Spec) {
2445 // Allocate a new canonical template specialization type.
2446 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2447 sizeof(TemplateArgument) * NumArgs),
2448 TypeAlignment);
2449 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2450 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002451 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002452 Types.push_back(Spec);
2453 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2454 }
2455
2456 assert(Spec->isDependentType() &&
2457 "Non-dependent template-id type must have a canonical type");
2458 return QualType(Spec, 0);
2459}
2460
2461QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002462ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2463 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002464 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002465 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002466 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002467
2468 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002469 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002470 if (T)
2471 return QualType(T, 0);
2472
Douglas Gregor789b1f62010-02-04 18:10:26 +00002473 QualType Canon = NamedType;
2474 if (!Canon.isCanonical()) {
2475 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002476 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2477 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002478 (void)CheckT;
2479 }
2480
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002481 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002482 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002483 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002484 return QualType(T, 0);
2485}
2486
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002487QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002488ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002489 llvm::FoldingSetNodeID ID;
2490 ParenType::Profile(ID, InnerType);
2491
2492 void *InsertPos = 0;
2493 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2494 if (T)
2495 return QualType(T, 0);
2496
2497 QualType Canon = InnerType;
2498 if (!Canon.isCanonical()) {
2499 Canon = getCanonicalType(InnerType);
2500 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2501 assert(!CheckT && "Paren canonical type broken");
2502 (void)CheckT;
2503 }
2504
2505 T = new (*this) ParenType(InnerType, Canon);
2506 Types.push_back(T);
2507 ParenTypes.InsertNode(T, InsertPos);
2508 return QualType(T, 0);
2509}
2510
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002511QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2512 NestedNameSpecifier *NNS,
2513 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002514 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002515 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2516
2517 if (Canon.isNull()) {
2518 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002519 ElaboratedTypeKeyword CanonKeyword = Keyword;
2520 if (Keyword == ETK_None)
2521 CanonKeyword = ETK_Typename;
2522
2523 if (CanonNNS != NNS || CanonKeyword != Keyword)
2524 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002525 }
2526
2527 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002528 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002529
2530 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002531 DependentNameType *T
2532 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002533 if (T)
2534 return QualType(T, 0);
2535
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002536 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002537 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002538 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002539 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002540}
2541
Mike Stump1eb44332009-09-09 15:08:12 +00002542QualType
John McCall33500952010-06-11 00:33:02 +00002543ASTContext::getDependentTemplateSpecializationType(
2544 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002545 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002546 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002547 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00002548 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00002549 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00002550 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2551 ArgCopy.push_back(Args[I].getArgument());
2552 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2553 ArgCopy.size(),
2554 ArgCopy.data());
2555}
2556
2557QualType
2558ASTContext::getDependentTemplateSpecializationType(
2559 ElaboratedTypeKeyword Keyword,
2560 NestedNameSpecifier *NNS,
2561 const IdentifierInfo *Name,
2562 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002563 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00002564 assert((!NNS || NNS->isDependent()) &&
2565 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00002566
Douglas Gregor789b1f62010-02-04 18:10:26 +00002567 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002568 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2569 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002570
2571 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002572 DependentTemplateSpecializationType *T
2573 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002574 if (T)
2575 return QualType(T, 0);
2576
John McCall33500952010-06-11 00:33:02 +00002577 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002578
John McCall33500952010-06-11 00:33:02 +00002579 ElaboratedTypeKeyword CanonKeyword = Keyword;
2580 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2581
2582 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002583 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00002584 for (unsigned I = 0; I != NumArgs; ++I) {
2585 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2586 if (!CanonArgs[I].structurallyEquals(Args[I]))
2587 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002588 }
2589
John McCall33500952010-06-11 00:33:02 +00002590 QualType Canon;
2591 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2592 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2593 Name, NumArgs,
2594 CanonArgs.data());
2595
2596 // Find the insert position again.
2597 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2598 }
2599
2600 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2601 sizeof(TemplateArgument) * NumArgs),
2602 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002603 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002604 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002605 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002606 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002607 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002608}
2609
Douglas Gregorcded4f62011-01-14 17:04:44 +00002610QualType ASTContext::getPackExpansionType(QualType Pattern,
2611 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00002612 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002613 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002614
2615 assert(Pattern->containsUnexpandedParameterPack() &&
2616 "Pack expansions must expand one or more parameter packs");
2617 void *InsertPos = 0;
2618 PackExpansionType *T
2619 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2620 if (T)
2621 return QualType(T, 0);
2622
2623 QualType Canon;
2624 if (!Pattern.isCanonical()) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002625 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002626
2627 // Find the insert position again.
2628 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2629 }
2630
Douglas Gregorcded4f62011-01-14 17:04:44 +00002631 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002632 Types.push_back(T);
2633 PackExpansionTypes.InsertNode(T, InsertPos);
2634 return QualType(T, 0);
2635}
2636
Chris Lattner88cb27a2008-04-07 04:56:42 +00002637/// CmpProtocolNames - Comparison predicate for sorting protocols
2638/// alphabetically.
2639static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2640 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002641 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002642}
2643
John McCallc12c5bb2010-05-15 11:32:37 +00002644static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002645 unsigned NumProtocols) {
2646 if (NumProtocols == 0) return true;
2647
2648 for (unsigned i = 1; i != NumProtocols; ++i)
2649 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2650 return false;
2651 return true;
2652}
2653
2654static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002655 unsigned &NumProtocols) {
2656 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002657
Chris Lattner88cb27a2008-04-07 04:56:42 +00002658 // Sort protocols, keyed by name.
2659 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2660
2661 // Remove duplicates.
2662 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2663 NumProtocols = ProtocolsEnd-Protocols;
2664}
2665
John McCallc12c5bb2010-05-15 11:32:37 +00002666QualType ASTContext::getObjCObjectType(QualType BaseType,
2667 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00002668 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002669 // If the base type is an interface and there aren't any protocols
2670 // to add, then the interface type will do just fine.
2671 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2672 return BaseType;
2673
2674 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002675 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002676 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002677 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002678 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2679 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002680
John McCallc12c5bb2010-05-15 11:32:37 +00002681 // Build the canonical type, which has the canonical base type and
2682 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002683 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002684 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2685 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2686 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002687 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00002688 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002689 unsigned UniqueCount = NumProtocols;
2690
John McCall54e14c42009-10-22 22:37:11 +00002691 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002692 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2693 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002694 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002695 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2696 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002697 }
2698
2699 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002700 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2701 }
2702
2703 unsigned Size = sizeof(ObjCObjectTypeImpl);
2704 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2705 void *Mem = Allocate(Size, TypeAlignment);
2706 ObjCObjectTypeImpl *T =
2707 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2708
2709 Types.push_back(T);
2710 ObjCObjectTypes.InsertNode(T, InsertPos);
2711 return QualType(T, 0);
2712}
2713
2714/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2715/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002716QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002717 llvm::FoldingSetNodeID ID;
2718 ObjCObjectPointerType::Profile(ID, ObjectT);
2719
2720 void *InsertPos = 0;
2721 if (ObjCObjectPointerType *QT =
2722 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2723 return QualType(QT, 0);
2724
2725 // Find the canonical object type.
2726 QualType Canonical;
2727 if (!ObjectT.isCanonical()) {
2728 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2729
2730 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002731 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2732 }
2733
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002734 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002735 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2736 ObjCObjectPointerType *QType =
2737 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002738
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002739 Types.push_back(QType);
2740 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002741 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002742}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002743
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002744/// getObjCInterfaceType - Return the unique reference to the type for the
2745/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad4ba2a172011-01-12 09:06:06 +00002746QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002747 if (Decl->TypeForDecl)
2748 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002749
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002750 // FIXME: redeclarations?
2751 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2752 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2753 Decl->TypeForDecl = T;
2754 Types.push_back(T);
2755 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002756}
2757
Douglas Gregor72564e72009-02-26 23:50:07 +00002758/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2759/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002760/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002761/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002762/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002763QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002764 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002765 if (tofExpr->isTypeDependent()) {
2766 llvm::FoldingSetNodeID ID;
2767 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002768
Douglas Gregorb1975722009-07-30 23:18:24 +00002769 void *InsertPos = 0;
2770 DependentTypeOfExprType *Canon
2771 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2772 if (Canon) {
2773 // We already have a "canonical" version of an identical, dependent
2774 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002775 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002776 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00002777 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00002778 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002779 Canon
2780 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002781 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2782 toe = Canon;
2783 }
2784 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002785 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002786 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002787 }
Steve Naroff9752f252007-08-01 18:02:17 +00002788 Types.push_back(toe);
2789 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002790}
2791
Steve Naroff9752f252007-08-01 18:02:17 +00002792/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2793/// TypeOfType AST's. The only motivation to unique these nodes would be
2794/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002795/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002796/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002797QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002798 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002799 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002800 Types.push_back(tot);
2801 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002802}
2803
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002804/// getDecltypeForExpr - Given an expr, will return the decltype for that
2805/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad4ba2a172011-01-12 09:06:06 +00002806static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002807 if (e->isTypeDependent())
2808 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002809
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002810 // If e is an id expression or a class member access, decltype(e) is defined
2811 // as the type of the entity named by e.
2812 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2813 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2814 return VD->getType();
2815 }
2816 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2817 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2818 return FD->getType();
2819 }
2820 // If e is a function call or an invocation of an overloaded operator,
2821 // (parentheses around e are ignored), decltype(e) is defined as the
2822 // return type of that function.
2823 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2824 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002825
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002826 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002827
2828 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002829 // defined as T&, otherwise decltype(e) is defined as T.
John McCall7eb0a9e2010-11-24 05:12:34 +00002830 if (e->isLValue())
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002831 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002832
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002833 return T;
2834}
2835
Anders Carlsson395b4752009-06-24 19:06:50 +00002836/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2837/// DecltypeType AST's. The only motivation to unique these nodes would be
2838/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002839/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002840/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002841QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002842 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00002843
2844 // C++0x [temp.type]p2:
2845 // If an expression e involves a template parameter, decltype(e) denotes a
2846 // unique dependent type. Two such decltype-specifiers refer to the same
2847 // type only if their expressions are equivalent (14.5.6.1).
2848 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002849 llvm::FoldingSetNodeID ID;
2850 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002851
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002852 void *InsertPos = 0;
2853 DependentDecltypeType *Canon
2854 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2855 if (Canon) {
2856 // We already have a "canonical" version of an equivalent, dependent
2857 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002858 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002859 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00002860 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002861 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002862 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002863 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2864 dt = Canon;
2865 }
2866 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002867 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002868 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002869 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002870 Types.push_back(dt);
2871 return QualType(dt, 0);
2872}
2873
Sean Huntca63c202011-05-24 22:41:36 +00002874/// getUnaryTransformationType - We don't unique these, since the memory
2875/// savings are minimal and these are rare.
2876QualType ASTContext::getUnaryTransformType(QualType BaseType,
2877 QualType UnderlyingType,
2878 UnaryTransformType::UTTKind Kind)
2879 const {
2880 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00002881 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2882 Kind,
2883 UnderlyingType->isDependentType() ?
2884 QualType() : UnderlyingType);
Sean Huntca63c202011-05-24 22:41:36 +00002885 Types.push_back(Ty);
2886 return QualType(Ty, 0);
2887}
2888
Richard Smith483b9f32011-02-21 20:05:19 +00002889/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00002890QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00002891 void *InsertPos = 0;
2892 if (!DeducedType.isNull()) {
2893 // Look in the folding set for an existing type.
2894 llvm::FoldingSetNodeID ID;
2895 AutoType::Profile(ID, DeducedType);
2896 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2897 return QualType(AT, 0);
2898 }
2899
2900 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2901 Types.push_back(AT);
2902 if (InsertPos)
2903 AutoTypes.InsertNode(AT, InsertPos);
2904 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00002905}
2906
Richard Smithad762fc2011-04-14 22:09:26 +00002907/// getAutoDeductType - Get type pattern for deducing against 'auto'.
2908QualType ASTContext::getAutoDeductType() const {
2909 if (AutoDeductTy.isNull())
2910 AutoDeductTy = getAutoType(QualType());
2911 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
2912 return AutoDeductTy;
2913}
2914
2915/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
2916QualType ASTContext::getAutoRRefDeductType() const {
2917 if (AutoRRefDeductTy.isNull())
2918 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
2919 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
2920 return AutoRRefDeductTy;
2921}
2922
Reid Spencer5f016e22007-07-11 17:01:13 +00002923/// getTagDeclType - Return the unique reference to the type for the
2924/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00002925QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00002926 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002927 // FIXME: What is the design on getTagDeclType when it requires casting
2928 // away const? mutable?
2929 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002930}
2931
Mike Stump1eb44332009-09-09 15:08:12 +00002932/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2933/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2934/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002935CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002936 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002937}
2938
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002939/// getSignedWCharType - Return the type of "signed wchar_t".
2940/// Used when in C++, as a GCC extension.
2941QualType ASTContext::getSignedWCharType() const {
2942 // FIXME: derive from "Target" ?
2943 return WCharTy;
2944}
2945
2946/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2947/// Used when in C++, as a GCC extension.
2948QualType ASTContext::getUnsignedWCharType() const {
2949 // FIXME: derive from "Target" ?
2950 return UnsignedIntTy;
2951}
2952
Chris Lattner8b9023b2007-07-13 03:05:23 +00002953/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2954/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2955QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002956 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002957}
2958
Chris Lattnere6327742008-04-02 05:18:44 +00002959//===----------------------------------------------------------------------===//
2960// Type Operators
2961//===----------------------------------------------------------------------===//
2962
Jay Foad4ba2a172011-01-12 09:06:06 +00002963CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00002964 // Push qualifiers into arrays, and then discard any remaining
2965 // qualifiers.
2966 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002967 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00002968 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00002969 QualType Result;
2970 if (isa<ArrayType>(Ty)) {
2971 Result = getArrayDecayedType(QualType(Ty,0));
2972 } else if (isa<FunctionType>(Ty)) {
2973 Result = getPointerType(QualType(Ty, 0));
2974 } else {
2975 Result = QualType(Ty, 0);
2976 }
2977
2978 return CanQualType::CreateUnsafe(Result);
2979}
2980
John McCall62c28c82011-01-18 07:41:22 +00002981QualType ASTContext::getUnqualifiedArrayType(QualType type,
2982 Qualifiers &quals) {
2983 SplitQualType splitType = type.getSplitUnqualifiedType();
2984
2985 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2986 // the unqualified desugared type and then drops it on the floor.
2987 // We then have to strip that sugar back off with
2988 // getUnqualifiedDesugaredType(), which is silly.
2989 const ArrayType *AT =
2990 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2991
2992 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00002993 if (!AT) {
John McCall62c28c82011-01-18 07:41:22 +00002994 quals = splitType.second;
2995 return QualType(splitType.first, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002996 }
2997
John McCall62c28c82011-01-18 07:41:22 +00002998 // Otherwise, recurse on the array's element type.
2999 QualType elementType = AT->getElementType();
3000 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3001
3002 // If that didn't change the element type, AT has no qualifiers, so we
3003 // can just use the results in splitType.
3004 if (elementType == unqualElementType) {
3005 assert(quals.empty()); // from the recursive call
3006 quals = splitType.second;
3007 return QualType(splitType.first, 0);
3008 }
3009
3010 // Otherwise, add in the qualifiers from the outermost type, then
3011 // build the type back up.
3012 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003013
Douglas Gregor9dadd942010-05-17 18:45:21 +00003014 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003015 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003016 CAT->getSizeModifier(), 0);
3017 }
3018
Douglas Gregor9dadd942010-05-17 18:45:21 +00003019 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003020 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003021 }
3022
Douglas Gregor9dadd942010-05-17 18:45:21 +00003023 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003024 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003025 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003026 VAT->getSizeModifier(),
3027 VAT->getIndexTypeCVRQualifiers(),
3028 VAT->getBracketsRange());
3029 }
3030
3031 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003032 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003033 DSAT->getSizeModifier(), 0,
3034 SourceRange());
3035}
3036
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003037/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3038/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3039/// they point to and return true. If T1 and T2 aren't pointer types
3040/// or pointer-to-member types, or if they are not similar at this
3041/// level, returns false and leaves T1 and T2 unchanged. Top-level
3042/// qualifiers on T1 and T2 are ignored. This function will typically
3043/// be called in a loop that successively "unwraps" pointer and
3044/// pointer-to-member types to compare them at each level.
3045bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3046 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3047 *T2PtrType = T2->getAs<PointerType>();
3048 if (T1PtrType && T2PtrType) {
3049 T1 = T1PtrType->getPointeeType();
3050 T2 = T2PtrType->getPointeeType();
3051 return true;
3052 }
3053
3054 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3055 *T2MPType = T2->getAs<MemberPointerType>();
3056 if (T1MPType && T2MPType &&
3057 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3058 QualType(T2MPType->getClass(), 0))) {
3059 T1 = T1MPType->getPointeeType();
3060 T2 = T2MPType->getPointeeType();
3061 return true;
3062 }
3063
3064 if (getLangOptions().ObjC1) {
3065 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3066 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3067 if (T1OPType && T2OPType) {
3068 T1 = T1OPType->getPointeeType();
3069 T2 = T2OPType->getPointeeType();
3070 return true;
3071 }
3072 }
3073
3074 // FIXME: Block pointers, too?
3075
3076 return false;
3077}
3078
Jay Foad4ba2a172011-01-12 09:06:06 +00003079DeclarationNameInfo
3080ASTContext::getNameForTemplate(TemplateName Name,
3081 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003082 switch (Name.getKind()) {
3083 case TemplateName::QualifiedTemplate:
3084 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003085 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003086 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3087 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003088
John McCall14606042011-06-30 08:33:18 +00003089 case TemplateName::OverloadedTemplate: {
3090 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3091 // DNInfo work in progress: CHECKME: what about DNLoc?
3092 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3093 }
3094
3095 case TemplateName::DependentTemplate: {
3096 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003097 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003098 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003099 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3100 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003101 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003102 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3103 // DNInfo work in progress: FIXME: source locations?
3104 DeclarationNameLoc DNLoc;
3105 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3106 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3107 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003108 }
3109 }
3110
John McCall14606042011-06-30 08:33:18 +00003111 case TemplateName::SubstTemplateTemplateParm: {
3112 SubstTemplateTemplateParmStorage *subst
3113 = Name.getAsSubstTemplateTemplateParm();
3114 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3115 NameLoc);
3116 }
3117
3118 case TemplateName::SubstTemplateTemplateParmPack: {
3119 SubstTemplateTemplateParmPackStorage *subst
3120 = Name.getAsSubstTemplateTemplateParmPack();
3121 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3122 NameLoc);
3123 }
3124 }
3125
3126 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003127}
3128
Jay Foad4ba2a172011-01-12 09:06:06 +00003129TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003130 switch (Name.getKind()) {
3131 case TemplateName::QualifiedTemplate:
3132 case TemplateName::Template: {
3133 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003134 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003135 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003136 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3137
3138 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003139 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003140 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003141
John McCall14606042011-06-30 08:33:18 +00003142 case TemplateName::OverloadedTemplate:
3143 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003144
John McCall14606042011-06-30 08:33:18 +00003145 case TemplateName::DependentTemplate: {
3146 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3147 assert(DTN && "Non-dependent template names must refer to template decls.");
3148 return DTN->CanonicalTemplateName;
3149 }
3150
3151 case TemplateName::SubstTemplateTemplateParm: {
3152 SubstTemplateTemplateParmStorage *subst
3153 = Name.getAsSubstTemplateTemplateParm();
3154 return getCanonicalTemplateName(subst->getReplacement());
3155 }
3156
3157 case TemplateName::SubstTemplateTemplateParmPack: {
3158 SubstTemplateTemplateParmPackStorage *subst
3159 = Name.getAsSubstTemplateTemplateParmPack();
3160 TemplateTemplateParmDecl *canonParameter
3161 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3162 TemplateArgument canonArgPack
3163 = getCanonicalTemplateArgument(subst->getArgumentPack());
3164 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3165 }
3166 }
3167
3168 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003169}
3170
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003171bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3172 X = getCanonicalTemplateName(X);
3173 Y = getCanonicalTemplateName(Y);
3174 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3175}
3176
Mike Stump1eb44332009-09-09 15:08:12 +00003177TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003178ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003179 switch (Arg.getKind()) {
3180 case TemplateArgument::Null:
3181 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003182
Douglas Gregor1275ae02009-07-28 23:00:59 +00003183 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003184 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003185
Douglas Gregor1275ae02009-07-28 23:00:59 +00003186 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00003187 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003188
Douglas Gregor788cd062009-11-11 01:00:40 +00003189 case TemplateArgument::Template:
3190 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003191
3192 case TemplateArgument::TemplateExpansion:
3193 return TemplateArgument(getCanonicalTemplateName(
3194 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003195 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003196
Douglas Gregor1275ae02009-07-28 23:00:59 +00003197 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00003198 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003199 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003200
Douglas Gregor1275ae02009-07-28 23:00:59 +00003201 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003202 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003203
Douglas Gregor1275ae02009-07-28 23:00:59 +00003204 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003205 if (Arg.pack_size() == 0)
3206 return Arg;
3207
Douglas Gregor910f8002010-11-07 23:05:16 +00003208 TemplateArgument *CanonArgs
3209 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003210 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003211 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003212 AEnd = Arg.pack_end();
3213 A != AEnd; (void)++A, ++Idx)
3214 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003215
Douglas Gregor910f8002010-11-07 23:05:16 +00003216 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003217 }
3218 }
3219
3220 // Silence GCC warning
3221 assert(false && "Unhandled template argument kind");
3222 return TemplateArgument();
3223}
3224
Douglas Gregord57959a2009-03-27 23:10:48 +00003225NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003226ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003227 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003228 return 0;
3229
3230 switch (NNS->getKind()) {
3231 case NestedNameSpecifier::Identifier:
3232 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003233 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003234 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3235 NNS->getAsIdentifier());
3236
3237 case NestedNameSpecifier::Namespace:
3238 // A namespace is canonical; build a nested-name-specifier with
3239 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003240 return NestedNameSpecifier::Create(*this, 0,
3241 NNS->getAsNamespace()->getOriginalNamespace());
3242
3243 case NestedNameSpecifier::NamespaceAlias:
3244 // A namespace is canonical; build a nested-name-specifier with
3245 // this namespace and no prefix.
3246 return NestedNameSpecifier::Create(*this, 0,
3247 NNS->getAsNamespaceAlias()->getNamespace()
3248 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003249
3250 case NestedNameSpecifier::TypeSpec:
3251 case NestedNameSpecifier::TypeSpecWithTemplate: {
3252 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003253
3254 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3255 // break it apart into its prefix and identifier, then reconsititute those
3256 // as the canonical nested-name-specifier. This is required to canonicalize
3257 // a dependent nested-name-specifier involving typedefs of dependent-name
3258 // types, e.g.,
3259 // typedef typename T::type T1;
3260 // typedef typename T1::type T2;
3261 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3262 NestedNameSpecifier *Prefix
3263 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3264 return NestedNameSpecifier::Create(*this, Prefix,
3265 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3266 }
3267
Douglas Gregor643f8432010-11-04 00:14:23 +00003268 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor264bf662010-11-04 00:09:33 +00003269 if (const DependentTemplateSpecializationType *DTST
3270 = T->getAs<DependentTemplateSpecializationType>()) {
3271 NestedNameSpecifier *Prefix
3272 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003273
3274 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3275 Prefix, DTST->getIdentifier(),
3276 DTST->getNumArgs(),
3277 DTST->getArgs());
Douglas Gregor264bf662010-11-04 00:09:33 +00003278 T = getCanonicalType(T);
3279 }
3280
John McCall3b657512011-01-19 10:06:00 +00003281 return NestedNameSpecifier::Create(*this, 0, false,
3282 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003283 }
3284
3285 case NestedNameSpecifier::Global:
3286 // The global specifier is canonical and unique.
3287 return NNS;
3288 }
3289
3290 // Required to silence a GCC warning
3291 return 0;
3292}
3293
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003294
Jay Foad4ba2a172011-01-12 09:06:06 +00003295const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003296 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003297 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003298 // Handle the common positive case fast.
3299 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3300 return AT;
3301 }
Mike Stump1eb44332009-09-09 15:08:12 +00003302
John McCall0953e762009-09-24 19:53:00 +00003303 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003304 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003305 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003306
John McCall0953e762009-09-24 19:53:00 +00003307 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003308 // implements C99 6.7.3p8: "If the specification of an array type includes
3309 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003310
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003311 // If we get here, we either have type qualifiers on the type, or we have
3312 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003313 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003314
John McCall3b657512011-01-19 10:06:00 +00003315 SplitQualType split = T.getSplitDesugaredType();
3316 Qualifiers qs = split.second;
Mike Stump1eb44332009-09-09 15:08:12 +00003317
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003318 // If we have a simple case, just return now.
John McCall3b657512011-01-19 10:06:00 +00003319 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3320 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003321 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003322
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003323 // Otherwise, we have an array and we have qualifiers on it. Push the
3324 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003325 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003326
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003327 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3328 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3329 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003330 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003331 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3332 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3333 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003334 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003335
Mike Stump1eb44332009-09-09 15:08:12 +00003336 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003337 = dyn_cast<DependentSizedArrayType>(ATy))
3338 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003339 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003340 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003341 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003342 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003343 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003344
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003345 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003346 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003347 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003348 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003349 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003350 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003351}
3352
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003353QualType ASTContext::getAdjustedParameterType(QualType T) {
3354 // C99 6.7.5.3p7:
3355 // A declaration of a parameter as "array of type" shall be
3356 // adjusted to "qualified pointer to type", where the type
3357 // qualifiers (if any) are those specified within the [ and ] of
3358 // the array type derivation.
3359 if (T->isArrayType())
3360 return getArrayDecayedType(T);
3361
3362 // C99 6.7.5.3p8:
3363 // A declaration of a parameter as "function returning type"
3364 // shall be adjusted to "pointer to function returning type", as
3365 // in 6.3.2.1.
3366 if (T->isFunctionType())
3367 return getPointerType(T);
3368
3369 return T;
3370}
3371
3372QualType ASTContext::getSignatureParameterType(QualType T) {
3373 T = getVariableArrayDecayedType(T);
3374 T = getAdjustedParameterType(T);
3375 return T.getUnqualifiedType();
3376}
3377
Chris Lattnere6327742008-04-02 05:18:44 +00003378/// getArrayDecayedType - Return the properly qualified result of decaying the
3379/// specified array type to a pointer. This operation is non-trivial when
3380/// handling typedefs etc. The canonical type of "T" must be an array type,
3381/// this returns a pointer to a properly qualified element of the array.
3382///
3383/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003384QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003385 // Get the element type with 'getAsArrayType' so that we don't lose any
3386 // typedefs in the element type of the array. This also handles propagation
3387 // of type qualifiers from the array type into the element type if present
3388 // (C99 6.7.3p8).
3389 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3390 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003391
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003392 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003393
3394 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003395 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003396}
3397
John McCall3b657512011-01-19 10:06:00 +00003398QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3399 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003400}
3401
John McCall3b657512011-01-19 10:06:00 +00003402QualType ASTContext::getBaseElementType(QualType type) const {
3403 Qualifiers qs;
3404 while (true) {
3405 SplitQualType split = type.getSplitDesugaredType();
3406 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3407 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003408
John McCall3b657512011-01-19 10:06:00 +00003409 type = array->getElementType();
3410 qs.addConsistentQualifiers(split.second);
3411 }
Mike Stump1eb44332009-09-09 15:08:12 +00003412
John McCall3b657512011-01-19 10:06:00 +00003413 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003414}
3415
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003416/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003417uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003418ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3419 uint64_t ElementCount = 1;
3420 do {
3421 ElementCount *= CA->getSize().getZExtValue();
3422 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3423 } while (CA);
3424 return ElementCount;
3425}
3426
Reid Spencer5f016e22007-07-11 17:01:13 +00003427/// getFloatingRank - Return a relative rank for floating point types.
3428/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003429static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003430 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003431 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003432
John McCall183700f2009-09-21 23:43:11 +00003433 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3434 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00003435 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00003436 case BuiltinType::Float: return FloatRank;
3437 case BuiltinType::Double: return DoubleRank;
3438 case BuiltinType::LongDouble: return LongDoubleRank;
3439 }
3440}
3441
Mike Stump1eb44332009-09-09 15:08:12 +00003442/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3443/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003444/// 'typeDomain' is a real floating point or complex type.
3445/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003446QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3447 QualType Domain) const {
3448 FloatingRank EltRank = getFloatingRank(Size);
3449 if (Domain->isComplexType()) {
3450 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00003451 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00003452 case FloatRank: return FloatComplexTy;
3453 case DoubleRank: return DoubleComplexTy;
3454 case LongDoubleRank: return LongDoubleComplexTy;
3455 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003456 }
Chris Lattner1361b112008-04-06 23:58:54 +00003457
3458 assert(Domain->isRealFloatingType() && "Unknown domain!");
3459 switch (EltRank) {
3460 default: assert(0 && "getFloatingRank(): illegal value for rank");
3461 case FloatRank: return FloatTy;
3462 case DoubleRank: return DoubleTy;
3463 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003464 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003465}
3466
Chris Lattner7cfeb082008-04-06 23:55:33 +00003467/// getFloatingTypeOrder - Compare the rank of the two specified floating
3468/// point types, ignoring the domain of the type (i.e. 'double' ==
3469/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003470/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003471int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003472 FloatingRank LHSR = getFloatingRank(LHS);
3473 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003474
Chris Lattnera75cea32008-04-06 23:38:49 +00003475 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003476 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003477 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003478 return 1;
3479 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003480}
3481
Chris Lattnerf52ab252008-04-06 22:59:24 +00003482/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3483/// routine will assert if passed a built-in type that isn't an integer or enum,
3484/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003485unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003486 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCallf4c73712011-01-19 06:33:43 +00003487 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00003488 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00003489
Chris Lattner3f59c972010-12-25 23:25:43 +00003490 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3491 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003492 T = getFromTargetType(Target->getWCharType()).getTypePtr();
Eli Friedmana3426752009-07-05 23:44:27 +00003493
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003494 if (T->isSpecificBuiltinType(BuiltinType::Char16))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003495 T = getFromTargetType(Target->getChar16Type()).getTypePtr();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003496
3497 if (T->isSpecificBuiltinType(BuiltinType::Char32))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003498 T = getFromTargetType(Target->getChar32Type()).getTypePtr();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003499
Chris Lattnerf52ab252008-04-06 22:59:24 +00003500 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00003501 default: assert(0 && "getIntegerRank(): not a built-in integer");
3502 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003503 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003504 case BuiltinType::Char_S:
3505 case BuiltinType::Char_U:
3506 case BuiltinType::SChar:
3507 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003508 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003509 case BuiltinType::Short:
3510 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003511 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003512 case BuiltinType::Int:
3513 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003514 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003515 case BuiltinType::Long:
3516 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003517 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003518 case BuiltinType::LongLong:
3519 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003520 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003521 case BuiltinType::Int128:
3522 case BuiltinType::UInt128:
3523 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003524 }
3525}
3526
Eli Friedman04e83572009-08-20 04:21:42 +00003527/// \brief Whether this is a promotable bitfield reference according
3528/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3529///
3530/// \returns the type this bit-field will promote to, or NULL if no
3531/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00003532QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003533 if (E->isTypeDependent() || E->isValueDependent())
3534 return QualType();
3535
Eli Friedman04e83572009-08-20 04:21:42 +00003536 FieldDecl *Field = E->getBitField();
3537 if (!Field)
3538 return QualType();
3539
3540 QualType FT = Field->getType();
3541
3542 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3543 uint64_t BitWidth = BitWidthAP.getZExtValue();
3544 uint64_t IntSize = getTypeSize(IntTy);
3545 // GCC extension compatibility: if the bit-field size is less than or equal
3546 // to the size of int, it gets promoted no matter what its type is.
3547 // For instance, unsigned long bf : 4 gets promoted to signed int.
3548 if (BitWidth < IntSize)
3549 return IntTy;
3550
3551 if (BitWidth == IntSize)
3552 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3553
3554 // Types bigger than int are not subject to promotions, and therefore act
3555 // like the base type.
3556 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3557 // is ridiculous.
3558 return QualType();
3559}
3560
Eli Friedmana95d7572009-08-19 07:44:53 +00003561/// getPromotedIntegerType - Returns the type that Promotable will
3562/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3563/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003564QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003565 assert(!Promotable.isNull());
3566 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003567 if (const EnumType *ET = Promotable->getAs<EnumType>())
3568 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00003569 if (Promotable->isSignedIntegerType())
3570 return IntTy;
3571 uint64_t PromotableSize = getTypeSize(Promotable);
3572 uint64_t IntSize = getTypeSize(IntTy);
3573 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3574 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3575}
3576
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003577/// \brief Recurses in pointer/array types until it finds an objc retainable
3578/// type and returns its ownership.
3579Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3580 while (!T.isNull()) {
3581 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3582 return T.getObjCLifetime();
3583 if (T->isArrayType())
3584 T = getBaseElementType(T);
3585 else if (const PointerType *PT = T->getAs<PointerType>())
3586 T = PT->getPointeeType();
3587 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00003588 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003589 else
3590 break;
3591 }
3592
3593 return Qualifiers::OCL_None;
3594}
3595
Mike Stump1eb44332009-09-09 15:08:12 +00003596/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003597/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003598/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003599int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00003600 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3601 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003602 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003603
Chris Lattnerf52ab252008-04-06 22:59:24 +00003604 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3605 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003606
Chris Lattner7cfeb082008-04-06 23:55:33 +00003607 unsigned LHSRank = getIntegerRank(LHSC);
3608 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003609
Chris Lattner7cfeb082008-04-06 23:55:33 +00003610 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3611 if (LHSRank == RHSRank) return 0;
3612 return LHSRank > RHSRank ? 1 : -1;
3613 }
Mike Stump1eb44332009-09-09 15:08:12 +00003614
Chris Lattner7cfeb082008-04-06 23:55:33 +00003615 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3616 if (LHSUnsigned) {
3617 // If the unsigned [LHS] type is larger, return it.
3618 if (LHSRank >= RHSRank)
3619 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003620
Chris Lattner7cfeb082008-04-06 23:55:33 +00003621 // If the signed type can represent all values of the unsigned type, it
3622 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003623 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003624 return -1;
3625 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003626
Chris Lattner7cfeb082008-04-06 23:55:33 +00003627 // If the unsigned [RHS] type is larger, return it.
3628 if (RHSRank >= LHSRank)
3629 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003630
Chris Lattner7cfeb082008-04-06 23:55:33 +00003631 // If the signed type can represent all values of the unsigned type, it
3632 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003633 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003634 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003635}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003636
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003637static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003638CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3639 DeclContext *DC, IdentifierInfo *Id) {
3640 SourceLocation Loc;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003641 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003642 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003643 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003644 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003645}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003646
Mike Stump1eb44332009-09-09 15:08:12 +00003647// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003648QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003649 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003650 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003651 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003652 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003653 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003654
Anders Carlssonf06273f2007-11-19 00:25:30 +00003655 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003656
Anders Carlsson71993dd2007-08-17 05:31:46 +00003657 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003658 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003659 // int flags;
3660 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003661 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003662 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003663 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003664 FieldTypes[3] = LongTy;
3665
Anders Carlsson71993dd2007-08-17 05:31:46 +00003666 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003667 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003668 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003669 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00003670 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003671 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003672 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003673 /*Mutable=*/false,
3674 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003675 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003676 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003677 }
3678
Douglas Gregor838db382010-02-11 01:19:42 +00003679 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003680 }
Mike Stump1eb44332009-09-09 15:08:12 +00003681
Anders Carlsson71993dd2007-08-17 05:31:46 +00003682 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003683}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003684
Douglas Gregor319ac892009-04-23 22:29:11 +00003685void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003686 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003687 assert(Rec && "Invalid CFConstantStringType");
3688 CFConstantStringTypeDecl = Rec->getDecl();
3689}
3690
Jay Foad4ba2a172011-01-12 09:06:06 +00003691QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00003692 if (BlockDescriptorType)
3693 return getTagDeclType(BlockDescriptorType);
3694
3695 RecordDecl *T;
3696 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003697 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003698 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003699 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003700
3701 QualType FieldTypes[] = {
3702 UnsignedLongTy,
3703 UnsignedLongTy,
3704 };
3705
3706 const char *FieldNames[] = {
3707 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003708 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003709 };
3710
3711 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003712 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003713 SourceLocation(),
3714 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003715 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003716 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003717 /*Mutable=*/false,
3718 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003719 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003720 T->addDecl(Field);
3721 }
3722
Douglas Gregor838db382010-02-11 01:19:42 +00003723 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003724
3725 BlockDescriptorType = T;
3726
3727 return getTagDeclType(BlockDescriptorType);
3728}
3729
Jay Foad4ba2a172011-01-12 09:06:06 +00003730QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00003731 if (BlockDescriptorExtendedType)
3732 return getTagDeclType(BlockDescriptorExtendedType);
3733
3734 RecordDecl *T;
3735 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003736 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003737 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003738 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003739
3740 QualType FieldTypes[] = {
3741 UnsignedLongTy,
3742 UnsignedLongTy,
3743 getPointerType(VoidPtrTy),
3744 getPointerType(VoidPtrTy)
3745 };
3746
3747 const char *FieldNames[] = {
3748 "reserved",
3749 "Size",
3750 "CopyFuncPtr",
3751 "DestroyFuncPtr"
3752 };
3753
3754 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003755 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00003756 SourceLocation(),
3757 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003758 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003759 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003760 /*Mutable=*/false,
3761 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003762 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003763 T->addDecl(Field);
3764 }
3765
Douglas Gregor838db382010-02-11 01:19:42 +00003766 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003767
3768 BlockDescriptorExtendedType = T;
3769
3770 return getTagDeclType(BlockDescriptorExtendedType);
3771}
3772
Jay Foad4ba2a172011-01-12 09:06:06 +00003773bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCallf85e1932011-06-15 23:02:42 +00003774 if (Ty->isObjCRetainableType())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003775 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003776 if (getLangOptions().CPlusPlus) {
3777 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3778 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Huntffe37fd2011-05-25 20:50:04 +00003779 return RD->hasConstCopyConstructor();
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003780
3781 }
3782 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003783 return false;
3784}
3785
Jay Foad4ba2a172011-01-12 09:06:06 +00003786QualType
Chris Lattner5f9e2722011-07-23 10:55:15 +00003787ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003788 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003789 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003790 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003791 // unsigned int __flags;
3792 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003793 // void *__copy_helper; // as needed
3794 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003795 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003796 // } *
3797
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003798 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3799
3800 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003801 llvm::SmallString<36> Name;
3802 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3803 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003804 RecordDecl *T;
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003805 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003806 T->startDefinition();
3807 QualType Int32Ty = IntTy;
3808 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3809 QualType FieldTypes[] = {
3810 getPointerType(VoidPtrTy),
3811 getPointerType(getTagDeclType(T)),
3812 Int32Ty,
3813 Int32Ty,
3814 getPointerType(VoidPtrTy),
3815 getPointerType(VoidPtrTy),
3816 Ty
3817 };
3818
Chris Lattner5f9e2722011-07-23 10:55:15 +00003819 StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003820 "__isa",
3821 "__forwarding",
3822 "__flags",
3823 "__size",
3824 "__copy_helper",
3825 "__destroy_helper",
3826 DeclName,
3827 };
3828
3829 for (size_t i = 0; i < 7; ++i) {
3830 if (!HasCopyAndDispose && i >=4 && i <= 5)
3831 continue;
3832 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003833 SourceLocation(),
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003834 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003835 FieldTypes[i], /*TInfo=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003836 /*BitWidth=*/0, /*Mutable=*/false,
3837 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003838 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003839 T->addDecl(Field);
3840 }
3841
Douglas Gregor838db382010-02-11 01:19:42 +00003842 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003843
3844 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003845}
3846
Anders Carlssone8c49532007-10-29 06:33:42 +00003847// This returns true if a type has been typedefed to BOOL:
3848// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003849static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003850 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003851 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3852 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003853
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003854 return false;
3855}
3856
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003857/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003858/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00003859CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00003860 if (!type->isIncompleteArrayType() && type->isIncompleteType())
3861 return CharUnits::Zero();
3862
Ken Dyck199c3d62010-01-11 17:06:35 +00003863 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003864
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003865 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003866 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003867 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003868 // Treat arrays as pointers, since that's how they're passed in.
3869 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003870 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003871 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003872}
3873
3874static inline
3875std::string charUnitsToString(const CharUnits &CU) {
3876 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003877}
3878
John McCall6b5a61b2011-02-07 10:33:21 +00003879/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003880/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00003881std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3882 std::string S;
3883
David Chisnall5e530af2009-11-17 19:33:30 +00003884 const BlockDecl *Decl = Expr->getBlockDecl();
3885 QualType BlockTy =
3886 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3887 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003888 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003889 // Compute size of all parameters.
3890 // Start with computing size of a pointer in number of bytes.
3891 // FIXME: There might(should) be a better way of doing this computation!
3892 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003893 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3894 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003895 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003896 E = Decl->param_end(); PI != E; ++PI) {
3897 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003898 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003899 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003900 ParmOffset += sz;
3901 }
3902 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003903 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003904 // Block pointer and offset.
3905 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00003906
3907 // Argument types.
3908 ParmOffset = PtrSize;
3909 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3910 Decl->param_end(); PI != E; ++PI) {
3911 ParmVarDecl *PVDecl = *PI;
3912 QualType PType = PVDecl->getOriginalType();
3913 if (const ArrayType *AT =
3914 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3915 // Use array's original type only if it has known number of
3916 // elements.
3917 if (!isa<ConstantArrayType>(AT))
3918 PType = PVDecl->getType();
3919 } else if (PType->isFunctionType())
3920 PType = PVDecl->getType();
3921 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003922 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003923 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003924 }
John McCall6b5a61b2011-02-07 10:33:21 +00003925
3926 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00003927}
3928
Douglas Gregorf968d832011-05-27 01:19:52 +00003929bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00003930 std::string& S) {
3931 // Encode result type.
3932 getObjCEncodingForType(Decl->getResultType(), S);
3933 CharUnits ParmOffset;
3934 // Compute size of all parameters.
3935 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3936 E = Decl->param_end(); PI != E; ++PI) {
3937 QualType PType = (*PI)->getType();
3938 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00003939 if (sz.isZero())
3940 return true;
3941
David Chisnall5389f482010-12-30 14:05:53 +00003942 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00003943 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00003944 ParmOffset += sz;
3945 }
3946 S += charUnitsToString(ParmOffset);
3947 ParmOffset = CharUnits::Zero();
3948
3949 // Argument types.
3950 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3951 E = Decl->param_end(); PI != E; ++PI) {
3952 ParmVarDecl *PVDecl = *PI;
3953 QualType PType = PVDecl->getOriginalType();
3954 if (const ArrayType *AT =
3955 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3956 // Use array's original type only if it has known number of
3957 // elements.
3958 if (!isa<ConstantArrayType>(AT))
3959 PType = PVDecl->getType();
3960 } else if (PType->isFunctionType())
3961 PType = PVDecl->getType();
3962 getObjCEncodingForType(PType, S);
3963 S += charUnitsToString(ParmOffset);
3964 ParmOffset += getObjCEncodingTypeSize(PType);
3965 }
Douglas Gregorf968d832011-05-27 01:19:52 +00003966
3967 return false;
David Chisnall5389f482010-12-30 14:05:53 +00003968}
3969
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003970/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003971/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00003972bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00003973 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003974 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003975 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003976 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003977 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003978 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003979 // Compute size of all parameters.
3980 // Start with computing size of a pointer in number of bytes.
3981 // FIXME: There might(should) be a better way of doing this computation!
3982 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003983 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003984 // The first two arguments (self and _cmd) are pointers; account for
3985 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003986 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003987 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003988 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003989 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003990 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00003991 if (sz.isZero())
3992 return true;
3993
Ken Dyck199c3d62010-01-11 17:06:35 +00003994 assert (sz.isPositive() &&
3995 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003996 ParmOffset += sz;
3997 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003998 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003999 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004000 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004001
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004002 // Argument types.
4003 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00004004 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004005 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004006 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004007 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004008 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004009 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4010 // Use array's original type only if it has known number of
4011 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004012 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004013 PType = PVDecl->getType();
4014 } else if (PType->isFunctionType())
4015 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004016 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004017 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004018 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004019 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004020 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004021 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004022 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004023
4024 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004025}
4026
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004027/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004028/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004029/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4030/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004031/// Property attributes are stored as a comma-delimited C string. The simple
4032/// attributes readonly and bycopy are encoded as single characters. The
4033/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4034/// encoded as single characters, followed by an identifier. Property types
4035/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004036/// these attributes are defined by the following enumeration:
4037/// @code
4038/// enum PropertyAttributes {
4039/// kPropertyReadOnly = 'R', // property is read-only.
4040/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4041/// kPropertyByref = '&', // property is a reference to the value last assigned
4042/// kPropertyDynamic = 'D', // property is dynamic
4043/// kPropertyGetter = 'G', // followed by getter selector name
4044/// kPropertySetter = 'S', // followed by setter selector name
4045/// kPropertyInstanceVariable = 'V' // followed by instance variable name
4046/// kPropertyType = 't' // followed by old-style type encoding.
4047/// kPropertyWeak = 'W' // 'weak' property
4048/// kPropertyStrong = 'P' // property GC'able
4049/// kPropertyNonAtomic = 'N' // property non-atomic
4050/// };
4051/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004052void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004053 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004054 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004055 // Collect information from the property implementation decl(s).
4056 bool Dynamic = false;
4057 ObjCPropertyImplDecl *SynthesizePID = 0;
4058
4059 // FIXME: Duplicated code due to poor abstraction.
4060 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004061 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004062 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4063 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004064 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004065 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004066 ObjCPropertyImplDecl *PID = *i;
4067 if (PID->getPropertyDecl() == PD) {
4068 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4069 Dynamic = true;
4070 } else {
4071 SynthesizePID = PID;
4072 }
4073 }
4074 }
4075 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004076 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004077 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004078 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004079 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004080 ObjCPropertyImplDecl *PID = *i;
4081 if (PID->getPropertyDecl() == PD) {
4082 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4083 Dynamic = true;
4084 } else {
4085 SynthesizePID = PID;
4086 }
4087 }
Mike Stump1eb44332009-09-09 15:08:12 +00004088 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004089 }
4090 }
4091
4092 // FIXME: This is not very efficient.
4093 S = "T";
4094
4095 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004096 // GCC has some special rules regarding encoding of properties which
4097 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004098 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004099 true /* outermost type */,
4100 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004101
4102 if (PD->isReadOnly()) {
4103 S += ",R";
4104 } else {
4105 switch (PD->getSetterKind()) {
4106 case ObjCPropertyDecl::Assign: break;
4107 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004108 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004109 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004110 }
4111 }
4112
4113 // It really isn't clear at all what this means, since properties
4114 // are "dynamic by default".
4115 if (Dynamic)
4116 S += ",D";
4117
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004118 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4119 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004120
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004121 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4122 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004123 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004124 }
4125
4126 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4127 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004128 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004129 }
4130
4131 if (SynthesizePID) {
4132 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4133 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004134 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004135 }
4136
4137 // FIXME: OBJCGC: weak & strong
4138}
4139
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004140/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004141/// Another legacy compatibility encoding: 32-bit longs are encoded as
4142/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004143/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4144///
4145void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004146 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004147 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004148 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004149 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004150 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004151 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004152 PointeeTy = IntTy;
4153 }
4154 }
4155}
4156
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004157void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004158 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004159 // We follow the behavior of gcc, expanding structures which are
4160 // directly pointed to, and expanding embedded structures. Note that
4161 // these rules are sufficient to prevent recursive encoding of the
4162 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004163 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004164 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004165}
4166
David Chisnall64fd7e82010-06-04 01:10:52 +00004167static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4168 switch (T->getAs<BuiltinType>()->getKind()) {
4169 default: assert(0 && "Unhandled builtin type kind");
4170 case BuiltinType::Void: return 'v';
4171 case BuiltinType::Bool: return 'B';
4172 case BuiltinType::Char_U:
4173 case BuiltinType::UChar: return 'C';
4174 case BuiltinType::UShort: return 'S';
4175 case BuiltinType::UInt: return 'I';
4176 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00004177 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004178 case BuiltinType::UInt128: return 'T';
4179 case BuiltinType::ULongLong: return 'Q';
4180 case BuiltinType::Char_S:
4181 case BuiltinType::SChar: return 'c';
4182 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004183 case BuiltinType::WChar_S:
4184 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004185 case BuiltinType::Int: return 'i';
4186 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00004187 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004188 case BuiltinType::LongLong: return 'q';
4189 case BuiltinType::Int128: return 't';
4190 case BuiltinType::Float: return 'f';
4191 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004192 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004193 }
4194}
4195
Jay Foad4ba2a172011-01-12 09:06:06 +00004196static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004197 QualType T, const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004198 const Expr *E = FD->getBitWidth();
4199 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004200 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004201 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4202 // The GNU runtime requires more information; bitfields are encoded as b,
4203 // then the offset (in bits) of the first element, then the type of the
4204 // bitfield, then the size in bits. For example, in this structure:
4205 //
4206 // struct
4207 // {
4208 // int integer;
4209 // int flags:2;
4210 // };
4211 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4212 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4213 // information is not especially sensible, but we're stuck with it for
4214 // compatibility with GCC, although providing it breaks anything that
4215 // actually uses runtime introspection and wants to work on both runtimes...
4216 if (!Ctx->getLangOptions().NeXTRuntime) {
4217 const RecordDecl *RD = FD->getParent();
4218 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004219 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
David Chisnallc7ff82c2010-12-26 20:12:30 +00004220 if (T->isEnumeralType())
4221 S += 'i';
4222 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004223 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004224 }
4225 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004226 S += llvm::utostr(N);
4227}
4228
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004229// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004230void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4231 bool ExpandPointedToStructures,
4232 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004233 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004234 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004235 bool EncodingProperty,
4236 bool StructField) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004237 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004238 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004239 return EncodeBitField(this, S, T, FD);
4240 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004241 return;
4242 }
Mike Stump1eb44332009-09-09 15:08:12 +00004243
John McCall183700f2009-09-21 23:43:11 +00004244 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004245 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004246 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004247 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004248 return;
4249 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004250
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004251 // encoding for pointer or r3eference types.
4252 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004253 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004254 if (PT->isObjCSelType()) {
4255 S += ':';
4256 return;
4257 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004258 PointeeTy = PT->getPointeeType();
4259 }
4260 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4261 PointeeTy = RT->getPointeeType();
4262 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004263 bool isReadOnly = false;
4264 // For historical/compatibility reasons, the read-only qualifier of the
4265 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4266 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004267 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004268 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004269 if (OutermostType && T.isConstQualified()) {
4270 isReadOnly = true;
4271 S += 'r';
4272 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004273 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004274 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004275 while (P->getAs<PointerType>())
4276 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004277 if (P.isConstQualified()) {
4278 isReadOnly = true;
4279 S += 'r';
4280 }
4281 }
4282 if (isReadOnly) {
4283 // Another legacy compatibility encoding. Some ObjC qualifier and type
4284 // combinations need to be rearranged.
4285 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00004286 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00004287 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004288 }
Mike Stump1eb44332009-09-09 15:08:12 +00004289
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004290 if (PointeeTy->isCharType()) {
4291 // char pointer types should be encoded as '*' unless it is a
4292 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004293 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004294 S += '*';
4295 return;
4296 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004297 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004298 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4299 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4300 S += '#';
4301 return;
4302 }
4303 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4304 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4305 S += '@';
4306 return;
4307 }
4308 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004309 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004310 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004311 getLegacyIntegralTypeEncoding(PointeeTy);
4312
Mike Stump1eb44332009-09-09 15:08:12 +00004313 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004314 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004315 return;
4316 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004317
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004318 if (const ArrayType *AT =
4319 // Ignore type qualifiers etc.
4320 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004321 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004322 // Incomplete arrays are encoded as a pointer to the array element.
4323 S += '^';
4324
Mike Stump1eb44332009-09-09 15:08:12 +00004325 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004326 false, ExpandStructures, FD);
4327 } else {
4328 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004329
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004330 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4331 if (getTypeSize(CAT->getElementType()) == 0)
4332 S += '0';
4333 else
4334 S += llvm::utostr(CAT->getSize().getZExtValue());
4335 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00004336 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004337 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4338 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00004339 S += '0';
4340 }
Mike Stump1eb44332009-09-09 15:08:12 +00004341
4342 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004343 false, ExpandStructures, FD);
4344 S += ']';
4345 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004346 return;
4347 }
Mike Stump1eb44332009-09-09 15:08:12 +00004348
John McCall183700f2009-09-21 23:43:11 +00004349 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004350 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004351 return;
4352 }
Mike Stump1eb44332009-09-09 15:08:12 +00004353
Ted Kremenek6217b802009-07-29 21:53:49 +00004354 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004355 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004356 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004357 // Anonymous structures print as '?'
4358 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4359 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004360 if (ClassTemplateSpecializationDecl *Spec
4361 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4362 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4363 std::string TemplateArgsStr
4364 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004365 TemplateArgs.data(),
4366 TemplateArgs.size(),
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004367 (*this).PrintingPolicy);
4368
4369 S += TemplateArgsStr;
4370 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004371 } else {
4372 S += '?';
4373 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004374 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004375 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004376 if (!RDecl->isUnion()) {
4377 getObjCEncodingForStructureImpl(RDecl, S, FD);
4378 } else {
4379 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4380 FieldEnd = RDecl->field_end();
4381 Field != FieldEnd; ++Field) {
4382 if (FD) {
4383 S += '"';
4384 S += Field->getNameAsString();
4385 S += '"';
4386 }
Mike Stump1eb44332009-09-09 15:08:12 +00004387
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004388 // Special case bit-fields.
4389 if (Field->isBitField()) {
4390 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4391 (*Field));
4392 } else {
4393 QualType qt = Field->getType();
4394 getLegacyIntegralTypeEncoding(qt);
4395 getObjCEncodingForTypeImpl(qt, S, false, true,
4396 FD, /*OutermostType*/false,
4397 /*EncodingProperty*/false,
4398 /*StructField*/true);
4399 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004400 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004401 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004402 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004403 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004404 return;
4405 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004406
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004407 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004408 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004409 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004410 else
4411 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004412 return;
4413 }
Mike Stump1eb44332009-09-09 15:08:12 +00004414
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004415 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004416 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004417 return;
4418 }
Mike Stump1eb44332009-09-09 15:08:12 +00004419
John McCallc12c5bb2010-05-15 11:32:37 +00004420 // Ignore protocol qualifiers when mangling at this level.
4421 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4422 T = OT->getBaseType();
4423
John McCall0953e762009-09-24 19:53:00 +00004424 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004425 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004426 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004427 S += '{';
4428 const IdentifierInfo *II = OI->getIdentifier();
4429 S += II->getName();
4430 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00004431 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004432 DeepCollectObjCIvars(OI, true, Ivars);
4433 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00004434 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004435 if (Field->isBitField())
4436 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004437 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004438 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004439 }
4440 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004441 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004442 }
Mike Stump1eb44332009-09-09 15:08:12 +00004443
John McCall183700f2009-09-21 23:43:11 +00004444 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004445 if (OPT->isObjCIdType()) {
4446 S += '@';
4447 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004448 }
Mike Stump1eb44332009-09-09 15:08:12 +00004449
Steve Naroff27d20a22009-10-28 22:03:49 +00004450 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4451 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4452 // Since this is a binary compatibility issue, need to consult with runtime
4453 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004454 S += '#';
4455 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004456 }
Mike Stump1eb44332009-09-09 15:08:12 +00004457
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004458 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004459 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004460 ExpandPointedToStructures,
4461 ExpandStructures, FD);
4462 if (FD || EncodingProperty) {
4463 // Note that we do extended encoding of protocol qualifer list
4464 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004465 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004466 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4467 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004468 S += '<';
4469 S += (*I)->getNameAsString();
4470 S += '>';
4471 }
4472 S += '"';
4473 }
4474 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004475 }
Mike Stump1eb44332009-09-09 15:08:12 +00004476
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004477 QualType PointeeTy = OPT->getPointeeType();
4478 if (!EncodingProperty &&
4479 isa<TypedefType>(PointeeTy.getTypePtr())) {
4480 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004481 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004482 // {...};
4483 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004484 getObjCEncodingForTypeImpl(PointeeTy, S,
4485 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004486 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004487 return;
4488 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004489
4490 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00004491 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004492 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004493 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004494 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4495 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004496 S += '<';
4497 S += (*I)->getNameAsString();
4498 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004499 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004500 S += '"';
4501 }
4502 return;
4503 }
Mike Stump1eb44332009-09-09 15:08:12 +00004504
John McCall532ec7b2010-05-17 23:56:34 +00004505 // gcc just blithely ignores member pointers.
4506 // TODO: maybe there should be a mangling for these
4507 if (T->getAs<MemberPointerType>())
4508 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004509
4510 if (T->isVectorType()) {
4511 // This matches gcc's encoding, even though technically it is
4512 // insufficient.
4513 // FIXME. We should do a better job than gcc.
4514 return;
4515 }
4516
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004517 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004518}
4519
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004520void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4521 std::string &S,
4522 const FieldDecl *FD,
4523 bool includeVBases) const {
4524 assert(RDecl && "Expected non-null RecordDecl");
4525 assert(!RDecl->isUnion() && "Should not be called for unions");
4526 if (!RDecl->getDefinition())
4527 return;
4528
4529 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4530 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4531 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4532
4533 if (CXXRec) {
4534 for (CXXRecordDecl::base_class_iterator
4535 BI = CXXRec->bases_begin(),
4536 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4537 if (!BI->isVirtual()) {
4538 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004539 if (base->isEmpty())
4540 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004541 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4542 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4543 std::make_pair(offs, base));
4544 }
4545 }
4546 }
4547
4548 unsigned i = 0;
4549 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4550 FieldEnd = RDecl->field_end();
4551 Field != FieldEnd; ++Field, ++i) {
4552 uint64_t offs = layout.getFieldOffset(i);
4553 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4554 std::make_pair(offs, *Field));
4555 }
4556
4557 if (CXXRec && includeVBases) {
4558 for (CXXRecordDecl::base_class_iterator
4559 BI = CXXRec->vbases_begin(),
4560 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4561 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004562 if (base->isEmpty())
4563 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004564 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
4565 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4566 std::make_pair(offs, base));
4567 }
4568 }
4569
4570 CharUnits size;
4571 if (CXXRec) {
4572 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4573 } else {
4574 size = layout.getSize();
4575 }
4576
4577 uint64_t CurOffs = 0;
4578 std::multimap<uint64_t, NamedDecl *>::iterator
4579 CurLayObj = FieldOrBaseOffsets.begin();
4580
Argyrios Kyrtzidiscb8061e2011-08-22 16:03:14 +00004581 if ((CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) ||
4582 (CurLayObj == FieldOrBaseOffsets.end() &&
4583 CXXRec && CXXRec->isDynamicClass())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004584 assert(CXXRec && CXXRec->isDynamicClass() &&
4585 "Offset 0 was empty but no VTable ?");
4586 if (FD) {
4587 S += "\"_vptr$";
4588 std::string recname = CXXRec->getNameAsString();
4589 if (recname.empty()) recname = "?";
4590 S += recname;
4591 S += '"';
4592 }
4593 S += "^^?";
4594 CurOffs += getTypeSize(VoidPtrTy);
4595 }
4596
4597 if (!RDecl->hasFlexibleArrayMember()) {
4598 // Mark the end of the structure.
4599 uint64_t offs = toBits(size);
4600 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4601 std::make_pair(offs, (NamedDecl*)0));
4602 }
4603
4604 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4605 assert(CurOffs <= CurLayObj->first);
4606
4607 if (CurOffs < CurLayObj->first) {
4608 uint64_t padding = CurLayObj->first - CurOffs;
4609 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4610 // packing/alignment of members is different that normal, in which case
4611 // the encoding will be out-of-sync with the real layout.
4612 // If the runtime switches to just consider the size of types without
4613 // taking into account alignment, we could make padding explicit in the
4614 // encoding (e.g. using arrays of chars). The encoding strings would be
4615 // longer then though.
4616 CurOffs += padding;
4617 }
4618
4619 NamedDecl *dcl = CurLayObj->second;
4620 if (dcl == 0)
4621 break; // reached end of structure.
4622
4623 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4624 // We expand the bases without their virtual bases since those are going
4625 // in the initial structure. Note that this differs from gcc which
4626 // expands virtual bases each time one is encountered in the hierarchy,
4627 // making the encoding type bigger than it really is.
4628 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004629 assert(!base->isEmpty());
4630 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004631 } else {
4632 FieldDecl *field = cast<FieldDecl>(dcl);
4633 if (FD) {
4634 S += '"';
4635 S += field->getNameAsString();
4636 S += '"';
4637 }
4638
4639 if (field->isBitField()) {
4640 EncodeBitField(this, S, field->getType(), field);
4641 CurOffs += field->getBitWidth()->EvaluateAsInt(*this).getZExtValue();
4642 } else {
4643 QualType qt = field->getType();
4644 getLegacyIntegralTypeEncoding(qt);
4645 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4646 /*OutermostType*/false,
4647 /*EncodingProperty*/false,
4648 /*StructField*/true);
4649 CurOffs += getTypeSize(field->getType());
4650 }
4651 }
4652 }
4653}
4654
Mike Stump1eb44332009-09-09 15:08:12 +00004655void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004656 std::string& S) const {
4657 if (QT & Decl::OBJC_TQ_In)
4658 S += 'n';
4659 if (QT & Decl::OBJC_TQ_Inout)
4660 S += 'N';
4661 if (QT & Decl::OBJC_TQ_Out)
4662 S += 'o';
4663 if (QT & Decl::OBJC_TQ_Bycopy)
4664 S += 'O';
4665 if (QT & Decl::OBJC_TQ_Byref)
4666 S += 'R';
4667 if (QT & Decl::OBJC_TQ_Oneway)
4668 S += 'V';
4669}
4670
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004671void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004672 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004673
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004674 BuiltinVaListType = T;
4675}
4676
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00004677TypedefDecl *ASTContext::getObjCIdDecl() const {
4678 if (!ObjCIdDecl) {
4679 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4680 T = getObjCObjectPointerType(T);
4681 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4682 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4683 getTranslationUnitDecl(),
4684 SourceLocation(), SourceLocation(),
4685 &Idents.get("id"), IdInfo);
4686 }
4687
4688 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00004689}
4690
Douglas Gregor7a27ea52011-08-12 06:17:30 +00004691TypedefDecl *ASTContext::getObjCSelDecl() const {
4692 if (!ObjCSelDecl) {
4693 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4694 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4695 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4696 getTranslationUnitDecl(),
4697 SourceLocation(), SourceLocation(),
4698 &Idents.get("SEL"), SelInfo);
4699 }
4700 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004701}
4702
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004703void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004704 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00004705}
4706
Douglas Gregor79d67262011-08-12 05:59:41 +00004707TypedefDecl *ASTContext::getObjCClassDecl() const {
4708 if (!ObjCClassDecl) {
4709 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4710 T = getObjCObjectPointerType(T);
4711 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4712 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4713 getTranslationUnitDecl(),
4714 SourceLocation(), SourceLocation(),
4715 &Idents.get("Class"), ClassInfo);
4716 }
4717
4718 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004719}
4720
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004721void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004722 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004723 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004724
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004725 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004726}
4727
John McCall0bd6feb2009-12-02 08:04:21 +00004728/// \brief Retrieve the template name that corresponds to a non-empty
4729/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00004730TemplateName
4731ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4732 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00004733 unsigned size = End - Begin;
4734 assert(size > 1 && "set is not overloaded!");
4735
4736 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4737 size * sizeof(FunctionTemplateDecl*));
4738 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4739
4740 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004741 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004742 NamedDecl *D = *I;
4743 assert(isa<FunctionTemplateDecl>(D) ||
4744 (isa<UsingShadowDecl>(D) &&
4745 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4746 *Storage++ = D;
4747 }
4748
4749 return TemplateName(OT);
4750}
4751
Douglas Gregor7532dc62009-03-30 22:58:21 +00004752/// \brief Retrieve the template name that represents a qualified
4753/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00004754TemplateName
4755ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4756 bool TemplateKeyword,
4757 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00004758 assert(NNS && "Missing nested-name-specifier in qualified template name");
4759
Douglas Gregor789b1f62010-02-04 18:10:26 +00004760 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004761 llvm::FoldingSetNodeID ID;
4762 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4763
4764 void *InsertPos = 0;
4765 QualifiedTemplateName *QTN =
4766 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4767 if (!QTN) {
4768 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4769 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4770 }
4771
4772 return TemplateName(QTN);
4773}
4774
4775/// \brief Retrieve the template name that represents a dependent
4776/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00004777TemplateName
4778ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4779 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004780 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004781 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004782
4783 llvm::FoldingSetNodeID ID;
4784 DependentTemplateName::Profile(ID, NNS, Name);
4785
4786 void *InsertPos = 0;
4787 DependentTemplateName *QTN =
4788 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4789
4790 if (QTN)
4791 return TemplateName(QTN);
4792
4793 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4794 if (CanonNNS == NNS) {
4795 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4796 } else {
4797 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4798 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004799 DependentTemplateName *CheckQTN =
4800 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4801 assert(!CheckQTN && "Dependent type name canonicalization broken");
4802 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004803 }
4804
4805 DependentTemplateNames.InsertNode(QTN, InsertPos);
4806 return TemplateName(QTN);
4807}
4808
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004809/// \brief Retrieve the template name that represents a dependent
4810/// template name such as \c MetaFun::template operator+.
4811TemplateName
4812ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00004813 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004814 assert((!NNS || NNS->isDependent()) &&
4815 "Nested name specifier must be dependent");
4816
4817 llvm::FoldingSetNodeID ID;
4818 DependentTemplateName::Profile(ID, NNS, Operator);
4819
4820 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004821 DependentTemplateName *QTN
4822 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004823
4824 if (QTN)
4825 return TemplateName(QTN);
4826
4827 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4828 if (CanonNNS == NNS) {
4829 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4830 } else {
4831 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4832 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004833
4834 DependentTemplateName *CheckQTN
4835 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4836 assert(!CheckQTN && "Dependent template name canonicalization broken");
4837 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004838 }
4839
4840 DependentTemplateNames.InsertNode(QTN, InsertPos);
4841 return TemplateName(QTN);
4842}
4843
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004844TemplateName
John McCall14606042011-06-30 08:33:18 +00004845ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
4846 TemplateName replacement) const {
4847 llvm::FoldingSetNodeID ID;
4848 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
4849
4850 void *insertPos = 0;
4851 SubstTemplateTemplateParmStorage *subst
4852 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
4853
4854 if (!subst) {
4855 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
4856 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
4857 }
4858
4859 return TemplateName(subst);
4860}
4861
4862TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004863ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4864 const TemplateArgument &ArgPack) const {
4865 ASTContext &Self = const_cast<ASTContext &>(*this);
4866 llvm::FoldingSetNodeID ID;
4867 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4868
4869 void *InsertPos = 0;
4870 SubstTemplateTemplateParmPackStorage *Subst
4871 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4872
4873 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00004874 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004875 ArgPack.pack_size(),
4876 ArgPack.pack_begin());
4877 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4878 }
4879
4880 return TemplateName(Subst);
4881}
4882
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004883/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004884/// TargetInfo, produce the corresponding type. The unsigned @p Type
4885/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004886CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004887 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004888 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004889 case TargetInfo::SignedShort: return ShortTy;
4890 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4891 case TargetInfo::SignedInt: return IntTy;
4892 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4893 case TargetInfo::SignedLong: return LongTy;
4894 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4895 case TargetInfo::SignedLongLong: return LongLongTy;
4896 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4897 }
4898
4899 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004900 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004901}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004902
4903//===----------------------------------------------------------------------===//
4904// Type Predicates.
4905//===----------------------------------------------------------------------===//
4906
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004907/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4908/// garbage collection attribute.
4909///
John McCallae278a32011-01-12 00:34:59 +00004910Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4911 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4912 return Qualifiers::GCNone;
4913
4914 assert(getLangOptions().ObjC1);
4915 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4916
4917 // Default behaviour under objective-C's gc is for ObjC pointers
4918 // (or pointers to them) be treated as though they were declared
4919 // as __strong.
4920 if (GCAttrs == Qualifiers::GCNone) {
4921 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4922 return Qualifiers::Strong;
4923 else if (Ty->isPointerType())
4924 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4925 } else {
4926 // It's not valid to set GC attributes on anything that isn't a
4927 // pointer.
4928#ifndef NDEBUG
4929 QualType CT = Ty->getCanonicalTypeInternal();
4930 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4931 CT = AT->getElementType();
4932 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4933#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004934 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004935 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004936}
4937
Chris Lattner6ac46a42008-04-07 06:51:04 +00004938//===----------------------------------------------------------------------===//
4939// Type Compatibility Testing
4940//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004941
Mike Stump1eb44332009-09-09 15:08:12 +00004942/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004943/// compatible.
4944static bool areCompatVectorTypes(const VectorType *LHS,
4945 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004946 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004947 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004948 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004949}
4950
Douglas Gregor255210e2010-08-06 10:14:59 +00004951bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4952 QualType SecondVec) {
4953 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4954 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4955
4956 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4957 return true;
4958
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004959 // Treat Neon vector types and most AltiVec vector types as if they are the
4960 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00004961 const VectorType *First = FirstVec->getAs<VectorType>();
4962 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004963 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00004964 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004965 First->getVectorKind() != VectorType::AltiVecPixel &&
4966 First->getVectorKind() != VectorType::AltiVecBool &&
4967 Second->getVectorKind() != VectorType::AltiVecPixel &&
4968 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00004969 return true;
4970
4971 return false;
4972}
4973
Steve Naroff4084c302009-07-23 01:01:38 +00004974//===----------------------------------------------------------------------===//
4975// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4976//===----------------------------------------------------------------------===//
4977
4978/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4979/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00004980bool
4981ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4982 ObjCProtocolDecl *rProto) const {
Steve Naroff4084c302009-07-23 01:01:38 +00004983 if (lProto == rProto)
4984 return true;
4985 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4986 E = rProto->protocol_end(); PI != E; ++PI)
4987 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4988 return true;
4989 return false;
4990}
4991
Steve Naroff4084c302009-07-23 01:01:38 +00004992/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4993/// return true if lhs's protocols conform to rhs's protocol; false
4994/// otherwise.
4995bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4996 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4997 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4998 return false;
4999}
5000
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005001/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5002/// Class<p1, ...>.
5003bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5004 QualType rhs) {
5005 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5006 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5007 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5008
5009 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5010 E = lhsQID->qual_end(); I != E; ++I) {
5011 bool match = false;
5012 ObjCProtocolDecl *lhsProto = *I;
5013 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5014 E = rhsOPT->qual_end(); J != E; ++J) {
5015 ObjCProtocolDecl *rhsProto = *J;
5016 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5017 match = true;
5018 break;
5019 }
5020 }
5021 if (!match)
5022 return false;
5023 }
5024 return true;
5025}
5026
Steve Naroff4084c302009-07-23 01:01:38 +00005027/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5028/// ObjCQualifiedIDType.
5029bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5030 bool compare) {
5031 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00005032 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005033 lhs->isObjCIdType() || lhs->isObjCClassType())
5034 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005035 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005036 rhs->isObjCIdType() || rhs->isObjCClassType())
5037 return true;
5038
5039 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00005040 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005041
Steve Naroff4084c302009-07-23 01:01:38 +00005042 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005043
Steve Naroff4084c302009-07-23 01:01:38 +00005044 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005045 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00005046 // make sure we check the class hierarchy.
5047 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5048 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5049 E = lhsQID->qual_end(); I != E; ++I) {
5050 // when comparing an id<P> on lhs with a static type on rhs,
5051 // see if static class implements all of id's protocols, directly or
5052 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005053 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00005054 return false;
5055 }
5056 }
5057 // If there are no qualifiers and no interface, we have an 'id'.
5058 return true;
5059 }
Mike Stump1eb44332009-09-09 15:08:12 +00005060 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005061 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5062 E = lhsQID->qual_end(); I != E; ++I) {
5063 ObjCProtocolDecl *lhsProto = *I;
5064 bool match = false;
5065
5066 // when comparing an id<P> on lhs with a static type on rhs,
5067 // see if static class implements all of id's protocols, directly or
5068 // through its super class and categories.
5069 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5070 E = rhsOPT->qual_end(); J != E; ++J) {
5071 ObjCProtocolDecl *rhsProto = *J;
5072 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5073 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5074 match = true;
5075 break;
5076 }
5077 }
Mike Stump1eb44332009-09-09 15:08:12 +00005078 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00005079 // make sure we check the class hierarchy.
5080 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5081 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5082 E = lhsQID->qual_end(); I != E; ++I) {
5083 // when comparing an id<P> on lhs with a static type on rhs,
5084 // see if static class implements all of id's protocols, directly or
5085 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005086 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00005087 match = true;
5088 break;
5089 }
5090 }
5091 }
5092 if (!match)
5093 return false;
5094 }
Mike Stump1eb44332009-09-09 15:08:12 +00005095
Steve Naroff4084c302009-07-23 01:01:38 +00005096 return true;
5097 }
Mike Stump1eb44332009-09-09 15:08:12 +00005098
Steve Naroff4084c302009-07-23 01:01:38 +00005099 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5100 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5101
Mike Stump1eb44332009-09-09 15:08:12 +00005102 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00005103 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005104 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005105 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5106 E = lhsOPT->qual_end(); I != E; ++I) {
5107 ObjCProtocolDecl *lhsProto = *I;
5108 bool match = false;
5109
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005110 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00005111 // see if static class implements all of id's protocols, directly or
5112 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005113 // First, lhs protocols in the qualifier list must be found, direct
5114 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00005115 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5116 E = rhsQID->qual_end(); J != E; ++J) {
5117 ObjCProtocolDecl *rhsProto = *J;
5118 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5119 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5120 match = true;
5121 break;
5122 }
5123 }
5124 if (!match)
5125 return false;
5126 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005127
5128 // Static class's protocols, or its super class or category protocols
5129 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5130 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5131 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5132 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5133 // This is rather dubious but matches gcc's behavior. If lhs has
5134 // no type qualifier and its class has no static protocol(s)
5135 // assume that it is mismatch.
5136 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5137 return false;
5138 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5139 LHSInheritedProtocols.begin(),
5140 E = LHSInheritedProtocols.end(); I != E; ++I) {
5141 bool match = false;
5142 ObjCProtocolDecl *lhsProto = (*I);
5143 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5144 E = rhsQID->qual_end(); J != E; ++J) {
5145 ObjCProtocolDecl *rhsProto = *J;
5146 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5147 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5148 match = true;
5149 break;
5150 }
5151 }
5152 if (!match)
5153 return false;
5154 }
5155 }
Steve Naroff4084c302009-07-23 01:01:38 +00005156 return true;
5157 }
5158 return false;
5159}
5160
Eli Friedman3d815e72008-08-22 00:56:42 +00005161/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005162/// compatible for assignment from RHS to LHS. This handles validation of any
5163/// protocol qualifiers on the LHS or RHS.
5164///
Steve Naroff14108da2009-07-10 23:34:53 +00005165bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5166 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00005167 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5168 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5169
Steve Naroffde2e22d2009-07-15 18:40:39 +00005170 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00005171 if (LHS->isObjCUnqualifiedIdOrClass() ||
5172 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00005173 return true;
5174
John McCallc12c5bb2010-05-15 11:32:37 +00005175 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00005176 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5177 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00005178 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005179
5180 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5181 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5182 QualType(RHSOPT,0));
5183
John McCallc12c5bb2010-05-15 11:32:37 +00005184 // If we have 2 user-defined types, fall into that path.
5185 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00005186 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00005187
Steve Naroff4084c302009-07-23 01:01:38 +00005188 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005189}
5190
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005191/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00005192/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005193/// arguments in block literals. When passed as arguments, passing 'A*' where
5194/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5195/// not OK. For the return type, the opposite is not OK.
5196bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5197 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005198 const ObjCObjectPointerType *RHSOPT,
5199 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005200 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005201 return true;
5202
5203 if (LHSOPT->isObjCBuiltinType()) {
5204 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5205 }
5206
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005207 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005208 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5209 QualType(RHSOPT,0),
5210 false);
5211
5212 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5213 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5214 if (LHS && RHS) { // We have 2 user-defined types.
5215 if (LHS != RHS) {
5216 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005217 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005218 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005219 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005220 }
5221 else
5222 return true;
5223 }
5224 return false;
5225}
5226
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005227/// getIntersectionOfProtocols - This routine finds the intersection of set
5228/// of protocols inherited from two distinct objective-c pointer objects.
5229/// It is used to build composite qualifier list of the composite type of
5230/// the conditional expression involving two objective-c pointer objects.
5231static
5232void getIntersectionOfProtocols(ASTContext &Context,
5233 const ObjCObjectPointerType *LHSOPT,
5234 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005235 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005236
John McCallc12c5bb2010-05-15 11:32:37 +00005237 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5238 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5239 assert(LHS->getInterface() && "LHS must have an interface base");
5240 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005241
5242 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5243 unsigned LHSNumProtocols = LHS->getNumProtocols();
5244 if (LHSNumProtocols > 0)
5245 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5246 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005247 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005248 Context.CollectInheritedProtocols(LHS->getInterface(),
5249 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005250 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5251 LHSInheritedProtocols.end());
5252 }
5253
5254 unsigned RHSNumProtocols = RHS->getNumProtocols();
5255 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00005256 ObjCProtocolDecl **RHSProtocols =
5257 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005258 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5259 if (InheritedProtocolSet.count(RHSProtocols[i]))
5260 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00005261 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005262 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005263 Context.CollectInheritedProtocols(RHS->getInterface(),
5264 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005265 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5266 RHSInheritedProtocols.begin(),
5267 E = RHSInheritedProtocols.end(); I != E; ++I)
5268 if (InheritedProtocolSet.count((*I)))
5269 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005270 }
5271}
5272
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005273/// areCommonBaseCompatible - Returns common base class of the two classes if
5274/// one found. Note that this is O'2 algorithm. But it will be called as the
5275/// last type comparison in a ?-exp of ObjC pointer types before a
5276/// warning is issued. So, its invokation is extremely rare.
5277QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00005278 const ObjCObjectPointerType *Lptr,
5279 const ObjCObjectPointerType *Rptr) {
5280 const ObjCObjectType *LHS = Lptr->getObjectType();
5281 const ObjCObjectType *RHS = Rptr->getObjectType();
5282 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5283 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005284 if (!LDecl || !RDecl || (LDecl == RDecl))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005285 return QualType();
5286
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005287 do {
John McCallc12c5bb2010-05-15 11:32:37 +00005288 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005289 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005290 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005291 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5292
5293 QualType Result = QualType(LHS, 0);
5294 if (!Protocols.empty())
5295 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5296 Result = getObjCObjectPointerType(Result);
5297 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005298 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005299 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005300
5301 return QualType();
5302}
5303
John McCallc12c5bb2010-05-15 11:32:37 +00005304bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5305 const ObjCObjectType *RHS) {
5306 assert(LHS->getInterface() && "LHS is not an interface type");
5307 assert(RHS->getInterface() && "RHS is not an interface type");
5308
Chris Lattner6ac46a42008-04-07 06:51:04 +00005309 // Verify that the base decls are compatible: the RHS must be a subclass of
5310 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00005311 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00005312 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005313
Chris Lattner6ac46a42008-04-07 06:51:04 +00005314 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5315 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00005316 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00005317 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005318
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005319 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5320 // more detailed analysis is required.
5321 if (RHS->getNumProtocols() == 0) {
5322 // OK, if LHS is a superclass of RHS *and*
5323 // this superclass is assignment compatible with LHS.
5324 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005325 bool IsSuperClass =
5326 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5327 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005328 // OK if conversion of LHS to SuperClass results in narrowing of types
5329 // ; i.e., SuperClass may implement at least one of the protocols
5330 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5331 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5332 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005333 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005334 // If super class has no protocols, it is not a match.
5335 if (SuperClassInheritedProtocols.empty())
5336 return false;
5337
5338 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5339 LHSPE = LHS->qual_end();
5340 LHSPI != LHSPE; LHSPI++) {
5341 bool SuperImplementsProtocol = false;
5342 ObjCProtocolDecl *LHSProto = (*LHSPI);
5343
5344 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5345 SuperClassInheritedProtocols.begin(),
5346 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5347 ObjCProtocolDecl *SuperClassProto = (*I);
5348 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5349 SuperImplementsProtocol = true;
5350 break;
5351 }
5352 }
5353 if (!SuperImplementsProtocol)
5354 return false;
5355 }
5356 return true;
5357 }
5358 return false;
5359 }
Mike Stump1eb44332009-09-09 15:08:12 +00005360
John McCallc12c5bb2010-05-15 11:32:37 +00005361 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5362 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005363 LHSPI != LHSPE; LHSPI++) {
5364 bool RHSImplementsProtocol = false;
5365
5366 // If the RHS doesn't implement the protocol on the left, the types
5367 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00005368 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5369 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00005370 RHSPI != RHSPE; RHSPI++) {
5371 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005372 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00005373 break;
5374 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005375 }
5376 // FIXME: For better diagnostics, consider passing back the protocol name.
5377 if (!RHSImplementsProtocol)
5378 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005379 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005380 // The RHS implements all protocols listed on the LHS.
5381 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005382}
5383
Steve Naroff389bf462009-02-12 17:52:19 +00005384bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5385 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00005386 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5387 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005388
Steve Naroff14108da2009-07-10 23:34:53 +00005389 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00005390 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005391
5392 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5393 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00005394}
5395
Douglas Gregor569c3162010-08-07 11:51:51 +00005396bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5397 return canAssignObjCInterfaces(
5398 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5399 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5400}
5401
Mike Stump1eb44332009-09-09 15:08:12 +00005402/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00005403/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00005404/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00005405/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00005406bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5407 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005408 if (getLangOptions().CPlusPlus)
5409 return hasSameType(LHS, RHS);
5410
Douglas Gregor447234d2010-07-29 15:18:02 +00005411 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00005412}
5413
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005414bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00005415 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005416}
5417
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005418bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5419 return !mergeTypes(LHS, RHS, true).isNull();
5420}
5421
Peter Collingbourne48466752010-10-24 18:30:18 +00005422/// mergeTransparentUnionType - if T is a transparent union type and a member
5423/// of T is compatible with SubType, return the merged type, else return
5424/// QualType()
5425QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5426 bool OfBlockPointer,
5427 bool Unqualified) {
5428 if (const RecordType *UT = T->getAsUnionType()) {
5429 RecordDecl *UD = UT->getDecl();
5430 if (UD->hasAttr<TransparentUnionAttr>()) {
5431 for (RecordDecl::field_iterator it = UD->field_begin(),
5432 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00005433 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005434 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5435 if (!MT.isNull())
5436 return MT;
5437 }
5438 }
5439 }
5440
5441 return QualType();
5442}
5443
5444/// mergeFunctionArgumentTypes - merge two types which appear as function
5445/// argument types
5446QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5447 bool OfBlockPointer,
5448 bool Unqualified) {
5449 // GNU extension: two types are compatible if they appear as a function
5450 // argument, one of the types is a transparent union type and the other
5451 // type is compatible with a union member
5452 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5453 Unqualified);
5454 if (!lmerge.isNull())
5455 return lmerge;
5456
5457 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5458 Unqualified);
5459 if (!rmerge.isNull())
5460 return rmerge;
5461
5462 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5463}
5464
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005465QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00005466 bool OfBlockPointer,
5467 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00005468 const FunctionType *lbase = lhs->getAs<FunctionType>();
5469 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00005470 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5471 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00005472 bool allLTypes = true;
5473 bool allRTypes = true;
5474
5475 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005476 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005477 if (OfBlockPointer) {
5478 QualType RHS = rbase->getResultType();
5479 QualType LHS = lbase->getResultType();
5480 bool UnqualifiedResult = Unqualified;
5481 if (!UnqualifiedResult)
5482 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005483 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005484 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005485 else
John McCall8cc246c2010-12-15 01:06:38 +00005486 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5487 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005488 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005489
5490 if (Unqualified)
5491 retType = retType.getUnqualifiedType();
5492
5493 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5494 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5495 if (Unqualified) {
5496 LRetType = LRetType.getUnqualifiedType();
5497 RRetType = RRetType.getUnqualifiedType();
5498 }
5499
5500 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005501 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00005502 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005503 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005504
Daniel Dunbar6a15c852010-04-28 16:20:58 +00005505 // FIXME: double check this
5506 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5507 // rbase->getRegParmAttr() != 0 &&
5508 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00005509 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5510 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00005511
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005512 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00005513 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005514 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005515
John McCall8cc246c2010-12-15 01:06:38 +00005516 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00005517 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5518 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00005519 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5520 return QualType();
5521
John McCallf85e1932011-06-15 23:02:42 +00005522 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5523 return QualType();
5524
John McCall8cc246c2010-12-15 01:06:38 +00005525 // It's noreturn if either type is.
5526 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5527 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5528 if (NoReturn != lbaseInfo.getNoReturn())
5529 allLTypes = false;
5530 if (NoReturn != rbaseInfo.getNoReturn())
5531 allRTypes = false;
5532
John McCallf85e1932011-06-15 23:02:42 +00005533 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00005534
Eli Friedman3d815e72008-08-22 00:56:42 +00005535 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00005536 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5537 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005538 unsigned lproto_nargs = lproto->getNumArgs();
5539 unsigned rproto_nargs = rproto->getNumArgs();
5540
5541 // Compatible functions must have the same number of arguments
5542 if (lproto_nargs != rproto_nargs)
5543 return QualType();
5544
5545 // Variadic and non-variadic functions aren't compatible
5546 if (lproto->isVariadic() != rproto->isVariadic())
5547 return QualType();
5548
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00005549 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5550 return QualType();
5551
Eli Friedman3d815e72008-08-22 00:56:42 +00005552 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00005553 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00005554 for (unsigned i = 0; i < lproto_nargs; i++) {
5555 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5556 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005557 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5558 OfBlockPointer,
5559 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005560 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005561
5562 if (Unqualified)
5563 argtype = argtype.getUnqualifiedType();
5564
Eli Friedman3d815e72008-08-22 00:56:42 +00005565 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00005566 if (Unqualified) {
5567 largtype = largtype.getUnqualifiedType();
5568 rargtype = rargtype.getUnqualifiedType();
5569 }
5570
Chris Lattner61710852008-10-05 17:34:18 +00005571 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5572 allLTypes = false;
5573 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5574 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00005575 }
5576 if (allLTypes) return lhs;
5577 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005578
5579 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5580 EPI.ExtInfo = einfo;
5581 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005582 }
5583
5584 if (lproto) allRTypes = false;
5585 if (rproto) allLTypes = false;
5586
Douglas Gregor72564e72009-02-26 23:50:07 +00005587 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00005588 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00005589 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005590 if (proto->isVariadic()) return QualType();
5591 // Check that the types are compatible with the types that
5592 // would result from default argument promotions (C99 6.7.5.3p15).
5593 // The only types actually affected are promotable integer
5594 // types and floats, which would be passed as a different
5595 // type depending on whether the prototype is visible.
5596 unsigned proto_nargs = proto->getNumArgs();
5597 for (unsigned i = 0; i < proto_nargs; ++i) {
5598 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00005599
5600 // Look at the promotion type of enum types, since that is the type used
5601 // to pass enum values.
5602 if (const EnumType *Enum = argTy->getAs<EnumType>())
5603 argTy = Enum->getDecl()->getPromotionType();
5604
Eli Friedman3d815e72008-08-22 00:56:42 +00005605 if (argTy->isPromotableIntegerType() ||
5606 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5607 return QualType();
5608 }
5609
5610 if (allLTypes) return lhs;
5611 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005612
5613 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5614 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00005615 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005616 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005617 }
5618
5619 if (allLTypes) return lhs;
5620 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00005621 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00005622}
5623
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005624QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00005625 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005626 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00005627 // C++ [expr]: If an expression initially has the type "reference to T", the
5628 // type is adjusted to "T" prior to any further analysis, the expression
5629 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005630 // expression is an lvalue unless the reference is an rvalue reference and
5631 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005632 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5633 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00005634
5635 if (Unqualified) {
5636 LHS = LHS.getUnqualifiedType();
5637 RHS = RHS.getUnqualifiedType();
5638 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005639
Eli Friedman3d815e72008-08-22 00:56:42 +00005640 QualType LHSCan = getCanonicalType(LHS),
5641 RHSCan = getCanonicalType(RHS);
5642
5643 // If two types are identical, they are compatible.
5644 if (LHSCan == RHSCan)
5645 return LHS;
5646
John McCall0953e762009-09-24 19:53:00 +00005647 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005648 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5649 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00005650 if (LQuals != RQuals) {
5651 // If any of these qualifiers are different, we have a type
5652 // mismatch.
5653 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00005654 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5655 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00005656 return QualType();
5657
5658 // Exactly one GC qualifier difference is allowed: __strong is
5659 // okay if the other type has no GC qualifier but is an Objective
5660 // C object pointer (i.e. implicitly strong by default). We fix
5661 // this by pretending that the unqualified type was actually
5662 // qualified __strong.
5663 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5664 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5665 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5666
5667 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5668 return QualType();
5669
5670 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5671 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5672 }
5673 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5674 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5675 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005676 return QualType();
John McCall0953e762009-09-24 19:53:00 +00005677 }
5678
5679 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00005680
Eli Friedman852d63b2009-06-01 01:22:52 +00005681 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5682 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00005683
Chris Lattner1adb8832008-01-14 05:45:46 +00005684 // We want to consider the two function types to be the same for these
5685 // comparisons, just force one to the other.
5686 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5687 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00005688
5689 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00005690 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5691 LHSClass = Type::ConstantArray;
5692 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5693 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00005694
John McCallc12c5bb2010-05-15 11:32:37 +00005695 // ObjCInterfaces are just specialized ObjCObjects.
5696 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5697 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5698
Nate Begeman213541a2008-04-18 23:10:10 +00005699 // Canonicalize ExtVector -> Vector.
5700 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5701 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00005702
Chris Lattnera36a61f2008-04-07 05:43:21 +00005703 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005704 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00005705 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00005706 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00005707 // Compatibility is based on the underlying type, not the promotion
5708 // type.
John McCall183700f2009-09-21 23:43:11 +00005709 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005710 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5711 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005712 }
John McCall183700f2009-09-21 23:43:11 +00005713 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005714 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5715 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005716 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005717
Eli Friedman3d815e72008-08-22 00:56:42 +00005718 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005719 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005720
Steve Naroff4a746782008-01-09 22:43:08 +00005721 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005722 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00005723#define TYPE(Class, Base)
5724#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00005725#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00005726#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5727#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5728#include "clang/AST/TypeNodes.def"
5729 assert(false && "Non-canonical and dependent types shouldn't get here");
5730 return QualType();
5731
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005732 case Type::LValueReference:
5733 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00005734 case Type::MemberPointer:
5735 assert(false && "C++ should never be in mergeTypes");
5736 return QualType();
5737
John McCallc12c5bb2010-05-15 11:32:37 +00005738 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00005739 case Type::IncompleteArray:
5740 case Type::VariableArray:
5741 case Type::FunctionProto:
5742 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00005743 assert(false && "Types are eliminated above");
5744 return QualType();
5745
Chris Lattner1adb8832008-01-14 05:45:46 +00005746 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00005747 {
5748 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005749 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5750 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005751 if (Unqualified) {
5752 LHSPointee = LHSPointee.getUnqualifiedType();
5753 RHSPointee = RHSPointee.getUnqualifiedType();
5754 }
5755 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5756 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005757 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00005758 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005759 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00005760 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005761 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005762 return getPointerType(ResultType);
5763 }
Steve Naroffc0febd52008-12-10 17:49:55 +00005764 case Type::BlockPointer:
5765 {
5766 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005767 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5768 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005769 if (Unqualified) {
5770 LHSPointee = LHSPointee.getUnqualifiedType();
5771 RHSPointee = RHSPointee.getUnqualifiedType();
5772 }
5773 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5774 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00005775 if (ResultType.isNull()) return QualType();
5776 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5777 return LHS;
5778 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5779 return RHS;
5780 return getBlockPointerType(ResultType);
5781 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005782 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00005783 {
5784 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5785 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5786 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5787 return QualType();
5788
5789 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5790 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005791 if (Unqualified) {
5792 LHSElem = LHSElem.getUnqualifiedType();
5793 RHSElem = RHSElem.getUnqualifiedType();
5794 }
5795
5796 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005797 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00005798 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5799 return LHS;
5800 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5801 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00005802 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5803 ArrayType::ArraySizeModifier(), 0);
5804 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5805 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005806 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5807 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00005808 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5809 return LHS;
5810 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5811 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005812 if (LVAT) {
5813 // FIXME: This isn't correct! But tricky to implement because
5814 // the array's size has to be the size of LHS, but the type
5815 // has to be different.
5816 return LHS;
5817 }
5818 if (RVAT) {
5819 // FIXME: This isn't correct! But tricky to implement because
5820 // the array's size has to be the size of RHS, but the type
5821 // has to be different.
5822 return RHS;
5823 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00005824 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5825 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00005826 return getIncompleteArrayType(ResultType,
5827 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005828 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005829 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00005830 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00005831 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00005832 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00005833 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00005834 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005835 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00005836 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00005837 case Type::Complex:
5838 // Distinct complex types are incompatible.
5839 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005840 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005841 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00005842 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5843 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005844 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00005845 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00005846 case Type::ObjCObject: {
5847 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005848 // FIXME: This should be type compatibility, e.g. whether
5849 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00005850 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5851 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5852 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00005853 return LHS;
5854
Eli Friedman3d815e72008-08-22 00:56:42 +00005855 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00005856 }
Steve Naroff14108da2009-07-10 23:34:53 +00005857 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005858 if (OfBlockPointer) {
5859 if (canAssignObjCInterfacesInBlockPointer(
5860 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005861 RHS->getAs<ObjCObjectPointerType>(),
5862 BlockReturnType))
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005863 return LHS;
5864 return QualType();
5865 }
John McCall183700f2009-09-21 23:43:11 +00005866 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5867 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00005868 return LHS;
5869
Steve Naroffbc76dd02008-12-10 22:14:21 +00005870 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005871 }
Steve Naroffec0550f2007-10-15 20:41:53 +00005872 }
Douglas Gregor72564e72009-02-26 23:50:07 +00005873
5874 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005875}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00005876
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005877/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5878/// 'RHS' attributes and returns the merged version; including for function
5879/// return types.
5880QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5881 QualType LHSCan = getCanonicalType(LHS),
5882 RHSCan = getCanonicalType(RHS);
5883 // If two types are identical, they are compatible.
5884 if (LHSCan == RHSCan)
5885 return LHS;
5886 if (RHSCan->isFunctionType()) {
5887 if (!LHSCan->isFunctionType())
5888 return QualType();
5889 QualType OldReturnType =
5890 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5891 QualType NewReturnType =
5892 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5893 QualType ResReturnType =
5894 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5895 if (ResReturnType.isNull())
5896 return QualType();
5897 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5898 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5899 // In either case, use OldReturnType to build the new function type.
5900 const FunctionType *F = LHS->getAs<FunctionType>();
5901 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00005902 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5903 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005904 QualType ResultType
5905 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005906 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005907 return ResultType;
5908 }
5909 }
5910 return QualType();
5911 }
5912
5913 // If the qualifiers are different, the types can still be merged.
5914 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5915 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5916 if (LQuals != RQuals) {
5917 // If any of these qualifiers are different, we have a type mismatch.
5918 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5919 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5920 return QualType();
5921
5922 // Exactly one GC qualifier difference is allowed: __strong is
5923 // okay if the other type has no GC qualifier but is an Objective
5924 // C object pointer (i.e. implicitly strong by default). We fix
5925 // this by pretending that the unqualified type was actually
5926 // qualified __strong.
5927 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5928 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5929 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5930
5931 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5932 return QualType();
5933
5934 if (GC_L == Qualifiers::Strong)
5935 return LHS;
5936 if (GC_R == Qualifiers::Strong)
5937 return RHS;
5938 return QualType();
5939 }
5940
5941 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5942 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5943 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5944 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5945 if (ResQT == LHSBaseQT)
5946 return LHS;
5947 if (ResQT == RHSBaseQT)
5948 return RHS;
5949 }
5950 return QualType();
5951}
5952
Chris Lattner5426bf62008-04-07 07:01:58 +00005953//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00005954// Integer Predicates
5955//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00005956
Jay Foad4ba2a172011-01-12 09:06:06 +00005957unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00005958 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00005959 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005960 if (T->isBooleanType())
5961 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00005962 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00005963 return (unsigned)getTypeSize(T);
5964}
5965
5966QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00005967 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00005968
5969 // Turn <4 x signed int> -> <4 x unsigned int>
5970 if (const VectorType *VTy = T->getAs<VectorType>())
5971 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00005972 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00005973
5974 // For enums, we return the unsigned version of the base type.
5975 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00005976 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00005977
5978 const BuiltinType *BTy = T->getAs<BuiltinType>();
5979 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00005980 switch (BTy->getKind()) {
5981 case BuiltinType::Char_S:
5982 case BuiltinType::SChar:
5983 return UnsignedCharTy;
5984 case BuiltinType::Short:
5985 return UnsignedShortTy;
5986 case BuiltinType::Int:
5987 return UnsignedIntTy;
5988 case BuiltinType::Long:
5989 return UnsignedLongTy;
5990 case BuiltinType::LongLong:
5991 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00005992 case BuiltinType::Int128:
5993 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00005994 default:
5995 assert(0 && "Unexpected signed integer type");
5996 return QualType();
5997 }
5998}
5999
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00006000ASTMutationListener::~ASTMutationListener() { }
6001
Chris Lattner86df27b2009-06-14 00:45:47 +00006002
6003//===----------------------------------------------------------------------===//
6004// Builtin Type Computation
6005//===----------------------------------------------------------------------===//
6006
6007/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00006008/// pointer over the consumed characters. This returns the resultant type. If
6009/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6010/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6011/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00006012///
6013/// RequiresICE is filled in on return to indicate whether the value is required
6014/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00006015static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00006016 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00006017 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00006018 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00006019 // Modifiers.
6020 int HowLong = 0;
6021 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00006022 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006023
Chris Lattner33daae62010-10-01 22:42:38 +00006024 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00006025 bool Done = false;
6026 while (!Done) {
6027 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00006028 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006029 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00006030 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006031 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006032 case 'S':
6033 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6034 assert(!Signed && "Can't use 'S' modifier multiple times!");
6035 Signed = true;
6036 break;
6037 case 'U':
6038 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6039 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6040 Unsigned = true;
6041 break;
6042 case 'L':
6043 assert(HowLong <= 2 && "Can't have LLLL modifier");
6044 ++HowLong;
6045 break;
6046 }
6047 }
6048
6049 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00006050
Chris Lattner86df27b2009-06-14 00:45:47 +00006051 // Read the base type.
6052 switch (*Str++) {
6053 default: assert(0 && "Unknown builtin type letter!");
6054 case 'v':
6055 assert(HowLong == 0 && !Signed && !Unsigned &&
6056 "Bad modifiers used with 'v'!");
6057 Type = Context.VoidTy;
6058 break;
6059 case 'f':
6060 assert(HowLong == 0 && !Signed && !Unsigned &&
6061 "Bad modifiers used with 'f'!");
6062 Type = Context.FloatTy;
6063 break;
6064 case 'd':
6065 assert(HowLong < 2 && !Signed && !Unsigned &&
6066 "Bad modifiers used with 'd'!");
6067 if (HowLong)
6068 Type = Context.LongDoubleTy;
6069 else
6070 Type = Context.DoubleTy;
6071 break;
6072 case 's':
6073 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6074 if (Unsigned)
6075 Type = Context.UnsignedShortTy;
6076 else
6077 Type = Context.ShortTy;
6078 break;
6079 case 'i':
6080 if (HowLong == 3)
6081 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6082 else if (HowLong == 2)
6083 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6084 else if (HowLong == 1)
6085 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6086 else
6087 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6088 break;
6089 case 'c':
6090 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6091 if (Signed)
6092 Type = Context.SignedCharTy;
6093 else if (Unsigned)
6094 Type = Context.UnsignedCharTy;
6095 else
6096 Type = Context.CharTy;
6097 break;
6098 case 'b': // boolean
6099 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6100 Type = Context.BoolTy;
6101 break;
6102 case 'z': // size_t.
6103 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6104 Type = Context.getSizeType();
6105 break;
6106 case 'F':
6107 Type = Context.getCFConstantStringType();
6108 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00006109 case 'G':
6110 Type = Context.getObjCIdType();
6111 break;
6112 case 'H':
6113 Type = Context.getObjCSelType();
6114 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006115 case 'a':
6116 Type = Context.getBuiltinVaListType();
6117 assert(!Type.isNull() && "builtin va list type not initialized!");
6118 break;
6119 case 'A':
6120 // This is a "reference" to a va_list; however, what exactly
6121 // this means depends on how va_list is defined. There are two
6122 // different kinds of va_list: ones passed by value, and ones
6123 // passed by reference. An example of a by-value va_list is
6124 // x86, where va_list is a char*. An example of by-ref va_list
6125 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6126 // we want this argument to be a char*&; for x86-64, we want
6127 // it to be a __va_list_tag*.
6128 Type = Context.getBuiltinVaListType();
6129 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00006130 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00006131 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00006132 else
Chris Lattner86df27b2009-06-14 00:45:47 +00006133 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00006134 break;
6135 case 'V': {
6136 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00006137 unsigned NumElements = strtoul(Str, &End, 10);
6138 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00006139 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00006140
Chris Lattner14e0e742010-10-01 22:53:11 +00006141 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6142 RequiresICE, false);
6143 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00006144
6145 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00006146 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00006147 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00006148 break;
6149 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00006150 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00006151 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6152 false);
6153 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00006154 Type = Context.getComplexType(ElementType);
6155 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00006156 }
6157 case 'Y' : {
6158 Type = Context.getPointerDiffType();
6159 break;
6160 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006161 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00006162 Type = Context.getFILEType();
6163 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006164 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00006165 return QualType();
6166 }
Mike Stumpfd612db2009-07-28 23:47:15 +00006167 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006168 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00006169 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00006170 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00006171 else
6172 Type = Context.getjmp_bufType();
6173
Mike Stumpfd612db2009-07-28 23:47:15 +00006174 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006175 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00006176 return QualType();
6177 }
6178 break;
Mike Stump782fa302009-07-28 02:25:19 +00006179 }
Mike Stump1eb44332009-09-09 15:08:12 +00006180
Chris Lattner33daae62010-10-01 22:42:38 +00006181 // If there are modifiers and if we're allowed to parse them, go for it.
6182 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00006183 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00006184 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00006185 default: Done = true; --Str; break;
6186 case '*':
6187 case '&': {
6188 // Both pointers and references can have their pointee types
6189 // qualified with an address space.
6190 char *End;
6191 unsigned AddrSpace = strtoul(Str, &End, 10);
6192 if (End != Str && AddrSpace != 0) {
6193 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6194 Str = End;
6195 }
6196 if (c == '*')
6197 Type = Context.getPointerType(Type);
6198 else
6199 Type = Context.getLValueReferenceType(Type);
6200 break;
6201 }
6202 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6203 case 'C':
6204 Type = Type.withConst();
6205 break;
6206 case 'D':
6207 Type = Context.getVolatileType(Type);
6208 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006209 }
6210 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00006211
Chris Lattner14e0e742010-10-01 22:53:11 +00006212 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00006213 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00006214
Chris Lattner86df27b2009-06-14 00:45:47 +00006215 return Type;
6216}
6217
6218/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00006219QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00006220 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00006221 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00006222 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00006223
Chris Lattner5f9e2722011-07-23 10:55:15 +00006224 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00006225
Chris Lattner14e0e742010-10-01 22:53:11 +00006226 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00006227 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00006228 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6229 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006230 if (Error != GE_None)
6231 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00006232
6233 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6234
Chris Lattner86df27b2009-06-14 00:45:47 +00006235 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00006236 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006237 if (Error != GE_None)
6238 return QualType();
6239
Chris Lattner14e0e742010-10-01 22:53:11 +00006240 // If this argument is required to be an IntegerConstantExpression and the
6241 // caller cares, fill in the bitmask we return.
6242 if (RequiresICE && IntegerConstantArgs)
6243 *IntegerConstantArgs |= 1 << ArgTypes.size();
6244
Chris Lattner86df27b2009-06-14 00:45:47 +00006245 // Do array -> pointer decay. The builtin should use the decayed type.
6246 if (Ty->isArrayType())
6247 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00006248
Chris Lattner86df27b2009-06-14 00:45:47 +00006249 ArgTypes.push_back(Ty);
6250 }
6251
6252 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6253 "'.' should only occur at end of builtin type list!");
6254
John McCall00ccbef2010-12-21 00:44:39 +00006255 FunctionType::ExtInfo EI;
6256 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6257
6258 bool Variadic = (TypeStr[0] == '.');
6259
6260 // We really shouldn't be making a no-proto type here, especially in C++.
6261 if (ArgTypes.empty() && Variadic)
6262 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00006263
John McCalle23cf432010-12-14 08:05:40 +00006264 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00006265 EPI.ExtInfo = EI;
6266 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00006267
6268 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00006269}
Eli Friedmana95d7572009-08-19 07:44:53 +00006270
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006271GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6272 GVALinkage External = GVA_StrongExternal;
6273
6274 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006275 switch (L) {
6276 case NoLinkage:
6277 case InternalLinkage:
6278 case UniqueExternalLinkage:
6279 return GVA_Internal;
6280
6281 case ExternalLinkage:
6282 switch (FD->getTemplateSpecializationKind()) {
6283 case TSK_Undeclared:
6284 case TSK_ExplicitSpecialization:
6285 External = GVA_StrongExternal;
6286 break;
6287
6288 case TSK_ExplicitInstantiationDefinition:
6289 return GVA_ExplicitTemplateInstantiation;
6290
6291 case TSK_ExplicitInstantiationDeclaration:
6292 case TSK_ImplicitInstantiation:
6293 External = GVA_TemplateInstantiation;
6294 break;
6295 }
6296 }
6297
6298 if (!FD->isInlined())
6299 return External;
6300
6301 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6302 // GNU or C99 inline semantics. Determine whether this symbol should be
6303 // externally visible.
6304 if (FD->isInlineDefinitionExternallyVisible())
6305 return External;
6306
6307 // C99 inline semantics, where the symbol is not externally visible.
6308 return GVA_C99Inline;
6309 }
6310
6311 // C++0x [temp.explicit]p9:
6312 // [ Note: The intent is that an inline function that is the subject of
6313 // an explicit instantiation declaration will still be implicitly
6314 // instantiated when used so that the body can be considered for
6315 // inlining, but that no out-of-line copy of the inline function would be
6316 // generated in the translation unit. -- end note ]
6317 if (FD->getTemplateSpecializationKind()
6318 == TSK_ExplicitInstantiationDeclaration)
6319 return GVA_C99Inline;
6320
6321 return GVA_CXXInline;
6322}
6323
6324GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6325 // If this is a static data member, compute the kind of template
6326 // specialization. Otherwise, this variable is not part of a
6327 // template.
6328 TemplateSpecializationKind TSK = TSK_Undeclared;
6329 if (VD->isStaticDataMember())
6330 TSK = VD->getTemplateSpecializationKind();
6331
6332 Linkage L = VD->getLinkage();
6333 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6334 VD->getType()->getLinkage() == UniqueExternalLinkage)
6335 L = UniqueExternalLinkage;
6336
6337 switch (L) {
6338 case NoLinkage:
6339 case InternalLinkage:
6340 case UniqueExternalLinkage:
6341 return GVA_Internal;
6342
6343 case ExternalLinkage:
6344 switch (TSK) {
6345 case TSK_Undeclared:
6346 case TSK_ExplicitSpecialization:
6347 return GVA_StrongExternal;
6348
6349 case TSK_ExplicitInstantiationDeclaration:
6350 llvm_unreachable("Variable should not be instantiated");
6351 // Fall through to treat this like any other instantiation.
6352
6353 case TSK_ExplicitInstantiationDefinition:
6354 return GVA_ExplicitTemplateInstantiation;
6355
6356 case TSK_ImplicitInstantiation:
6357 return GVA_TemplateInstantiation;
6358 }
6359 }
6360
6361 return GVA_StrongExternal;
6362}
6363
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00006364bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006365 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6366 if (!VD->isFileVarDecl())
6367 return false;
6368 } else if (!isa<FunctionDecl>(D))
6369 return false;
6370
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006371 // Weak references don't produce any output by themselves.
6372 if (D->hasAttr<WeakRefAttr>())
6373 return false;
6374
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006375 // Aliases and used decls are required.
6376 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6377 return true;
6378
6379 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6380 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00006381 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00006382 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006383
6384 // Constructors and destructors are required.
6385 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6386 return true;
6387
6388 // The key function for a class is required.
6389 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6390 const CXXRecordDecl *RD = MD->getParent();
6391 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6392 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6393 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6394 return true;
6395 }
6396 }
6397
6398 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6399
6400 // static, static inline, always_inline, and extern inline functions can
6401 // always be deferred. Normal inline functions can be deferred in C99/C++.
6402 // Implicit template instantiations can also be deferred in C++.
6403 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6404 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6405 return false;
6406 return true;
6407 }
6408
6409 const VarDecl *VD = cast<VarDecl>(D);
6410 assert(VD->isFileVarDecl() && "Expected file scoped var");
6411
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006412 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6413 return false;
6414
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006415 // Structs that have non-trivial constructors or destructors are required.
6416
6417 // FIXME: Handle references.
Sean Hunt023df372011-05-09 18:22:59 +00006418 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006419 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6420 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Sean Hunt023df372011-05-09 18:22:59 +00006421 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6422 RD->hasTrivialCopyConstructor() &&
6423 RD->hasTrivialMoveConstructor() &&
6424 RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006425 return true;
6426 }
6427 }
6428
6429 GVALinkage L = GetGVALinkageForVariable(VD);
6430 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6431 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6432 return false;
6433 }
6434
6435 return true;
6436}
Charles Davis071cc7d2010-08-16 03:33:14 +00006437
Charles Davisee743f92010-11-09 18:04:24 +00006438CallingConv ASTContext::getDefaultMethodCallConv() {
6439 // Pass through to the C++ ABI object
6440 return ABI->getDefaultMethodCallConv();
6441}
6442
Jay Foad4ba2a172011-01-12 09:06:06 +00006443bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00006444 // Pass through to the C++ ABI object
6445 return ABI->isNearlyEmpty(RD);
6446}
6447
Peter Collingbourne14110472011-01-13 18:57:25 +00006448MangleContext *ASTContext::createMangleContext() {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00006449 switch (Target->getCXXABI()) {
Peter Collingbourne14110472011-01-13 18:57:25 +00006450 case CXXABI_ARM:
6451 case CXXABI_Itanium:
6452 return createItaniumMangleContext(*this, getDiagnostics());
6453 case CXXABI_Microsoft:
6454 return createMicrosoftMangleContext(*this, getDiagnostics());
6455 }
6456 assert(0 && "Unsupported ABI");
6457 return 0;
6458}
6459
Charles Davis071cc7d2010-08-16 03:33:14 +00006460CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00006461
6462size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00006463 return ASTRecordLayouts.getMemorySize()
6464 + llvm::capacity_in_bytes(ObjCLayouts)
6465 + llvm::capacity_in_bytes(KeyFunctions)
6466 + llvm::capacity_in_bytes(ObjCImpls)
6467 + llvm::capacity_in_bytes(BlockVarCopyInits)
6468 + llvm::capacity_in_bytes(DeclAttrs)
6469 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6470 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6471 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6472 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6473 + llvm::capacity_in_bytes(OverriddenMethods)
6474 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00006475 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00006476 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00006477}