blob: 3406be552c7193879042634c2c03c2d7905821a2 [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Ted Kremenek7d39c9a2011-07-27 18:41:12 +000033#include "llvm/Support/Capacity.h"
Charles Davis53c59df2010-08-16 03:33:14 +000034#include "CXXABI.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000035#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000036
Chris Lattnerddc135e2006-11-10 06:34:16 +000037using namespace clang;
38
Douglas Gregor9672f922010-07-03 00:47:00 +000039unsigned ASTContext::NumImplicitDefaultConstructors;
40unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000041unsigned ASTContext::NumImplicitCopyConstructors;
42unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000043unsigned ASTContext::NumImplicitMoveConstructors;
44unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000045unsigned ASTContext::NumImplicitCopyAssignmentOperators;
46unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000047unsigned ASTContext::NumImplicitMoveAssignmentOperators;
48unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000049unsigned ASTContext::NumImplicitDestructors;
50unsigned ASTContext::NumImplicitDestructorsDeclared;
51
Steve Naroff0af91202007-04-27 21:51:21 +000052enum FloatingRank {
53 FloatRank, DoubleRank, LongDoubleRank
54};
55
Douglas Gregor7dbfb462010-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 Gregorf5500772011-01-05 15:48:55 +000061 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-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 Gregorf5500772011-01-05 15:48:55 +000076 ID.AddBoolean(NTTP->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000077 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-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 Gregor7dbfb462010-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 Foad39c79802011-01-12 09:06:06 +000096 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-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 Lattner0e62c1c2011-07-23 10:55:15 +0000108 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-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 Bagnarab3185b02011-03-06 15:48:19 +0000116 SourceLocation(),
117 SourceLocation(),
118 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000119 TTP->getIndex(), 0, false,
120 TTP->isParameterPack()));
121 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-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 Lattner0e62c1c2011-07-23 10:55:15 +0000127 SmallVector<QualType, 2> ExpandedTypes;
128 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-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 Bagnaradff19302011-03-08 08:55:46 +0000136 SourceLocation(),
137 SourceLocation(),
Douglas Gregor0231d8d2011-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 Bagnaradff19302011-03-08 08:55:46 +0000147 SourceLocation(),
148 SourceLocation(),
Douglas Gregor0231d8d2011-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 Gregor7dbfb462010-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 Gregorf5500772011-01-05 15:48:55 +0000165 TTP->getPosition(),
166 TTP->isParameterPack(),
167 0,
Douglas Gregor7dbfb462010-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 Davis53c59df2010-08-16 03:33:14 +0000185CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000186 if (!LangOpts.CPlusPlus) return 0;
187
Charles Davis6bcb07a2010-08-19 02:18:14 +0000188 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000189 case CXXABI_ARM:
190 return CreateARMCXXABI(*this);
191 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000192 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000193 case CXXABI_Microsoft:
194 return CreateMicrosoftCXXABI(*this);
195 }
John McCall86353412010-08-21 22:46:04 +0000196 return 0;
Charles Davis53c59df2010-08-16 03:33:14 +0000197}
198
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000199static const LangAS::Map &getAddressSpaceMap(const TargetInfo &T,
200 const LangOptions &LOpts) {
201 if (LOpts.FakeAddressSpaceMap) {
202 // The fake address space map must have a distinct entry for each
203 // language-specific address space.
204 static const unsigned FakeAddrSpaceMap[] = {
205 1, // opencl_global
206 2, // opencl_local
207 3 // opencl_constant
208 };
209 return FakeAddrSpaceMap;
210 } else {
211 return T.getAddressSpaceMap();
212 }
213}
214
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000215ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +0000216 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000217 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000218 Builtin::Context &builtins,
Douglas Gregor5b11d492010-07-25 17:53:33 +0000219 unsigned size_reserve) :
Sebastian Redl31ad7542011-03-13 17:09:40 +0000220 FunctionProtoTypes(this_()),
John McCall773cc982010-06-11 11:07:21 +0000221 TemplateSpecializationTypes(this_()),
222 DependentTemplateSpecializationTypes(this_()),
John McCalld9dfe3a2011-06-30 08:33:18 +0000223 SubstTemplateTemplateParmPacks(this_()),
Douglas Gregor801c99d2011-08-12 06:49:56 +0000224 GlobalNestedNameSpecifier(0),
225 Int128Decl(0), UInt128Decl(0),
Douglas Gregor52e02802011-08-12 06:17:30 +0000226 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0),
Douglas Gregor0a586182011-08-12 05:59:41 +0000227 CFConstantStringTypeDecl(0),
Douglas Gregor636e2002011-08-09 17:23:49 +0000228 FILEDecl(0),
John McCall31168b02011-06-15 23:02:42 +0000229 jmp_bufDecl(0), sigjmp_bufDecl(0), BlockDescriptorType(0),
230 BlockDescriptorExtendedType(0), cudaConfigureCallDecl(0),
John McCall8cb7bdf2010-06-04 23:28:52 +0000231 NullTypeSourceInfo(QualType()),
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000232 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)),
233 AddrSpaceMap(getAddressSpaceMap(t, LOpts)), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000234 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +0000235 BuiltinInfo(builtins),
236 DeclarationNames(*this),
Argyrios Kyrtzidis440ea322010-10-28 09:29:35 +0000237 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenek520f47b2010-06-18 00:31:04 +0000238 LastSDM(0, 0),
John McCall147d0212011-02-22 22:38:33 +0000239 UniqueBlockByRefTypeID(0) {
Mike Stump11289f42009-09-09 15:08:12 +0000240 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000241 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000242 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +0000243}
244
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000245ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000246 // Release the DenseMaps associated with DeclContext objects.
247 // FIXME: Is this the ideal solution?
248 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000249
Douglas Gregor5b11d492010-07-25 17:53:33 +0000250 // Call all of the deallocation functions.
251 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
252 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000253
Douglas Gregor832940b2010-03-02 23:58:15 +0000254 // Release all of the memory associated with overridden C++ methods.
255 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
256 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
257 OM != OMEnd; ++OM)
258 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000259
Ted Kremenek076baeb2010-06-08 23:00:58 +0000260 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000261 // because they can contain DenseMaps.
262 for (llvm::DenseMap<const ObjCContainerDecl*,
263 const ASTRecordLayout*>::iterator
264 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
265 // Increment in loop to prevent using deallocated memory.
266 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
267 R->Destroy(*this);
268
Ted Kremenek076baeb2010-06-08 23:00:58 +0000269 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
270 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.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 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000275
276 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
277 AEnd = DeclAttrs.end();
278 A != AEnd; ++A)
279 A->second->~AttrVec();
280}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000281
Douglas Gregor1a809332010-05-23 18:26:36 +0000282void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
283 Deallocations.push_back(std::make_pair(Callback, Data));
284}
285
Mike Stump11289f42009-09-09 15:08:12 +0000286void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000287ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
288 ExternalSource.reset(Source.take());
289}
290
Chris Lattner4eb445d2007-01-26 01:27:23 +0000291void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000292 llvm::errs() << "\n*** AST Context Stats:\n";
293 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000294
Douglas Gregora30d0462009-05-26 14:40:08 +0000295 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000296#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000297#define ABSTRACT_TYPE(Name, Parent)
298#include "clang/AST/TypeNodes.def"
299 0 // Extra
300 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000301
Chris Lattner4eb445d2007-01-26 01:27:23 +0000302 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
303 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000304 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000305 }
306
Douglas Gregora30d0462009-05-26 14:40:08 +0000307 unsigned Idx = 0;
308 unsigned TotalBytes = 0;
309#define TYPE(Name, Parent) \
310 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000311 llvm::errs() << " " << counts[Idx] << " " << #Name \
312 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000313 TotalBytes += counts[Idx] * sizeof(Name##Type); \
314 ++Idx;
315#define ABSTRACT_TYPE(Name, Parent)
316#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000317
Chandler Carruth3c147a72011-07-04 05:32:14 +0000318 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
319
Douglas Gregor7454c562010-07-02 20:37:36 +0000320 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000321 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
322 << NumImplicitDefaultConstructors
323 << " implicit default constructors created\n";
324 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
325 << NumImplicitCopyConstructors
326 << " implicit copy constructors created\n";
Alexis Huntfcaeae42011-05-25 20:50:04 +0000327 if (getLangOptions().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000328 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
329 << NumImplicitMoveConstructors
330 << " implicit move constructors created\n";
331 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
332 << NumImplicitCopyAssignmentOperators
333 << " implicit copy assignment operators created\n";
Alexis Huntfcaeae42011-05-25 20:50:04 +0000334 if (getLangOptions().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000335 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
336 << NumImplicitMoveAssignmentOperators
337 << " implicit move assignment operators created\n";
338 llvm::errs() << NumImplicitDestructorsDeclared << "/"
339 << NumImplicitDestructors
340 << " implicit destructors created\n";
341
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000342 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000343 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000344 ExternalSource->PrintStats();
345 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000346
Douglas Gregor5b11d492010-07-25 17:53:33 +0000347 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000348}
349
Douglas Gregor801c99d2011-08-12 06:49:56 +0000350TypedefDecl *ASTContext::getInt128Decl() const {
351 if (!Int128Decl) {
352 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
353 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
354 getTranslationUnitDecl(),
355 SourceLocation(),
356 SourceLocation(),
357 &Idents.get("__int128_t"),
358 TInfo);
359 }
360
361 return Int128Decl;
362}
363
364TypedefDecl *ASTContext::getUInt128Decl() const {
365 if (!UInt128Decl) {
366 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
367 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
368 getTranslationUnitDecl(),
369 SourceLocation(),
370 SourceLocation(),
371 &Idents.get("__uint128_t"),
372 TInfo);
373 }
374
375 return UInt128Decl;
376}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000377
John McCall48f2d582009-10-23 23:03:21 +0000378void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000379 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000380 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000381 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000382}
383
Chris Lattner970e54e2006-11-12 00:37:36 +0000384void ASTContext::InitBuiltinTypes() {
385 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000386
Chris Lattner970e54e2006-11-12 00:37:36 +0000387 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000388 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000389
Chris Lattner970e54e2006-11-12 00:37:36 +0000390 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000391 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000392 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000393 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000394 InitBuiltinType(CharTy, BuiltinType::Char_S);
395 else
396 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000397 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000398 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
399 InitBuiltinType(ShortTy, BuiltinType::Short);
400 InitBuiltinType(IntTy, BuiltinType::Int);
401 InitBuiltinType(LongTy, BuiltinType::Long);
402 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000403
Chris Lattner970e54e2006-11-12 00:37:36 +0000404 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000405 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
406 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
407 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
408 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
409 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000410
Chris Lattner970e54e2006-11-12 00:37:36 +0000411 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000412 InitBuiltinType(FloatTy, BuiltinType::Float);
413 InitBuiltinType(DoubleTy, BuiltinType::Double);
414 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000415
Chris Lattnerf122cef2009-04-30 02:43:43 +0000416 // GNU extension, 128-bit integers.
417 InitBuiltinType(Int128Ty, BuiltinType::Int128);
418 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
419
Chris Lattnerad3467e2010-12-25 23:25:43 +0000420 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000421 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000422 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
423 else // -fshort-wchar makes wchar_t be unsigned.
424 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
425 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000426 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000427
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000428 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
429 InitBuiltinType(Char16Ty, BuiltinType::Char16);
430 else // C99
431 Char16Ty = getFromTargetType(Target.getChar16Type());
432
433 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
434 InitBuiltinType(Char32Ty, BuiltinType::Char32);
435 else // C99
436 Char32Ty = getFromTargetType(Target.getChar32Type());
437
Douglas Gregor4619e432008-12-05 23:32:09 +0000438 // Placeholder type for type-dependent expressions whose type is
439 // completely unknown. No code should ever check a type against
440 // DependentTy and users should never see it; however, it is here to
441 // help diagnose failures to properly check for type-dependent
442 // expressions.
443 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000444
John McCall36e7fe32010-10-12 00:20:44 +0000445 // Placeholder type for functions.
446 InitBuiltinType(OverloadTy, BuiltinType::Overload);
447
John McCall0009fcc2011-04-26 20:42:42 +0000448 // Placeholder type for bound members.
449 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
450
John McCall31996342011-04-07 08:22:57 +0000451 // "any" type; useful for debugger-like clients.
452 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
453
Chris Lattner970e54e2006-11-12 00:37:36 +0000454 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000455 FloatComplexTy = getComplexType(FloatTy);
456 DoubleComplexTy = getComplexType(DoubleTy);
457 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000458
Steve Naroff66e9f332007-10-15 14:41:52 +0000459 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000460
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000461 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000462 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
463 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000464 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000465
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000466 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000467
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000468 // void * type
469 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000470
471 // nullptr type (C++0x 2.14.7)
472 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000473}
474
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000475Diagnostic &ASTContext::getDiagnostics() const {
476 return SourceMgr.getDiagnostics();
477}
478
Douglas Gregor561eceb2010-08-30 16:49:28 +0000479AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
480 AttrVec *&Result = DeclAttrs[D];
481 if (!Result) {
482 void *Mem = Allocate(sizeof(AttrVec));
483 Result = new (Mem) AttrVec;
484 }
485
486 return *Result;
487}
488
489/// \brief Erase the attributes corresponding to the given declaration.
490void ASTContext::eraseDeclAttrs(const Decl *D) {
491 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
492 if (Pos != DeclAttrs.end()) {
493 Pos->second->~AttrVec();
494 DeclAttrs.erase(Pos);
495 }
496}
497
Douglas Gregor86d142a2009-10-08 07:24:58 +0000498MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000499ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000500 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000501 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000502 = InstantiatedFromStaticDataMember.find(Var);
503 if (Pos == InstantiatedFromStaticDataMember.end())
504 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000505
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000506 return Pos->second;
507}
508
Mike Stump11289f42009-09-09 15:08:12 +0000509void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000510ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000511 TemplateSpecializationKind TSK,
512 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000513 assert(Inst->isStaticDataMember() && "Not a static data member");
514 assert(Tmpl->isStaticDataMember() && "Not a static data member");
515 assert(!InstantiatedFromStaticDataMember[Inst] &&
516 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000517 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000518 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000519}
520
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000521FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
522 const FunctionDecl *FD){
523 assert(FD && "Specialization is 0");
524 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000525 = ClassScopeSpecializationPattern.find(FD);
526 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000527 return 0;
528
529 return Pos->second;
530}
531
532void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
533 FunctionDecl *Pattern) {
534 assert(FD && "Specialization is 0");
535 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000536 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000537}
538
John McCalle61f2ba2009-11-18 02:36:19 +0000539NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000540ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000541 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000542 = InstantiatedFromUsingDecl.find(UUD);
543 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000544 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000545
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000546 return Pos->second;
547}
548
549void
John McCallb96ec562009-12-04 22:46:56 +0000550ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
551 assert((isa<UsingDecl>(Pattern) ||
552 isa<UnresolvedUsingValueDecl>(Pattern) ||
553 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
554 "pattern decl is not a using decl");
555 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
556 InstantiatedFromUsingDecl[Inst] = Pattern;
557}
558
559UsingShadowDecl *
560ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
561 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
562 = InstantiatedFromUsingShadowDecl.find(Inst);
563 if (Pos == InstantiatedFromUsingShadowDecl.end())
564 return 0;
565
566 return Pos->second;
567}
568
569void
570ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
571 UsingShadowDecl *Pattern) {
572 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
573 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000574}
575
Anders Carlsson5da84842009-09-01 04:26:58 +0000576FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
577 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
578 = InstantiatedFromUnnamedFieldDecl.find(Field);
579 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
580 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000581
Anders Carlsson5da84842009-09-01 04:26:58 +0000582 return Pos->second;
583}
584
585void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
586 FieldDecl *Tmpl) {
587 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
588 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
589 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
590 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000591
Anders Carlsson5da84842009-09-01 04:26:58 +0000592 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
593}
594
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000595bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
596 const FieldDecl *LastFD) const {
597 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Chad Rosierb43c21a2011-08-04 21:50:29 +0000598 FD->getBitWidth()->EvaluateAsInt(*this).getZExtValue() == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000599}
600
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000601bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
602 const FieldDecl *LastFD) const {
603 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Chad Rosierb43c21a2011-08-04 21:50:29 +0000604 FD->getBitWidth()->EvaluateAsInt(*this).getZExtValue() == 0 &&
605 LastFD->getBitWidth()->EvaluateAsInt(*this).getZExtValue() != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000606}
607
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000608bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
609 const FieldDecl *LastFD) const {
610 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Chad Rosierb43c21a2011-08-04 21:50:29 +0000611 FD->getBitWidth()->EvaluateAsInt(*this).getZExtValue() &&
612 LastFD->getBitWidth()->EvaluateAsInt(*this).getZExtValue());
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000613}
614
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000615bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000616 const FieldDecl *LastFD) const {
617 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Chad Rosierb43c21a2011-08-04 21:50:29 +0000618 LastFD->getBitWidth()->EvaluateAsInt(*this).getZExtValue());
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000619}
620
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000621bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000622 const FieldDecl *LastFD) const {
623 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Chad Rosierb43c21a2011-08-04 21:50:29 +0000624 FD->getBitWidth()->EvaluateAsInt(*this).getZExtValue());
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000625}
626
Douglas Gregor832940b2010-03-02 23:58:15 +0000627ASTContext::overridden_cxx_method_iterator
628ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
629 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
630 = OverriddenMethods.find(Method);
631 if (Pos == OverriddenMethods.end())
632 return 0;
633
634 return Pos->second.begin();
635}
636
637ASTContext::overridden_cxx_method_iterator
638ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
639 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
640 = OverriddenMethods.find(Method);
641 if (Pos == OverriddenMethods.end())
642 return 0;
643
644 return Pos->second.end();
645}
646
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000647unsigned
648ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
649 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
650 = OverriddenMethods.find(Method);
651 if (Pos == OverriddenMethods.end())
652 return 0;
653
654 return Pos->second.size();
655}
656
Douglas Gregor832940b2010-03-02 23:58:15 +0000657void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
658 const CXXMethodDecl *Overridden) {
659 OverriddenMethods[Method].push_back(Overridden);
660}
661
Chris Lattner53cfe802007-07-18 17:52:12 +0000662//===----------------------------------------------------------------------===//
663// Type Sizing and Analysis
664//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000665
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000666/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
667/// scalar floating point type.
668const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000669 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000670 assert(BT && "Not a floating point type!");
671 switch (BT->getKind()) {
672 default: assert(0 && "Not a floating point type!");
673 case BuiltinType::Float: return Target.getFloatFormat();
674 case BuiltinType::Double: return Target.getDoubleFormat();
675 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
676 }
677}
678
Ken Dyck160146e2010-01-27 17:10:57 +0000679/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000680/// specified decl. Note that bitfields do not have a valid alignment, so
681/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000682/// If @p RefAsPointee, references are treated like their underlying type
683/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000684CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedman19a546c2009-02-22 02:56:25 +0000685 unsigned Align = Target.getCharWidth();
686
John McCall94268702010-10-08 18:24:19 +0000687 bool UseAlignAttrOnly = false;
688 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
689 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000690
John McCall94268702010-10-08 18:24:19 +0000691 // __attribute__((aligned)) can increase or decrease alignment
692 // *except* on a struct or struct member, where it only increases
693 // alignment unless 'packed' is also specified.
694 //
695 // It is an error for [[align]] to decrease alignment, so we can
696 // ignore that possibility; Sema should diagnose it.
697 if (isa<FieldDecl>(D)) {
698 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
699 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
700 } else {
701 UseAlignAttrOnly = true;
702 }
703 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000704 else if (isa<FieldDecl>(D))
705 UseAlignAttrOnly =
706 D->hasAttr<PackedAttr>() ||
707 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000708
John McCall4e819612011-01-20 07:57:12 +0000709 // If we're using the align attribute only, just ignore everything
710 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000711 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000712 // do nothing
713
John McCall94268702010-10-08 18:24:19 +0000714 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000715 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000716 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000717 if (RefAsPointee)
718 T = RT->getPointeeType();
719 else
720 T = getPointerType(RT->getPointeeType());
721 }
722 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000723 // Adjust alignments of declarations with array type by the
724 // large-array alignment on the target.
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000725 unsigned MinWidth = Target.getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000726 const ArrayType *arrayType;
727 if (MinWidth && (arrayType = getAsArrayType(T))) {
728 if (isa<VariableArrayType>(arrayType))
729 Align = std::max(Align, Target.getLargeArrayAlign());
730 else if (isa<ConstantArrayType>(arrayType) &&
731 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
732 Align = std::max(Align, Target.getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000733
John McCall33ddac02011-01-19 10:06:00 +0000734 // Walk through any array types while we're at it.
735 T = getBaseElementType(arrayType);
736 }
Chad Rosier99ee7822011-07-26 07:03:04 +0000737 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +0000738 }
John McCall4e819612011-01-20 07:57:12 +0000739
740 // Fields can be subject to extra alignment constraints, like if
741 // the field is packed, the struct is packed, or the struct has a
742 // a max-field-alignment constraint (#pragma pack). So calculate
743 // the actual alignment of the field within the struct, and then
744 // (as we're expected to) constrain that by the alignment of the type.
745 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
746 // So calculate the alignment of the field.
747 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
748
749 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000750 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000751
752 // Use the GCD of that and the offset within the record.
753 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
754 if (offset > 0) {
755 // Alignment is always a power of 2, so the GCD will be a power of 2,
756 // which means we get to do this crazy thing instead of Euclid's.
757 uint64_t lowBitOfOffset = offset & (~offset + 1);
758 if (lowBitOfOffset < fieldAlign)
759 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
760 }
761
762 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000763 }
Chris Lattner68061312009-01-24 21:53:27 +0000764 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000765
Ken Dyckcc56c542011-01-15 18:38:59 +0000766 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000767}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000768
John McCall87fe5d52010-05-20 01:18:31 +0000769std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000770ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000771 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000772 return std::make_pair(toCharUnitsFromBits(Info.first),
773 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000774}
775
776std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000777ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000778 return getTypeInfoInChars(T.getTypePtr());
779}
780
Chris Lattner983a8bb2007-07-13 22:13:22 +0000781/// getTypeSize - Return the size of the specified type, in bits. This method
782/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000783///
784/// FIXME: Pointers into different addr spaces could have different sizes and
785/// alignment requirements: getPointerInfo should take an AddrSpace, this
786/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000787std::pair<uint64_t, unsigned>
Jay Foad39c79802011-01-12 09:06:06 +0000788ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000789 uint64_t Width=0;
790 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000791 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000792#define TYPE(Class, Base)
793#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000794#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000795#define DEPENDENT_TYPE(Class, Base) case Type::Class:
796#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +0000797 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000798 break;
799
Chris Lattner355332d2007-07-13 22:27:08 +0000800 case Type::FunctionNoProto:
801 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000802 // GCC extension: alignof(function) = 32 bits
803 Width = 0;
804 Align = 32;
805 break;
806
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000807 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000808 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000809 Width = 0;
810 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
811 break;
812
Steve Naroff5c131802007-08-30 01:06:46 +0000813 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000814 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000815
Chris Lattner37e05872008-03-05 18:54:05 +0000816 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000817 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000818 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +0000819 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000820 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000821 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000822 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000823 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000824 const VectorType *VT = cast<VectorType>(T);
825 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
826 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000827 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000828 // If the alignment is not a power of 2, round up to the next power of 2.
829 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000830 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000831 Align = llvm::NextPowerOf2(Align);
832 Width = llvm::RoundUpToAlignment(Width, Align);
833 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000834 break;
835 }
Chris Lattner647fb222007-07-18 18:26:58 +0000836
Chris Lattner7570e9c2008-03-08 08:52:55 +0000837 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000838 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000839 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000840 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000841 // GCC extension: alignof(void) = 8 bits.
842 Width = 0;
843 Align = 8;
844 break;
845
Chris Lattner6a4f7452007-12-19 19:23:28 +0000846 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000847 Width = Target.getBoolWidth();
848 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000849 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000850 case BuiltinType::Char_S:
851 case BuiltinType::Char_U:
852 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000853 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000854 Width = Target.getCharWidth();
855 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000856 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000857 case BuiltinType::WChar_S:
858 case BuiltinType::WChar_U:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000859 Width = Target.getWCharWidth();
860 Align = Target.getWCharAlign();
861 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000862 case BuiltinType::Char16:
863 Width = Target.getChar16Width();
864 Align = Target.getChar16Align();
865 break;
866 case BuiltinType::Char32:
867 Width = Target.getChar32Width();
868 Align = Target.getChar32Align();
869 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000870 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000871 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000872 Width = Target.getShortWidth();
873 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000874 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000875 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000876 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000877 Width = Target.getIntWidth();
878 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000879 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000880 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000881 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000882 Width = Target.getLongWidth();
883 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000884 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000885 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000886 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000887 Width = Target.getLongLongWidth();
888 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000889 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000890 case BuiltinType::Int128:
891 case BuiltinType::UInt128:
892 Width = 128;
893 Align = 128; // int128_t is 128-bit aligned on all targets.
894 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000895 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000896 Width = Target.getFloatWidth();
897 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000898 break;
899 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000900 Width = Target.getDoubleWidth();
901 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000902 break;
903 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000904 Width = Target.getLongDoubleWidth();
905 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000906 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000907 case BuiltinType::NullPtr:
908 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
909 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000910 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000911 case BuiltinType::ObjCId:
912 case BuiltinType::ObjCClass:
913 case BuiltinType::ObjCSel:
914 Width = Target.getPointerWidth(0);
915 Align = Target.getPointerAlign(0);
916 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000917 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000918 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000919 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000920 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000921 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000922 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000923 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000924 unsigned AS = getTargetAddressSpace(
925 cast<BlockPointerType>(T)->getPointeeType());
Steve Naroff921a45c2008-09-24 15:05:44 +0000926 Width = Target.getPointerWidth(AS);
927 Align = Target.getPointerAlign(AS);
928 break;
929 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000930 case Type::LValueReference:
931 case Type::RValueReference: {
932 // alignof and sizeof should never enter this code path here, so we go
933 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000934 unsigned AS = getTargetAddressSpace(
935 cast<ReferenceType>(T)->getPointeeType());
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000936 Width = Target.getPointerWidth(AS);
937 Align = Target.getPointerAlign(AS);
938 break;
939 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000940 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000941 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000942 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000943 Align = Target.getPointerAlign(AS);
944 break;
945 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000946 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000947 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000948 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000949 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000950 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000951 Align = PtrDiffInfo.second;
952 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000953 }
Chris Lattner647fb222007-07-18 18:26:58 +0000954 case Type::Complex: {
955 // Complex types have the same alignment as their elements, but twice the
956 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000957 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000958 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000959 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000960 Align = EltInfo.second;
961 break;
962 }
John McCall8b07ec22010-05-15 11:32:37 +0000963 case Type::ObjCObject:
964 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000965 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000966 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000967 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000968 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000969 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +0000970 break;
971 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000972 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000973 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000974 const TagType *TT = cast<TagType>(T);
975
976 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +0000977 Width = 8;
978 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +0000979 break;
980 }
Mike Stump11289f42009-09-09 15:08:12 +0000981
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000982 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000983 return getTypeInfo(ET->getDecl()->getIntegerType());
984
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000985 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000986 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000987 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000988 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +0000989 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000990 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000991
Chris Lattner63d2b362009-10-22 05:17:15 +0000992 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000993 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
994 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000995
Richard Smith30482bc2011-02-20 03:19:35 +0000996 case Type::Auto: {
997 const AutoType *A = cast<AutoType>(T);
998 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +0000999 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001000 }
1001
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001002 case Type::Paren:
1003 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1004
Douglas Gregoref462e62009-04-30 17:32:17 +00001005 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001006 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001007 std::pair<uint64_t, unsigned> Info
1008 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001009 // If the typedef has an aligned attribute on it, it overrides any computed
1010 // alignment we have. This violates the GCC documentation (which says that
1011 // attribute(aligned) can only round up) but matches its implementation.
1012 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1013 Align = AttrAlign;
1014 else
1015 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001016 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001017 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001018 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001019
1020 case Type::TypeOfExpr:
1021 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1022 .getTypePtr());
1023
1024 case Type::TypeOf:
1025 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1026
Anders Carlsson81df7b82009-06-24 19:06:50 +00001027 case Type::Decltype:
1028 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1029 .getTypePtr());
1030
Alexis Hunte852b102011-05-24 22:41:36 +00001031 case Type::UnaryTransform:
1032 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1033
Abramo Bagnara6150c882010-05-11 21:36:43 +00001034 case Type::Elaborated:
1035 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001036
John McCall81904512011-01-06 01:58:22 +00001037 case Type::Attributed:
1038 return getTypeInfo(
1039 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1040
Richard Smith3f1b5d02011-05-05 21:57:07 +00001041 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001042 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001043 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001044 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1045 // A type alias template specialization may refer to a typedef with the
1046 // aligned attribute on it.
1047 if (TST->isTypeAlias())
1048 return getTypeInfo(TST->getAliasedType().getTypePtr());
1049 else
1050 return getTypeInfo(getCanonicalType(T));
1051 }
1052
Douglas Gregoref462e62009-04-30 17:32:17 +00001053 }
Mike Stump11289f42009-09-09 15:08:12 +00001054
Chris Lattner53cfe802007-07-18 17:52:12 +00001055 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001056 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001057}
1058
Ken Dyckcc56c542011-01-15 18:38:59 +00001059/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1060CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1061 return CharUnits::fromQuantity(BitSize / getCharWidth());
1062}
1063
Ken Dyckb0fcc592011-02-11 01:54:29 +00001064/// toBits - Convert a size in characters to a size in characters.
1065int64_t ASTContext::toBits(CharUnits CharSize) const {
1066 return CharSize.getQuantity() * getCharWidth();
1067}
1068
Ken Dyck8c89d592009-12-22 14:23:30 +00001069/// getTypeSizeInChars - Return the size of the specified type, in characters.
1070/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001071CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001072 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001073}
Jay Foad39c79802011-01-12 09:06:06 +00001074CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001075 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001076}
1077
Ken Dycka6046ab2010-01-26 17:25:18 +00001078/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001079/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001080CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001081 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001082}
Jay Foad39c79802011-01-12 09:06:06 +00001083CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001084 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001085}
1086
Chris Lattnera3402cd2009-01-27 18:08:34 +00001087/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1088/// type for the current target in bits. This can be different than the ABI
1089/// alignment in cases where it is beneficial for performance to overalign
1090/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001091unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001092 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001093
1094 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001095 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001096 T = CT->getElementType().getTypePtr();
1097 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1098 T->isSpecificBuiltinType(BuiltinType::LongLong))
1099 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1100
Chris Lattnera3402cd2009-01-27 18:08:34 +00001101 return ABIAlign;
1102}
1103
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001104/// DeepCollectObjCIvars -
1105/// This routine first collects all declared, but not synthesized, ivars in
1106/// super class and then collects all ivars, including those synthesized for
1107/// current class. This routine is used for implementation of current class
1108/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001109///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001110void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1111 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001112 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001113 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1114 DeepCollectObjCIvars(SuperClass, false, Ivars);
1115 if (!leafClass) {
1116 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1117 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +00001118 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001119 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001120 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001121 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001122 Iv= Iv->getNextIvar())
1123 Ivars.push_back(Iv);
1124 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001125}
1126
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001127/// CollectInheritedProtocols - Collect all protocols in current class and
1128/// those inherited by it.
1129void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001130 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001131 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001132 // We can use protocol_iterator here instead of
1133 // all_referenced_protocol_iterator since we are walking all categories.
1134 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1135 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001136 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001137 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001138 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001139 PE = Proto->protocol_end(); P != PE; ++P) {
1140 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001141 CollectInheritedProtocols(*P, Protocols);
1142 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001143 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001144
1145 // Categories of this Interface.
1146 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1147 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1148 CollectInheritedProtocols(CDeclChain, Protocols);
1149 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1150 while (SD) {
1151 CollectInheritedProtocols(SD, Protocols);
1152 SD = SD->getSuperClass();
1153 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001154 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001155 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001156 PE = OC->protocol_end(); P != PE; ++P) {
1157 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001158 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001159 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1160 PE = Proto->protocol_end(); P != PE; ++P)
1161 CollectInheritedProtocols(*P, Protocols);
1162 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001163 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001164 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1165 PE = OP->protocol_end(); P != PE; ++P) {
1166 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001167 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001168 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1169 PE = Proto->protocol_end(); P != PE; ++P)
1170 CollectInheritedProtocols(*P, Protocols);
1171 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001172 }
1173}
1174
Jay Foad39c79802011-01-12 09:06:06 +00001175unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001176 unsigned count = 0;
1177 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001178 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1179 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001180 count += CDecl->ivar_size();
1181
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001182 // Count ivar defined in this class's implementation. This
1183 // includes synthesized ivars.
1184 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001185 count += ImplDecl->ivar_size();
1186
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001187 return count;
1188}
1189
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001190/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1191ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1192 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1193 I = ObjCImpls.find(D);
1194 if (I != ObjCImpls.end())
1195 return cast<ObjCImplementationDecl>(I->second);
1196 return 0;
1197}
1198/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1199ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1200 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1201 I = ObjCImpls.find(D);
1202 if (I != ObjCImpls.end())
1203 return cast<ObjCCategoryImplDecl>(I->second);
1204 return 0;
1205}
1206
1207/// \brief Set the implementation of ObjCInterfaceDecl.
1208void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1209 ObjCImplementationDecl *ImplD) {
1210 assert(IFaceD && ImplD && "Passed null params");
1211 ObjCImpls[IFaceD] = ImplD;
1212}
1213/// \brief Set the implementation of ObjCCategoryDecl.
1214void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1215 ObjCCategoryImplDecl *ImplD) {
1216 assert(CatD && ImplD && "Passed null params");
1217 ObjCImpls[CatD] = ImplD;
1218}
1219
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001220/// \brief Get the copy initialization expression of VarDecl,or NULL if
1221/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001222Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001223 assert(VD && "Passed null params");
1224 assert(VD->hasAttr<BlocksAttr>() &&
1225 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001226 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001227 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001228 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1229}
1230
1231/// \brief Set the copy inialization expression of a block var decl.
1232void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1233 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001234 assert(VD->hasAttr<BlocksAttr>() &&
1235 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001236 BlockVarCopyInits[VD] = Init;
1237}
1238
John McCallbcd03502009-12-07 02:54:59 +00001239/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001240///
John McCallbcd03502009-12-07 02:54:59 +00001241/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001242/// the TypeLoc wrappers.
1243///
1244/// \param T the type that will be the basis for type source info. This type
1245/// should refer to how the declarator was written in source code, not to
1246/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001247TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001248 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001249 if (!DataSize)
1250 DataSize = TypeLoc::getFullDataSizeForType(T);
1251 else
1252 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001253 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001254
John McCallbcd03502009-12-07 02:54:59 +00001255 TypeSourceInfo *TInfo =
1256 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1257 new (TInfo) TypeSourceInfo(T);
1258 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001259}
1260
John McCallbcd03502009-12-07 02:54:59 +00001261TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001262 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001263 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001264 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001265 return DI;
1266}
1267
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001268const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001269ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001270 return getObjCLayout(D, 0);
1271}
1272
1273const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001274ASTContext::getASTObjCImplementationLayout(
1275 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001276 return getObjCLayout(D->getClassInterface(), D);
1277}
1278
Chris Lattner983a8bb2007-07-13 22:13:22 +00001279//===----------------------------------------------------------------------===//
1280// Type creation/memoization methods
1281//===----------------------------------------------------------------------===//
1282
Jay Foad39c79802011-01-12 09:06:06 +00001283QualType
John McCall33ddac02011-01-19 10:06:00 +00001284ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1285 unsigned fastQuals = quals.getFastQualifiers();
1286 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001287
1288 // Check if we've already instantiated this type.
1289 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001290 ExtQuals::Profile(ID, baseType, quals);
1291 void *insertPos = 0;
1292 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1293 assert(eq->getQualifiers() == quals);
1294 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001295 }
1296
John McCall33ddac02011-01-19 10:06:00 +00001297 // If the base type is not canonical, make the appropriate canonical type.
1298 QualType canon;
1299 if (!baseType->isCanonicalUnqualified()) {
1300 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1301 canonSplit.second.addConsistentQualifiers(quals);
1302 canon = getExtQualType(canonSplit.first, canonSplit.second);
1303
1304 // Re-find the insert position.
1305 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1306 }
1307
1308 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1309 ExtQualNodes.InsertNode(eq, insertPos);
1310 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001311}
1312
Jay Foad39c79802011-01-12 09:06:06 +00001313QualType
1314ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001315 QualType CanT = getCanonicalType(T);
1316 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001317 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001318
John McCall8ccfcb52009-09-24 19:53:00 +00001319 // If we are composing extended qualifiers together, merge together
1320 // into one ExtQuals node.
1321 QualifierCollector Quals;
1322 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001323
John McCall8ccfcb52009-09-24 19:53:00 +00001324 // If this type already has an address space specified, it cannot get
1325 // another one.
1326 assert(!Quals.hasAddressSpace() &&
1327 "Type cannot be in multiple addr spaces!");
1328 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001329
John McCall8ccfcb52009-09-24 19:53:00 +00001330 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001331}
1332
Chris Lattnerd60183d2009-02-18 22:53:11 +00001333QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001334 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001335 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001336 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001337 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001338
John McCall53fa7142010-12-24 02:08:15 +00001339 if (const PointerType *ptr = T->getAs<PointerType>()) {
1340 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001341 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001342 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1343 return getPointerType(ResultType);
1344 }
1345 }
Mike Stump11289f42009-09-09 15:08:12 +00001346
John McCall8ccfcb52009-09-24 19:53:00 +00001347 // If we are composing extended qualifiers together, merge together
1348 // into one ExtQuals node.
1349 QualifierCollector Quals;
1350 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001351
John McCall8ccfcb52009-09-24 19:53:00 +00001352 // If this type already has an ObjCGC specified, it cannot get
1353 // another one.
1354 assert(!Quals.hasObjCGCAttr() &&
1355 "Type cannot have multiple ObjCGCs!");
1356 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001357
John McCall8ccfcb52009-09-24 19:53:00 +00001358 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001359}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001360
John McCall4f5019e2010-12-19 02:44:49 +00001361const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1362 FunctionType::ExtInfo Info) {
1363 if (T->getExtInfo() == Info)
1364 return T;
1365
1366 QualType Result;
1367 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1368 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1369 } else {
1370 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1371 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1372 EPI.ExtInfo = Info;
1373 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1374 FPT->getNumArgs(), EPI);
1375 }
1376
1377 return cast<FunctionType>(Result.getTypePtr());
1378}
1379
Chris Lattnerc6395932007-06-22 20:56:16 +00001380/// getComplexType - Return the uniqued reference to the type for a complex
1381/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001382QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001383 // Unique pointers, to guarantee there is only one pointer of a particular
1384 // structure.
1385 llvm::FoldingSetNodeID ID;
1386 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001387
Chris Lattnerc6395932007-06-22 20:56:16 +00001388 void *InsertPos = 0;
1389 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1390 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001391
Chris Lattnerc6395932007-06-22 20:56:16 +00001392 // If the pointee type isn't canonical, this won't be a canonical type either,
1393 // so fill in the canonical type field.
1394 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001395 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001396 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001397
Chris Lattnerc6395932007-06-22 20:56:16 +00001398 // Get the new insert position for the node we care about.
1399 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001400 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001401 }
John McCall90d1c2d2009-09-24 23:30:46 +00001402 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001403 Types.push_back(New);
1404 ComplexTypes.InsertNode(New, InsertPos);
1405 return QualType(New, 0);
1406}
1407
Chris Lattner970e54e2006-11-12 00:37:36 +00001408/// getPointerType - Return the uniqued reference to the type for a pointer to
1409/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001410QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001411 // Unique pointers, to guarantee there is only one pointer of a particular
1412 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001413 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001414 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001415
Chris Lattner67521df2007-01-27 01:29:36 +00001416 void *InsertPos = 0;
1417 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001418 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001419
Chris Lattner7ccecb92006-11-12 08:50:50 +00001420 // If the pointee type isn't canonical, this won't be a canonical type either,
1421 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001422 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001423 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001424 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001425
Chris Lattner67521df2007-01-27 01:29:36 +00001426 // Get the new insert position for the node we care about.
1427 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001428 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001429 }
John McCall90d1c2d2009-09-24 23:30:46 +00001430 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001431 Types.push_back(New);
1432 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001433 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001434}
1435
Mike Stump11289f42009-09-09 15:08:12 +00001436/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001437/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001438QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001439 assert(T->isFunctionType() && "block of function types only");
1440 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001441 // structure.
1442 llvm::FoldingSetNodeID ID;
1443 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001444
Steve Naroffec33ed92008-08-27 16:04:49 +00001445 void *InsertPos = 0;
1446 if (BlockPointerType *PT =
1447 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1448 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001449
1450 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001451 // type either so fill in the canonical type field.
1452 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001453 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001454 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001455
Steve Naroffec33ed92008-08-27 16:04:49 +00001456 // Get the new insert position for the node we care about.
1457 BlockPointerType *NewIP =
1458 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001459 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001460 }
John McCall90d1c2d2009-09-24 23:30:46 +00001461 BlockPointerType *New
1462 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001463 Types.push_back(New);
1464 BlockPointerTypes.InsertNode(New, InsertPos);
1465 return QualType(New, 0);
1466}
1467
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001468/// getLValueReferenceType - Return the uniqued reference to the type for an
1469/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001470QualType
1471ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001472 assert(getCanonicalType(T) != OverloadTy &&
1473 "Unresolved overloaded function type");
1474
Bill Wendling3708c182007-05-27 10:15:43 +00001475 // Unique pointers, to guarantee there is only one pointer of a particular
1476 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001477 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001478 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001479
1480 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001481 if (LValueReferenceType *RT =
1482 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001483 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001484
John McCallfc93cf92009-10-22 22:37:11 +00001485 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1486
Bill Wendling3708c182007-05-27 10:15:43 +00001487 // If the referencee type isn't canonical, this won't be a canonical type
1488 // either, so fill in the canonical type field.
1489 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001490 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1491 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1492 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001493
Bill Wendling3708c182007-05-27 10:15:43 +00001494 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001495 LValueReferenceType *NewIP =
1496 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001497 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001498 }
1499
John McCall90d1c2d2009-09-24 23:30:46 +00001500 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001501 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1502 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001503 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001504 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001505
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001506 return QualType(New, 0);
1507}
1508
1509/// getRValueReferenceType - Return the uniqued reference to the type for an
1510/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001511QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001512 // Unique pointers, to guarantee there is only one pointer of a particular
1513 // structure.
1514 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001515 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001516
1517 void *InsertPos = 0;
1518 if (RValueReferenceType *RT =
1519 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1520 return QualType(RT, 0);
1521
John McCallfc93cf92009-10-22 22:37:11 +00001522 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1523
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001524 // If the referencee type isn't canonical, this won't be a canonical type
1525 // either, so fill in the canonical type field.
1526 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001527 if (InnerRef || !T.isCanonical()) {
1528 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1529 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001530
1531 // Get the new insert position for the node we care about.
1532 RValueReferenceType *NewIP =
1533 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001534 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001535 }
1536
John McCall90d1c2d2009-09-24 23:30:46 +00001537 RValueReferenceType *New
1538 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001539 Types.push_back(New);
1540 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001541 return QualType(New, 0);
1542}
1543
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001544/// getMemberPointerType - Return the uniqued reference to the type for a
1545/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001546QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001547 // Unique pointers, to guarantee there is only one pointer of a particular
1548 // structure.
1549 llvm::FoldingSetNodeID ID;
1550 MemberPointerType::Profile(ID, T, Cls);
1551
1552 void *InsertPos = 0;
1553 if (MemberPointerType *PT =
1554 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1555 return QualType(PT, 0);
1556
1557 // If the pointee or class type isn't canonical, this won't be a canonical
1558 // type either, so fill in the canonical type field.
1559 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001560 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001561 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1562
1563 // Get the new insert position for the node we care about.
1564 MemberPointerType *NewIP =
1565 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001566 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001567 }
John McCall90d1c2d2009-09-24 23:30:46 +00001568 MemberPointerType *New
1569 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001570 Types.push_back(New);
1571 MemberPointerTypes.InsertNode(New, InsertPos);
1572 return QualType(New, 0);
1573}
1574
Mike Stump11289f42009-09-09 15:08:12 +00001575/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001576/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001577QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001578 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001579 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001580 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001581 assert((EltTy->isDependentType() ||
1582 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001583 "Constant array of VLAs is illegal!");
1584
Chris Lattnere2df3f92009-05-13 04:12:56 +00001585 // Convert the array size into a canonical width matching the pointer size for
1586 // the target.
1587 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001588 ArySize =
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001589 ArySize.zextOrTrunc(Target.getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001590
Chris Lattner23b7eb62007-06-15 23:05:46 +00001591 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001592 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001593
Chris Lattner36f8e652007-01-27 08:31:04 +00001594 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001595 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001596 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001597 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001598
John McCall33ddac02011-01-19 10:06:00 +00001599 // If the element type isn't canonical or has qualifiers, this won't
1600 // be a canonical type either, so fill in the canonical type field.
1601 QualType Canon;
1602 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1603 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1604 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001605 ASM, IndexTypeQuals);
John McCall33ddac02011-01-19 10:06:00 +00001606 Canon = getQualifiedType(Canon, canonSplit.second);
1607
Chris Lattner36f8e652007-01-27 08:31:04 +00001608 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001609 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001610 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001611 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001612 }
Mike Stump11289f42009-09-09 15:08:12 +00001613
John McCall90d1c2d2009-09-24 23:30:46 +00001614 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001615 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001616 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001617 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001618 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001619}
1620
John McCall06549462011-01-18 08:40:38 +00001621/// getVariableArrayDecayedType - Turns the given type, which may be
1622/// variably-modified, into the corresponding type with all the known
1623/// sizes replaced with [*].
1624QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1625 // Vastly most common case.
1626 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001627
John McCall06549462011-01-18 08:40:38 +00001628 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001629
John McCall06549462011-01-18 08:40:38 +00001630 SplitQualType split = type.getSplitDesugaredType();
1631 const Type *ty = split.first;
1632 switch (ty->getTypeClass()) {
1633#define TYPE(Class, Base)
1634#define ABSTRACT_TYPE(Class, Base)
1635#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1636#include "clang/AST/TypeNodes.def"
1637 llvm_unreachable("didn't desugar past all non-canonical types?");
1638
1639 // These types should never be variably-modified.
1640 case Type::Builtin:
1641 case Type::Complex:
1642 case Type::Vector:
1643 case Type::ExtVector:
1644 case Type::DependentSizedExtVector:
1645 case Type::ObjCObject:
1646 case Type::ObjCInterface:
1647 case Type::ObjCObjectPointer:
1648 case Type::Record:
1649 case Type::Enum:
1650 case Type::UnresolvedUsing:
1651 case Type::TypeOfExpr:
1652 case Type::TypeOf:
1653 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001654 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001655 case Type::DependentName:
1656 case Type::InjectedClassName:
1657 case Type::TemplateSpecialization:
1658 case Type::DependentTemplateSpecialization:
1659 case Type::TemplateTypeParm:
1660 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001661 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001662 case Type::PackExpansion:
1663 llvm_unreachable("type should never be variably-modified");
1664
1665 // These types can be variably-modified but should never need to
1666 // further decay.
1667 case Type::FunctionNoProto:
1668 case Type::FunctionProto:
1669 case Type::BlockPointer:
1670 case Type::MemberPointer:
1671 return type;
1672
1673 // These types can be variably-modified. All these modifications
1674 // preserve structure except as noted by comments.
1675 // TODO: if we ever care about optimizing VLAs, there are no-op
1676 // optimizations available here.
1677 case Type::Pointer:
1678 result = getPointerType(getVariableArrayDecayedType(
1679 cast<PointerType>(ty)->getPointeeType()));
1680 break;
1681
1682 case Type::LValueReference: {
1683 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1684 result = getLValueReferenceType(
1685 getVariableArrayDecayedType(lv->getPointeeType()),
1686 lv->isSpelledAsLValue());
1687 break;
1688 }
1689
1690 case Type::RValueReference: {
1691 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1692 result = getRValueReferenceType(
1693 getVariableArrayDecayedType(lv->getPointeeType()));
1694 break;
1695 }
1696
1697 case Type::ConstantArray: {
1698 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1699 result = getConstantArrayType(
1700 getVariableArrayDecayedType(cat->getElementType()),
1701 cat->getSize(),
1702 cat->getSizeModifier(),
1703 cat->getIndexTypeCVRQualifiers());
1704 break;
1705 }
1706
1707 case Type::DependentSizedArray: {
1708 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1709 result = getDependentSizedArrayType(
1710 getVariableArrayDecayedType(dat->getElementType()),
1711 dat->getSizeExpr(),
1712 dat->getSizeModifier(),
1713 dat->getIndexTypeCVRQualifiers(),
1714 dat->getBracketsRange());
1715 break;
1716 }
1717
1718 // Turn incomplete types into [*] types.
1719 case Type::IncompleteArray: {
1720 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1721 result = getVariableArrayType(
1722 getVariableArrayDecayedType(iat->getElementType()),
1723 /*size*/ 0,
1724 ArrayType::Normal,
1725 iat->getIndexTypeCVRQualifiers(),
1726 SourceRange());
1727 break;
1728 }
1729
1730 // Turn VLA types into [*] types.
1731 case Type::VariableArray: {
1732 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1733 result = getVariableArrayType(
1734 getVariableArrayDecayedType(vat->getElementType()),
1735 /*size*/ 0,
1736 ArrayType::Star,
1737 vat->getIndexTypeCVRQualifiers(),
1738 vat->getBracketsRange());
1739 break;
1740 }
1741 }
1742
1743 // Apply the top-level qualifiers from the original.
1744 return getQualifiedType(result, split.second);
1745}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001746
Steve Naroffcadebd02007-08-30 18:14:25 +00001747/// getVariableArrayType - Returns a non-unique reference to the type for a
1748/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001749QualType ASTContext::getVariableArrayType(QualType EltTy,
1750 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001751 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001752 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001753 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001754 // Since we don't unique expressions, it isn't possible to unique VLA's
1755 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001756 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001757
John McCall33ddac02011-01-19 10:06:00 +00001758 // Be sure to pull qualifiers off the element type.
1759 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1760 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1761 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001762 IndexTypeQuals, Brackets);
John McCall33ddac02011-01-19 10:06:00 +00001763 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001764 }
1765
John McCall90d1c2d2009-09-24 23:30:46 +00001766 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001767 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001768
1769 VariableArrayTypes.push_back(New);
1770 Types.push_back(New);
1771 return QualType(New, 0);
1772}
1773
Douglas Gregor4619e432008-12-05 23:32:09 +00001774/// getDependentSizedArrayType - Returns a non-unique reference to
1775/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001776/// type.
John McCall33ddac02011-01-19 10:06:00 +00001777QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1778 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001779 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001780 unsigned elementTypeQuals,
1781 SourceRange brackets) const {
1782 assert((!numElements || numElements->isTypeDependent() ||
1783 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001784 "Size must be type- or value-dependent!");
1785
John McCall33ddac02011-01-19 10:06:00 +00001786 // Dependently-sized array types that do not have a specified number
1787 // of elements will have their sizes deduced from a dependent
1788 // initializer. We do no canonicalization here at all, which is okay
1789 // because they can't be used in most locations.
1790 if (!numElements) {
1791 DependentSizedArrayType *newType
1792 = new (*this, TypeAlignment)
1793 DependentSizedArrayType(*this, elementType, QualType(),
1794 numElements, ASM, elementTypeQuals,
1795 brackets);
1796 Types.push_back(newType);
1797 return QualType(newType, 0);
1798 }
1799
1800 // Otherwise, we actually build a new type every time, but we
1801 // also build a canonical type.
1802
1803 SplitQualType canonElementType = getCanonicalType(elementType).split();
1804
1805 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001806 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001807 DependentSizedArrayType::Profile(ID, *this,
1808 QualType(canonElementType.first, 0),
1809 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001810
John McCall33ddac02011-01-19 10:06:00 +00001811 // Look for an existing type with these properties.
1812 DependentSizedArrayType *canonTy =
1813 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001814
John McCall33ddac02011-01-19 10:06:00 +00001815 // If we don't have one, build one.
1816 if (!canonTy) {
1817 canonTy = new (*this, TypeAlignment)
1818 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1819 QualType(), numElements, ASM, elementTypeQuals,
1820 brackets);
1821 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1822 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001823 }
1824
John McCall33ddac02011-01-19 10:06:00 +00001825 // Apply qualifiers from the element type to the array.
1826 QualType canon = getQualifiedType(QualType(canonTy,0),
1827 canonElementType.second);
Mike Stump11289f42009-09-09 15:08:12 +00001828
John McCall33ddac02011-01-19 10:06:00 +00001829 // If we didn't need extra canonicalization for the element type,
1830 // then just use that as our result.
1831 if (QualType(canonElementType.first, 0) == elementType)
1832 return canon;
1833
1834 // Otherwise, we need to build a type which follows the spelling
1835 // of the element type.
1836 DependentSizedArrayType *sugaredType
1837 = new (*this, TypeAlignment)
1838 DependentSizedArrayType(*this, elementType, canon, numElements,
1839 ASM, elementTypeQuals, brackets);
1840 Types.push_back(sugaredType);
1841 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00001842}
1843
John McCall33ddac02011-01-19 10:06:00 +00001844QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00001845 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001846 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001847 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001848 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001849
John McCall33ddac02011-01-19 10:06:00 +00001850 void *insertPos = 0;
1851 if (IncompleteArrayType *iat =
1852 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1853 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00001854
1855 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00001856 // either, so fill in the canonical type field. We also have to pull
1857 // qualifiers off the element type.
1858 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00001859
John McCall33ddac02011-01-19 10:06:00 +00001860 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1861 SplitQualType canonSplit = getCanonicalType(elementType).split();
1862 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1863 ASM, elementTypeQuals);
1864 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanbd258282008-02-15 18:16:39 +00001865
1866 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00001867 IncompleteArrayType *existing =
1868 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1869 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001870 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001871
John McCall33ddac02011-01-19 10:06:00 +00001872 IncompleteArrayType *newType = new (*this, TypeAlignment)
1873 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001874
John McCall33ddac02011-01-19 10:06:00 +00001875 IncompleteArrayTypes.InsertNode(newType, insertPos);
1876 Types.push_back(newType);
1877 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001878}
1879
Steve Naroff91fcddb2007-07-18 18:00:27 +00001880/// getVectorType - Return the unique reference to a vector type of
1881/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001882QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001883 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00001884 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001885
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001886 // Check if we've already instantiated a vector of this type.
1887 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001888 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001889
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001890 void *InsertPos = 0;
1891 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1892 return QualType(VTP, 0);
1893
1894 // If the element type isn't canonical, this won't be a canonical type either,
1895 // so fill in the canonical type field.
1896 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001897 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001898 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001899
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001900 // Get the new insert position for the node we care about.
1901 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001902 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001903 }
John McCall90d1c2d2009-09-24 23:30:46 +00001904 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001905 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001906 VectorTypes.InsertNode(New, InsertPos);
1907 Types.push_back(New);
1908 return QualType(New, 0);
1909}
1910
Nate Begemance4d7fc2008-04-18 23:10:10 +00001911/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001912/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00001913QualType
1914ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00001915 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00001916
Steve Naroff91fcddb2007-07-18 18:00:27 +00001917 // Check if we've already instantiated a vector of this type.
1918 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001919 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001920 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001921 void *InsertPos = 0;
1922 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1923 return QualType(VTP, 0);
1924
1925 // If the element type isn't canonical, this won't be a canonical type either,
1926 // so fill in the canonical type field.
1927 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001928 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001929 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001930
Steve Naroff91fcddb2007-07-18 18:00:27 +00001931 // Get the new insert position for the node we care about.
1932 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001933 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001934 }
John McCall90d1c2d2009-09-24 23:30:46 +00001935 ExtVectorType *New = new (*this, TypeAlignment)
1936 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001937 VectorTypes.InsertNode(New, InsertPos);
1938 Types.push_back(New);
1939 return QualType(New, 0);
1940}
1941
Jay Foad39c79802011-01-12 09:06:06 +00001942QualType
1943ASTContext::getDependentSizedExtVectorType(QualType vecType,
1944 Expr *SizeExpr,
1945 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00001946 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001947 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001948 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001949
Douglas Gregor352169a2009-07-31 03:54:25 +00001950 void *InsertPos = 0;
1951 DependentSizedExtVectorType *Canon
1952 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1953 DependentSizedExtVectorType *New;
1954 if (Canon) {
1955 // We already have a canonical version of this array type; use it as
1956 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001957 New = new (*this, TypeAlignment)
1958 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1959 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001960 } else {
1961 QualType CanonVecTy = getCanonicalType(vecType);
1962 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001963 New = new (*this, TypeAlignment)
1964 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1965 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001966
1967 DependentSizedExtVectorType *CanonCheck
1968 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1969 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1970 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001971 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1972 } else {
1973 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1974 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001975 New = new (*this, TypeAlignment)
1976 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001977 }
1978 }
Mike Stump11289f42009-09-09 15:08:12 +00001979
Douglas Gregor758a8692009-06-17 21:51:59 +00001980 Types.push_back(New);
1981 return QualType(New, 0);
1982}
1983
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001984/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001985///
Jay Foad39c79802011-01-12 09:06:06 +00001986QualType
1987ASTContext::getFunctionNoProtoType(QualType ResultTy,
1988 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00001989 const CallingConv DefaultCC = Info.getCC();
1990 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1991 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001992 // Unique functions, to guarantee there is only one function of a particular
1993 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001994 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001995 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001996
Chris Lattner47955de2007-01-27 08:37:20 +00001997 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001998 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001999 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002000 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002001
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002002 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002003 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002004 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002005 Canonical =
2006 getFunctionNoProtoType(getCanonicalType(ResultTy),
2007 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002008
Chris Lattner47955de2007-01-27 08:37:20 +00002009 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002010 FunctionNoProtoType *NewIP =
2011 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002012 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002013 }
Mike Stump11289f42009-09-09 15:08:12 +00002014
Roman Divacky65b88cd2011-03-01 17:40:53 +00002015 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002016 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002017 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002018 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002019 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002020 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002021}
2022
2023/// getFunctionType - Return a normal function type with a typed argument
2024/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002025QualType
2026ASTContext::getFunctionType(QualType ResultTy,
2027 const QualType *ArgArray, unsigned NumArgs,
2028 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002029 // Unique functions, to guarantee there is only one function of a particular
2030 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002031 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002032 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002033
2034 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002035 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002036 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002037 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002038
2039 // Determine whether the type being created is already canonical or not.
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002040 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002041 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002042 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002043 isCanonical = false;
2044
Roman Divacky65b88cd2011-03-01 17:40:53 +00002045 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2046 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2047 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002048
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002049 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002050 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002051 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002052 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002053 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002054 CanonicalArgs.reserve(NumArgs);
2055 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002056 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002057
John McCalldb40c7f2010-12-14 08:05:40 +00002058 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002059 CanonicalEPI.ExceptionSpecType = EST_None;
2060 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002061 CanonicalEPI.ExtInfo
2062 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2063
Chris Lattner76a00cf2008-04-06 22:59:24 +00002064 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002065 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002066 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002067
Chris Lattnerfd4de792007-01-27 01:15:32 +00002068 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002069 FunctionProtoType *NewIP =
2070 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002071 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002072 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002073
John McCall31168b02011-06-15 23:02:42 +00002074 // FunctionProtoType objects are allocated with extra bytes after
2075 // them for three variable size arrays at the end:
2076 // - parameter types
2077 // - exception types
2078 // - consumed-arguments flags
2079 // Instead of the exception types, there could be a noexcept
2080 // expression.
John McCalldb40c7f2010-12-14 08:05:40 +00002081 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002082 NumArgs * sizeof(QualType);
2083 if (EPI.ExceptionSpecType == EST_Dynamic)
2084 Size += EPI.NumExceptions * sizeof(QualType);
2085 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002086 Size += sizeof(Expr*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002087 }
John McCall31168b02011-06-15 23:02:42 +00002088 if (EPI.ConsumedArguments)
2089 Size += NumArgs * sizeof(bool);
2090
John McCalldb40c7f2010-12-14 08:05:40 +00002091 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002092 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2093 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002094 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002095 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002096 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002097 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002098}
Chris Lattneref51c202006-11-10 07:17:23 +00002099
John McCalle78aac42010-03-10 03:28:59 +00002100#ifndef NDEBUG
2101static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2102 if (!isa<CXXRecordDecl>(D)) return false;
2103 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2104 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2105 return true;
2106 if (RD->getDescribedClassTemplate() &&
2107 !isa<ClassTemplateSpecializationDecl>(RD))
2108 return true;
2109 return false;
2110}
2111#endif
2112
2113/// getInjectedClassNameType - Return the unique reference to the
2114/// injected class name type for the specified templated declaration.
2115QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002116 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002117 assert(NeedsInjectedClassNameType(Decl));
2118 if (Decl->TypeForDecl) {
2119 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00002120 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00002121 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2122 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2123 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2124 } else {
John McCall424cec92011-01-19 06:33:43 +00002125 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002126 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002127 Decl->TypeForDecl = newType;
2128 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002129 }
2130 return QualType(Decl->TypeForDecl, 0);
2131}
2132
Douglas Gregor83a586e2008-04-13 21:07:44 +00002133/// getTypeDeclType - Return the unique reference to the type for the
2134/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002135QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002136 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002137 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002138
Richard Smithdda56e42011-04-15 14:24:37 +00002139 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002140 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002141
John McCall96f0b5f2010-03-10 06:48:02 +00002142 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2143 "Template type parameter types are always available.");
2144
John McCall81e38502010-02-16 03:57:14 +00002145 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002146 assert(!Record->getPreviousDeclaration() &&
2147 "struct/union has previous declaration");
2148 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002149 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002150 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002151 assert(!Enum->getPreviousDeclaration() &&
2152 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002153 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002154 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002155 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002156 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2157 Decl->TypeForDecl = newType;
2158 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002159 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002160 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002161
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002162 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002163}
2164
Chris Lattner32d920b2007-01-26 02:01:53 +00002165/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002166/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002167QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002168ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2169 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002170 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002171
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002172 if (Canonical.isNull())
2173 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002174 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002175 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002176 Decl->TypeForDecl = newType;
2177 Types.push_back(newType);
2178 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002179}
2180
Jay Foad39c79802011-01-12 09:06:06 +00002181QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002182 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2183
2184 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2185 if (PrevDecl->TypeForDecl)
2186 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2187
John McCall424cec92011-01-19 06:33:43 +00002188 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2189 Decl->TypeForDecl = newType;
2190 Types.push_back(newType);
2191 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002192}
2193
Jay Foad39c79802011-01-12 09:06:06 +00002194QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002195 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2196
2197 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2198 if (PrevDecl->TypeForDecl)
2199 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2200
John McCall424cec92011-01-19 06:33:43 +00002201 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2202 Decl->TypeForDecl = newType;
2203 Types.push_back(newType);
2204 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002205}
2206
John McCall81904512011-01-06 01:58:22 +00002207QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2208 QualType modifiedType,
2209 QualType equivalentType) {
2210 llvm::FoldingSetNodeID id;
2211 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2212
2213 void *insertPos = 0;
2214 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2215 if (type) return QualType(type, 0);
2216
2217 QualType canon = getCanonicalType(equivalentType);
2218 type = new (*this, TypeAlignment)
2219 AttributedType(canon, attrKind, modifiedType, equivalentType);
2220
2221 Types.push_back(type);
2222 AttributedTypes.InsertNode(type, insertPos);
2223
2224 return QualType(type, 0);
2225}
2226
2227
John McCallcebee162009-10-18 09:09:24 +00002228/// \brief Retrieve a substitution-result type.
2229QualType
2230ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002231 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002232 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002233 && "replacement types must always be canonical");
2234
2235 llvm::FoldingSetNodeID ID;
2236 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2237 void *InsertPos = 0;
2238 SubstTemplateTypeParmType *SubstParm
2239 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2240
2241 if (!SubstParm) {
2242 SubstParm = new (*this, TypeAlignment)
2243 SubstTemplateTypeParmType(Parm, Replacement);
2244 Types.push_back(SubstParm);
2245 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2246 }
2247
2248 return QualType(SubstParm, 0);
2249}
2250
Douglas Gregorada4b792011-01-14 02:55:32 +00002251/// \brief Retrieve a
2252QualType ASTContext::getSubstTemplateTypeParmPackType(
2253 const TemplateTypeParmType *Parm,
2254 const TemplateArgument &ArgPack) {
2255#ifndef NDEBUG
2256 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2257 PEnd = ArgPack.pack_end();
2258 P != PEnd; ++P) {
2259 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2260 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2261 }
2262#endif
2263
2264 llvm::FoldingSetNodeID ID;
2265 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2266 void *InsertPos = 0;
2267 if (SubstTemplateTypeParmPackType *SubstParm
2268 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2269 return QualType(SubstParm, 0);
2270
2271 QualType Canon;
2272 if (!Parm->isCanonicalUnqualified()) {
2273 Canon = getCanonicalType(QualType(Parm, 0));
2274 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2275 ArgPack);
2276 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2277 }
2278
2279 SubstTemplateTypeParmPackType *SubstParm
2280 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2281 ArgPack);
2282 Types.push_back(SubstParm);
2283 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2284 return QualType(SubstParm, 0);
2285}
2286
Douglas Gregoreff93e02009-02-05 23:33:38 +00002287/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002288/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002289/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002290QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002291 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002292 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002293 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002294 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002295 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002296 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002297 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2298
2299 if (TypeParm)
2300 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002301
Chandler Carruth08836322011-05-01 00:51:33 +00002302 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002303 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002304 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002305
2306 TemplateTypeParmType *TypeCheck
2307 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2308 assert(!TypeCheck && "Template type parameter canonical type broken");
2309 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002310 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002311 TypeParm = new (*this, TypeAlignment)
2312 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002313
2314 Types.push_back(TypeParm);
2315 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2316
2317 return QualType(TypeParm, 0);
2318}
2319
John McCalle78aac42010-03-10 03:28:59 +00002320TypeSourceInfo *
2321ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2322 SourceLocation NameLoc,
2323 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002324 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002325 assert(!Name.getAsDependentTemplateName() &&
2326 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002327 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002328
2329 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2330 TemplateSpecializationTypeLoc TL
2331 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2332 TL.setTemplateNameLoc(NameLoc);
2333 TL.setLAngleLoc(Args.getLAngleLoc());
2334 TL.setRAngleLoc(Args.getRAngleLoc());
2335 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2336 TL.setArgLocInfo(i, Args[i].getLocInfo());
2337 return DI;
2338}
2339
Mike Stump11289f42009-09-09 15:08:12 +00002340QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002341ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002342 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002343 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002344 assert(!Template.getAsDependentTemplateName() &&
2345 "No dependent template names here!");
2346
John McCall6b51f282009-11-23 01:53:49 +00002347 unsigned NumArgs = Args.size();
2348
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002349 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002350 ArgVec.reserve(NumArgs);
2351 for (unsigned i = 0; i != NumArgs; ++i)
2352 ArgVec.push_back(Args[i].getArgument());
2353
John McCall2408e322010-04-27 00:57:59 +00002354 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002355 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002356}
2357
2358QualType
2359ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002360 const TemplateArgument *Args,
2361 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002362 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002363 assert(!Template.getAsDependentTemplateName() &&
2364 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002365 // Look through qualified template names.
2366 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2367 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002368
Richard Smith3f1b5d02011-05-05 21:57:07 +00002369 bool isTypeAlias =
2370 Template.getAsTemplateDecl() &&
2371 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2372
2373 QualType CanonType;
2374 if (!Underlying.isNull())
2375 CanonType = getCanonicalType(Underlying);
2376 else {
2377 assert(!isTypeAlias &&
2378 "Underlying type for template alias must be computed by caller");
2379 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2380 NumArgs);
2381 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002382
Douglas Gregora8e02e72009-07-28 23:00:59 +00002383 // Allocate the (non-canonical) template specialization type, but don't
2384 // try to unique it: these types typically have location information that
2385 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002386 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2387 sizeof(TemplateArgument) * NumArgs +
2388 (isTypeAlias ? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002389 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002390 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00002391 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00002392 Args, NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002393 CanonType,
2394 isTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002395
Douglas Gregor8bf42052009-02-09 18:46:07 +00002396 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002397 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002398}
2399
Mike Stump11289f42009-09-09 15:08:12 +00002400QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002401ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2402 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002403 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002404 assert(!Template.getAsDependentTemplateName() &&
2405 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002406 assert((!Template.getAsTemplateDecl() ||
2407 !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2408 "Underlying type for template alias must be computed by caller");
2409
Douglas Gregore29139c2011-03-03 17:04:51 +00002410 // Look through qualified template names.
2411 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2412 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002413
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002414 // Build the canonical template specialization type.
2415 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002416 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002417 CanonArgs.reserve(NumArgs);
2418 for (unsigned I = 0; I != NumArgs; ++I)
2419 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2420
2421 // Determine whether this canonical template specialization type already
2422 // exists.
2423 llvm::FoldingSetNodeID ID;
2424 TemplateSpecializationType::Profile(ID, CanonTemplate,
2425 CanonArgs.data(), NumArgs, *this);
2426
2427 void *InsertPos = 0;
2428 TemplateSpecializationType *Spec
2429 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2430
2431 if (!Spec) {
2432 // Allocate a new canonical template specialization type.
2433 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2434 sizeof(TemplateArgument) * NumArgs),
2435 TypeAlignment);
2436 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2437 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002438 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002439 Types.push_back(Spec);
2440 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2441 }
2442
2443 assert(Spec->isDependentType() &&
2444 "Non-dependent template-id type must have a canonical type");
2445 return QualType(Spec, 0);
2446}
2447
2448QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002449ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2450 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002451 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002452 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002453 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002454
2455 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002456 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002457 if (T)
2458 return QualType(T, 0);
2459
Douglas Gregorc42075a2010-02-04 18:10:26 +00002460 QualType Canon = NamedType;
2461 if (!Canon.isCanonical()) {
2462 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002463 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2464 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002465 (void)CheckT;
2466 }
2467
Abramo Bagnara6150c882010-05-11 21:36:43 +00002468 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002469 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002470 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002471 return QualType(T, 0);
2472}
2473
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002474QualType
Jay Foad39c79802011-01-12 09:06:06 +00002475ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002476 llvm::FoldingSetNodeID ID;
2477 ParenType::Profile(ID, InnerType);
2478
2479 void *InsertPos = 0;
2480 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2481 if (T)
2482 return QualType(T, 0);
2483
2484 QualType Canon = InnerType;
2485 if (!Canon.isCanonical()) {
2486 Canon = getCanonicalType(InnerType);
2487 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2488 assert(!CheckT && "Paren canonical type broken");
2489 (void)CheckT;
2490 }
2491
2492 T = new (*this) ParenType(InnerType, Canon);
2493 Types.push_back(T);
2494 ParenTypes.InsertNode(T, InsertPos);
2495 return QualType(T, 0);
2496}
2497
Douglas Gregor02085352010-03-31 20:19:30 +00002498QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2499 NestedNameSpecifier *NNS,
2500 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002501 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002502 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2503
2504 if (Canon.isNull()) {
2505 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002506 ElaboratedTypeKeyword CanonKeyword = Keyword;
2507 if (Keyword == ETK_None)
2508 CanonKeyword = ETK_Typename;
2509
2510 if (CanonNNS != NNS || CanonKeyword != Keyword)
2511 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002512 }
2513
2514 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002515 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002516
2517 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002518 DependentNameType *T
2519 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002520 if (T)
2521 return QualType(T, 0);
2522
Douglas Gregor02085352010-03-31 20:19:30 +00002523 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002524 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002525 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002526 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002527}
2528
Mike Stump11289f42009-09-09 15:08:12 +00002529QualType
John McCallc392f372010-06-11 00:33:02 +00002530ASTContext::getDependentTemplateSpecializationType(
2531 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002532 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002533 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002534 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002535 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002536 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002537 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2538 ArgCopy.push_back(Args[I].getArgument());
2539 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2540 ArgCopy.size(),
2541 ArgCopy.data());
2542}
2543
2544QualType
2545ASTContext::getDependentTemplateSpecializationType(
2546 ElaboratedTypeKeyword Keyword,
2547 NestedNameSpecifier *NNS,
2548 const IdentifierInfo *Name,
2549 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002550 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002551 assert((!NNS || NNS->isDependent()) &&
2552 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002553
Douglas Gregorc42075a2010-02-04 18:10:26 +00002554 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002555 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2556 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002557
2558 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002559 DependentTemplateSpecializationType *T
2560 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002561 if (T)
2562 return QualType(T, 0);
2563
John McCallc392f372010-06-11 00:33:02 +00002564 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002565
John McCallc392f372010-06-11 00:33:02 +00002566 ElaboratedTypeKeyword CanonKeyword = Keyword;
2567 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2568
2569 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002570 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002571 for (unsigned I = 0; I != NumArgs; ++I) {
2572 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2573 if (!CanonArgs[I].structurallyEquals(Args[I]))
2574 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002575 }
2576
John McCallc392f372010-06-11 00:33:02 +00002577 QualType Canon;
2578 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2579 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2580 Name, NumArgs,
2581 CanonArgs.data());
2582
2583 // Find the insert position again.
2584 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2585 }
2586
2587 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2588 sizeof(TemplateArgument) * NumArgs),
2589 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002590 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002591 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002592 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002593 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002594 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002595}
2596
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002597QualType ASTContext::getPackExpansionType(QualType Pattern,
2598 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002599 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002600 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002601
2602 assert(Pattern->containsUnexpandedParameterPack() &&
2603 "Pack expansions must expand one or more parameter packs");
2604 void *InsertPos = 0;
2605 PackExpansionType *T
2606 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2607 if (T)
2608 return QualType(T, 0);
2609
2610 QualType Canon;
2611 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002612 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002613
2614 // Find the insert position again.
2615 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2616 }
2617
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002618 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002619 Types.push_back(T);
2620 PackExpansionTypes.InsertNode(T, InsertPos);
2621 return QualType(T, 0);
2622}
2623
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002624/// CmpProtocolNames - Comparison predicate for sorting protocols
2625/// alphabetically.
2626static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2627 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002628 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002629}
2630
John McCall8b07ec22010-05-15 11:32:37 +00002631static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002632 unsigned NumProtocols) {
2633 if (NumProtocols == 0) return true;
2634
2635 for (unsigned i = 1; i != NumProtocols; ++i)
2636 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2637 return false;
2638 return true;
2639}
2640
2641static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002642 unsigned &NumProtocols) {
2643 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002644
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002645 // Sort protocols, keyed by name.
2646 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2647
2648 // Remove duplicates.
2649 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2650 NumProtocols = ProtocolsEnd-Protocols;
2651}
2652
John McCall8b07ec22010-05-15 11:32:37 +00002653QualType ASTContext::getObjCObjectType(QualType BaseType,
2654 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002655 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002656 // If the base type is an interface and there aren't any protocols
2657 // to add, then the interface type will do just fine.
2658 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2659 return BaseType;
2660
2661 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002662 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002663 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002664 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002665 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2666 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002667
John McCall8b07ec22010-05-15 11:32:37 +00002668 // Build the canonical type, which has the canonical base type and
2669 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002670 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002671 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2672 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2673 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002674 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002675 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002676 unsigned UniqueCount = NumProtocols;
2677
John McCallfc93cf92009-10-22 22:37:11 +00002678 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002679 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2680 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002681 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002682 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2683 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002684 }
2685
2686 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002687 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2688 }
2689
2690 unsigned Size = sizeof(ObjCObjectTypeImpl);
2691 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2692 void *Mem = Allocate(Size, TypeAlignment);
2693 ObjCObjectTypeImpl *T =
2694 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2695
2696 Types.push_back(T);
2697 ObjCObjectTypes.InsertNode(T, InsertPos);
2698 return QualType(T, 0);
2699}
2700
2701/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2702/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002703QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002704 llvm::FoldingSetNodeID ID;
2705 ObjCObjectPointerType::Profile(ID, ObjectT);
2706
2707 void *InsertPos = 0;
2708 if (ObjCObjectPointerType *QT =
2709 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2710 return QualType(QT, 0);
2711
2712 // Find the canonical object type.
2713 QualType Canonical;
2714 if (!ObjectT.isCanonical()) {
2715 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2716
2717 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002718 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2719 }
2720
Douglas Gregorf85bee62010-02-08 22:59:26 +00002721 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002722 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2723 ObjCObjectPointerType *QType =
2724 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002725
Steve Narofffb4330f2009-06-17 22:40:22 +00002726 Types.push_back(QType);
2727 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002728 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002729}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002730
Douglas Gregor1c283312010-08-11 12:19:30 +00002731/// getObjCInterfaceType - Return the unique reference to the type for the
2732/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad39c79802011-01-12 09:06:06 +00002733QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002734 if (Decl->TypeForDecl)
2735 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002736
Douglas Gregor1c283312010-08-11 12:19:30 +00002737 // FIXME: redeclarations?
2738 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2739 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2740 Decl->TypeForDecl = T;
2741 Types.push_back(T);
2742 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002743}
2744
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002745/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2746/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002747/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002748/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002749/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002750QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002751 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002752 if (tofExpr->isTypeDependent()) {
2753 llvm::FoldingSetNodeID ID;
2754 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002755
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002756 void *InsertPos = 0;
2757 DependentTypeOfExprType *Canon
2758 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2759 if (Canon) {
2760 // We already have a "canonical" version of an identical, dependent
2761 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002762 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002763 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002764 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002765 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002766 Canon
2767 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002768 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2769 toe = Canon;
2770 }
2771 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002772 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002773 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002774 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002775 Types.push_back(toe);
2776 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002777}
2778
Steve Naroffa773cd52007-08-01 18:02:17 +00002779/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2780/// TypeOfType AST's. The only motivation to unique these nodes would be
2781/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002782/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002783/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002784QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002785 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002786 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002787 Types.push_back(tot);
2788 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002789}
2790
Anders Carlssonad6bd352009-06-24 21:24:56 +00002791/// getDecltypeForExpr - Given an expr, will return the decltype for that
2792/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad39c79802011-01-12 09:06:06 +00002793static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002794 if (e->isTypeDependent())
2795 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002796
Anders Carlssonad6bd352009-06-24 21:24:56 +00002797 // If e is an id expression or a class member access, decltype(e) is defined
2798 // as the type of the entity named by e.
2799 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2800 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2801 return VD->getType();
2802 }
2803 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2804 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2805 return FD->getType();
2806 }
2807 // If e is a function call or an invocation of an overloaded operator,
2808 // (parentheses around e are ignored), decltype(e) is defined as the
2809 // return type of that function.
2810 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2811 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002812
Anders Carlssonad6bd352009-06-24 21:24:56 +00002813 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002814
2815 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002816 // defined as T&, otherwise decltype(e) is defined as T.
John McCall086a4642010-11-24 05:12:34 +00002817 if (e->isLValue())
Anders Carlssonad6bd352009-06-24 21:24:56 +00002818 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002819
Anders Carlssonad6bd352009-06-24 21:24:56 +00002820 return T;
2821}
2822
Anders Carlsson81df7b82009-06-24 19:06:50 +00002823/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2824/// DecltypeType AST's. The only motivation to unique these nodes would be
2825/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002826/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002827/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002828QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002829 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00002830
2831 // C++0x [temp.type]p2:
2832 // If an expression e involves a template parameter, decltype(e) denotes a
2833 // unique dependent type. Two such decltype-specifiers refer to the same
2834 // type only if their expressions are equivalent (14.5.6.1).
2835 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002836 llvm::FoldingSetNodeID ID;
2837 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002838
Douglas Gregora21f6c32009-07-30 23:36:40 +00002839 void *InsertPos = 0;
2840 DependentDecltypeType *Canon
2841 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2842 if (Canon) {
2843 // We already have a "canonical" version of an equivalent, dependent
2844 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002845 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002846 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002847 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002848 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002849 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002850 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2851 dt = Canon;
2852 }
2853 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002854 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002855 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002856 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002857 Types.push_back(dt);
2858 return QualType(dt, 0);
2859}
2860
Alexis Hunte852b102011-05-24 22:41:36 +00002861/// getUnaryTransformationType - We don't unique these, since the memory
2862/// savings are minimal and these are rare.
2863QualType ASTContext::getUnaryTransformType(QualType BaseType,
2864 QualType UnderlyingType,
2865 UnaryTransformType::UTTKind Kind)
2866 const {
2867 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00002868 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2869 Kind,
2870 UnderlyingType->isDependentType() ?
2871 QualType() : UnderlyingType);
Alexis Hunte852b102011-05-24 22:41:36 +00002872 Types.push_back(Ty);
2873 return QualType(Ty, 0);
2874}
2875
Richard Smithb2bc2e62011-02-21 20:05:19 +00002876/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00002877QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00002878 void *InsertPos = 0;
2879 if (!DeducedType.isNull()) {
2880 // Look in the folding set for an existing type.
2881 llvm::FoldingSetNodeID ID;
2882 AutoType::Profile(ID, DeducedType);
2883 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2884 return QualType(AT, 0);
2885 }
2886
2887 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2888 Types.push_back(AT);
2889 if (InsertPos)
2890 AutoTypes.InsertNode(AT, InsertPos);
2891 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00002892}
2893
Richard Smith02e85f32011-04-14 22:09:26 +00002894/// getAutoDeductType - Get type pattern for deducing against 'auto'.
2895QualType ASTContext::getAutoDeductType() const {
2896 if (AutoDeductTy.isNull())
2897 AutoDeductTy = getAutoType(QualType());
2898 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
2899 return AutoDeductTy;
2900}
2901
2902/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
2903QualType ASTContext::getAutoRRefDeductType() const {
2904 if (AutoRRefDeductTy.isNull())
2905 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
2906 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
2907 return AutoRRefDeductTy;
2908}
2909
Chris Lattnerfb072462007-01-23 05:45:31 +00002910/// getTagDeclType - Return the unique reference to the type for the
2911/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00002912QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002913 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002914 // FIXME: What is the design on getTagDeclType when it requires casting
2915 // away const? mutable?
2916 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002917}
2918
Mike Stump11289f42009-09-09 15:08:12 +00002919/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2920/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2921/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002922CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002923 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002924}
Chris Lattnerfb072462007-01-23 05:45:31 +00002925
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002926/// getSignedWCharType - Return the type of "signed wchar_t".
2927/// Used when in C++, as a GCC extension.
2928QualType ASTContext::getSignedWCharType() const {
2929 // FIXME: derive from "Target" ?
2930 return WCharTy;
2931}
2932
2933/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2934/// Used when in C++, as a GCC extension.
2935QualType ASTContext::getUnsignedWCharType() const {
2936 // FIXME: derive from "Target" ?
2937 return UnsignedIntTy;
2938}
2939
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002940/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2941/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2942QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002943 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002944}
2945
Chris Lattnera21ad802008-04-02 05:18:44 +00002946//===----------------------------------------------------------------------===//
2947// Type Operators
2948//===----------------------------------------------------------------------===//
2949
Jay Foad39c79802011-01-12 09:06:06 +00002950CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00002951 // Push qualifiers into arrays, and then discard any remaining
2952 // qualifiers.
2953 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002954 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00002955 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00002956 QualType Result;
2957 if (isa<ArrayType>(Ty)) {
2958 Result = getArrayDecayedType(QualType(Ty,0));
2959 } else if (isa<FunctionType>(Ty)) {
2960 Result = getPointerType(QualType(Ty, 0));
2961 } else {
2962 Result = QualType(Ty, 0);
2963 }
2964
2965 return CanQualType::CreateUnsafe(Result);
2966}
2967
John McCall6c9dd522011-01-18 07:41:22 +00002968QualType ASTContext::getUnqualifiedArrayType(QualType type,
2969 Qualifiers &quals) {
2970 SplitQualType splitType = type.getSplitUnqualifiedType();
2971
2972 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2973 // the unqualified desugared type and then drops it on the floor.
2974 // We then have to strip that sugar back off with
2975 // getUnqualifiedDesugaredType(), which is silly.
2976 const ArrayType *AT =
2977 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2978
2979 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002980 if (!AT) {
John McCall6c9dd522011-01-18 07:41:22 +00002981 quals = splitType.second;
2982 return QualType(splitType.first, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002983 }
2984
John McCall6c9dd522011-01-18 07:41:22 +00002985 // Otherwise, recurse on the array's element type.
2986 QualType elementType = AT->getElementType();
2987 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2988
2989 // If that didn't change the element type, AT has no qualifiers, so we
2990 // can just use the results in splitType.
2991 if (elementType == unqualElementType) {
2992 assert(quals.empty()); // from the recursive call
2993 quals = splitType.second;
2994 return QualType(splitType.first, 0);
2995 }
2996
2997 // Otherwise, add in the qualifiers from the outermost type, then
2998 // build the type back up.
2999 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003000
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003001 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003002 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003003 CAT->getSizeModifier(), 0);
3004 }
3005
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003006 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003007 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003008 }
3009
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003010 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003011 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003012 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003013 VAT->getSizeModifier(),
3014 VAT->getIndexTypeCVRQualifiers(),
3015 VAT->getBracketsRange());
3016 }
3017
3018 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003019 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003020 DSAT->getSizeModifier(), 0,
3021 SourceRange());
3022}
3023
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003024/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3025/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3026/// they point to and return true. If T1 and T2 aren't pointer types
3027/// or pointer-to-member types, or if they are not similar at this
3028/// level, returns false and leaves T1 and T2 unchanged. Top-level
3029/// qualifiers on T1 and T2 are ignored. This function will typically
3030/// be called in a loop that successively "unwraps" pointer and
3031/// pointer-to-member types to compare them at each level.
3032bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3033 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3034 *T2PtrType = T2->getAs<PointerType>();
3035 if (T1PtrType && T2PtrType) {
3036 T1 = T1PtrType->getPointeeType();
3037 T2 = T2PtrType->getPointeeType();
3038 return true;
3039 }
3040
3041 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3042 *T2MPType = T2->getAs<MemberPointerType>();
3043 if (T1MPType && T2MPType &&
3044 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3045 QualType(T2MPType->getClass(), 0))) {
3046 T1 = T1MPType->getPointeeType();
3047 T2 = T2MPType->getPointeeType();
3048 return true;
3049 }
3050
3051 if (getLangOptions().ObjC1) {
3052 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3053 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3054 if (T1OPType && T2OPType) {
3055 T1 = T1OPType->getPointeeType();
3056 T2 = T2OPType->getPointeeType();
3057 return true;
3058 }
3059 }
3060
3061 // FIXME: Block pointers, too?
3062
3063 return false;
3064}
3065
Jay Foad39c79802011-01-12 09:06:06 +00003066DeclarationNameInfo
3067ASTContext::getNameForTemplate(TemplateName Name,
3068 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003069 switch (Name.getKind()) {
3070 case TemplateName::QualifiedTemplate:
3071 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003072 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003073 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3074 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003075
John McCalld9dfe3a2011-06-30 08:33:18 +00003076 case TemplateName::OverloadedTemplate: {
3077 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3078 // DNInfo work in progress: CHECKME: what about DNLoc?
3079 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3080 }
3081
3082 case TemplateName::DependentTemplate: {
3083 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003084 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003085 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003086 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3087 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003088 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003089 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3090 // DNInfo work in progress: FIXME: source locations?
3091 DeclarationNameLoc DNLoc;
3092 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3093 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3094 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003095 }
3096 }
3097
John McCalld9dfe3a2011-06-30 08:33:18 +00003098 case TemplateName::SubstTemplateTemplateParm: {
3099 SubstTemplateTemplateParmStorage *subst
3100 = Name.getAsSubstTemplateTemplateParm();
3101 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3102 NameLoc);
3103 }
3104
3105 case TemplateName::SubstTemplateTemplateParmPack: {
3106 SubstTemplateTemplateParmPackStorage *subst
3107 = Name.getAsSubstTemplateTemplateParmPack();
3108 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3109 NameLoc);
3110 }
3111 }
3112
3113 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003114}
3115
Jay Foad39c79802011-01-12 09:06:06 +00003116TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003117 switch (Name.getKind()) {
3118 case TemplateName::QualifiedTemplate:
3119 case TemplateName::Template: {
3120 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003121 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003122 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003123 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3124
3125 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003126 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003127 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003128
John McCalld9dfe3a2011-06-30 08:33:18 +00003129 case TemplateName::OverloadedTemplate:
3130 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003131
John McCalld9dfe3a2011-06-30 08:33:18 +00003132 case TemplateName::DependentTemplate: {
3133 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3134 assert(DTN && "Non-dependent template names must refer to template decls.");
3135 return DTN->CanonicalTemplateName;
3136 }
3137
3138 case TemplateName::SubstTemplateTemplateParm: {
3139 SubstTemplateTemplateParmStorage *subst
3140 = Name.getAsSubstTemplateTemplateParm();
3141 return getCanonicalTemplateName(subst->getReplacement());
3142 }
3143
3144 case TemplateName::SubstTemplateTemplateParmPack: {
3145 SubstTemplateTemplateParmPackStorage *subst
3146 = Name.getAsSubstTemplateTemplateParmPack();
3147 TemplateTemplateParmDecl *canonParameter
3148 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3149 TemplateArgument canonArgPack
3150 = getCanonicalTemplateArgument(subst->getArgumentPack());
3151 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3152 }
3153 }
3154
3155 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003156}
3157
Douglas Gregoradee3e32009-11-11 23:06:43 +00003158bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3159 X = getCanonicalTemplateName(X);
3160 Y = getCanonicalTemplateName(Y);
3161 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3162}
3163
Mike Stump11289f42009-09-09 15:08:12 +00003164TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003165ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003166 switch (Arg.getKind()) {
3167 case TemplateArgument::Null:
3168 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003169
Douglas Gregora8e02e72009-07-28 23:00:59 +00003170 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003171 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003172
Douglas Gregora8e02e72009-07-28 23:00:59 +00003173 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00003174 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003175
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003176 case TemplateArgument::Template:
3177 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003178
3179 case TemplateArgument::TemplateExpansion:
3180 return TemplateArgument(getCanonicalTemplateName(
3181 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003182 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003183
Douglas Gregora8e02e72009-07-28 23:00:59 +00003184 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00003185 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003186 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003187
Douglas Gregora8e02e72009-07-28 23:00:59 +00003188 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003189 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003190
Douglas Gregora8e02e72009-07-28 23:00:59 +00003191 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003192 if (Arg.pack_size() == 0)
3193 return Arg;
3194
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003195 TemplateArgument *CanonArgs
3196 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003197 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003198 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003199 AEnd = Arg.pack_end();
3200 A != AEnd; (void)++A, ++Idx)
3201 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003202
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003203 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003204 }
3205 }
3206
3207 // Silence GCC warning
3208 assert(false && "Unhandled template argument kind");
3209 return TemplateArgument();
3210}
3211
Douglas Gregor333489b2009-03-27 23:10:48 +00003212NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003213ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003214 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003215 return 0;
3216
3217 switch (NNS->getKind()) {
3218 case NestedNameSpecifier::Identifier:
3219 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003220 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003221 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3222 NNS->getAsIdentifier());
3223
3224 case NestedNameSpecifier::Namespace:
3225 // A namespace is canonical; build a nested-name-specifier with
3226 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003227 return NestedNameSpecifier::Create(*this, 0,
3228 NNS->getAsNamespace()->getOriginalNamespace());
3229
3230 case NestedNameSpecifier::NamespaceAlias:
3231 // A namespace is canonical; build a nested-name-specifier with
3232 // this namespace and no prefix.
3233 return NestedNameSpecifier::Create(*this, 0,
3234 NNS->getAsNamespaceAlias()->getNamespace()
3235 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003236
3237 case NestedNameSpecifier::TypeSpec:
3238 case NestedNameSpecifier::TypeSpecWithTemplate: {
3239 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003240
3241 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3242 // break it apart into its prefix and identifier, then reconsititute those
3243 // as the canonical nested-name-specifier. This is required to canonicalize
3244 // a dependent nested-name-specifier involving typedefs of dependent-name
3245 // types, e.g.,
3246 // typedef typename T::type T1;
3247 // typedef typename T1::type T2;
3248 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3249 NestedNameSpecifier *Prefix
3250 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3251 return NestedNameSpecifier::Create(*this, Prefix,
3252 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3253 }
3254
Douglas Gregorcc10cbf2010-11-04 00:14:23 +00003255 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor3ade5702010-11-04 00:09:33 +00003256 if (const DependentTemplateSpecializationType *DTST
3257 = T->getAs<DependentTemplateSpecializationType>()) {
3258 NestedNameSpecifier *Prefix
3259 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregor6e068012011-02-28 00:04:36 +00003260
3261 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3262 Prefix, DTST->getIdentifier(),
3263 DTST->getNumArgs(),
3264 DTST->getArgs());
Douglas Gregor3ade5702010-11-04 00:09:33 +00003265 T = getCanonicalType(T);
3266 }
3267
John McCall33ddac02011-01-19 10:06:00 +00003268 return NestedNameSpecifier::Create(*this, 0, false,
3269 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003270 }
3271
3272 case NestedNameSpecifier::Global:
3273 // The global specifier is canonical and unique.
3274 return NNS;
3275 }
3276
3277 // Required to silence a GCC warning
3278 return 0;
3279}
3280
Chris Lattner7adf0762008-08-04 07:31:14 +00003281
Jay Foad39c79802011-01-12 09:06:06 +00003282const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003283 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003284 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003285 // Handle the common positive case fast.
3286 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3287 return AT;
3288 }
Mike Stump11289f42009-09-09 15:08:12 +00003289
John McCall8ccfcb52009-09-24 19:53:00 +00003290 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003291 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003292 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003293
John McCall8ccfcb52009-09-24 19:53:00 +00003294 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003295 // implements C99 6.7.3p8: "If the specification of an array type includes
3296 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003297
Chris Lattner7adf0762008-08-04 07:31:14 +00003298 // If we get here, we either have type qualifiers on the type, or we have
3299 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003300 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003301
John McCall33ddac02011-01-19 10:06:00 +00003302 SplitQualType split = T.getSplitDesugaredType();
3303 Qualifiers qs = split.second;
Mike Stump11289f42009-09-09 15:08:12 +00003304
Chris Lattner7adf0762008-08-04 07:31:14 +00003305 // If we have a simple case, just return now.
John McCall33ddac02011-01-19 10:06:00 +00003306 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3307 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003308 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003309
Chris Lattner7adf0762008-08-04 07:31:14 +00003310 // Otherwise, we have an array and we have qualifiers on it. Push the
3311 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003312 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003313
Chris Lattner7adf0762008-08-04 07:31:14 +00003314 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3315 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3316 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003317 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003318 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3319 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3320 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003321 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003322
Mike Stump11289f42009-09-09 15:08:12 +00003323 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003324 = dyn_cast<DependentSizedArrayType>(ATy))
3325 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003326 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003327 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003328 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003329 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003330 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003331
Chris Lattner7adf0762008-08-04 07:31:14 +00003332 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003333 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003334 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003335 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003336 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003337 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003338}
3339
Douglas Gregor84280642011-07-12 04:42:08 +00003340QualType ASTContext::getAdjustedParameterType(QualType T) {
3341 // C99 6.7.5.3p7:
3342 // A declaration of a parameter as "array of type" shall be
3343 // adjusted to "qualified pointer to type", where the type
3344 // qualifiers (if any) are those specified within the [ and ] of
3345 // the array type derivation.
3346 if (T->isArrayType())
3347 return getArrayDecayedType(T);
3348
3349 // C99 6.7.5.3p8:
3350 // A declaration of a parameter as "function returning type"
3351 // shall be adjusted to "pointer to function returning type", as
3352 // in 6.3.2.1.
3353 if (T->isFunctionType())
3354 return getPointerType(T);
3355
3356 return T;
3357}
3358
3359QualType ASTContext::getSignatureParameterType(QualType T) {
3360 T = getVariableArrayDecayedType(T);
3361 T = getAdjustedParameterType(T);
3362 return T.getUnqualifiedType();
3363}
3364
Chris Lattnera21ad802008-04-02 05:18:44 +00003365/// getArrayDecayedType - Return the properly qualified result of decaying the
3366/// specified array type to a pointer. This operation is non-trivial when
3367/// handling typedefs etc. The canonical type of "T" must be an array type,
3368/// this returns a pointer to a properly qualified element of the array.
3369///
3370/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003371QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003372 // Get the element type with 'getAsArrayType' so that we don't lose any
3373 // typedefs in the element type of the array. This also handles propagation
3374 // of type qualifiers from the array type into the element type if present
3375 // (C99 6.7.3p8).
3376 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3377 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003378
Chris Lattner7adf0762008-08-04 07:31:14 +00003379 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003380
3381 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003382 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003383}
3384
John McCall33ddac02011-01-19 10:06:00 +00003385QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3386 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003387}
3388
John McCall33ddac02011-01-19 10:06:00 +00003389QualType ASTContext::getBaseElementType(QualType type) const {
3390 Qualifiers qs;
3391 while (true) {
3392 SplitQualType split = type.getSplitDesugaredType();
3393 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3394 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003395
John McCall33ddac02011-01-19 10:06:00 +00003396 type = array->getElementType();
3397 qs.addConsistentQualifiers(split.second);
3398 }
Mike Stump11289f42009-09-09 15:08:12 +00003399
John McCall33ddac02011-01-19 10:06:00 +00003400 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003401}
3402
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003403/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003404uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003405ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3406 uint64_t ElementCount = 1;
3407 do {
3408 ElementCount *= CA->getSize().getZExtValue();
3409 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3410 } while (CA);
3411 return ElementCount;
3412}
3413
Steve Naroff0af91202007-04-27 21:51:21 +00003414/// getFloatingRank - Return a relative rank for floating point types.
3415/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003416static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003417 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003418 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003419
John McCall9dd450b2009-09-21 23:43:11 +00003420 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3421 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003422 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00003423 case BuiltinType::Float: return FloatRank;
3424 case BuiltinType::Double: return DoubleRank;
3425 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003426 }
3427}
3428
Mike Stump11289f42009-09-09 15:08:12 +00003429/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3430/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003431/// 'typeDomain' is a real floating point or complex type.
3432/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003433QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3434 QualType Domain) const {
3435 FloatingRank EltRank = getFloatingRank(Size);
3436 if (Domain->isComplexType()) {
3437 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00003438 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00003439 case FloatRank: return FloatComplexTy;
3440 case DoubleRank: return DoubleComplexTy;
3441 case LongDoubleRank: return LongDoubleComplexTy;
3442 }
Steve Naroff0af91202007-04-27 21:51:21 +00003443 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003444
3445 assert(Domain->isRealFloatingType() && "Unknown domain!");
3446 switch (EltRank) {
3447 default: assert(0 && "getFloatingRank(): illegal value for rank");
3448 case FloatRank: return FloatTy;
3449 case DoubleRank: return DoubleTy;
3450 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003451 }
Steve Naroffe4718892007-04-27 18:30:00 +00003452}
3453
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003454/// getFloatingTypeOrder - Compare the rank of the two specified floating
3455/// point types, ignoring the domain of the type (i.e. 'double' ==
3456/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003457/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003458int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003459 FloatingRank LHSR = getFloatingRank(LHS);
3460 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003461
Chris Lattnerb90739d2008-04-06 23:38:49 +00003462 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003463 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003464 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003465 return 1;
3466 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003467}
3468
Chris Lattner76a00cf2008-04-06 22:59:24 +00003469/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3470/// routine will assert if passed a built-in type that isn't an integer or enum,
3471/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003472unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003473 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCall424cec92011-01-19 06:33:43 +00003474 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00003475 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00003476
Chris Lattnerad3467e2010-12-25 23:25:43 +00003477 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3478 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmanc131d3b2009-07-05 23:44:27 +00003479 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3480
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003481 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3482 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3483
3484 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3485 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3486
Chris Lattner76a00cf2008-04-06 22:59:24 +00003487 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003488 default: assert(0 && "getIntegerRank(): not a built-in integer");
3489 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003490 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003491 case BuiltinType::Char_S:
3492 case BuiltinType::Char_U:
3493 case BuiltinType::SChar:
3494 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003495 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003496 case BuiltinType::Short:
3497 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003498 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003499 case BuiltinType::Int:
3500 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003501 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003502 case BuiltinType::Long:
3503 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003504 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003505 case BuiltinType::LongLong:
3506 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003507 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003508 case BuiltinType::Int128:
3509 case BuiltinType::UInt128:
3510 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003511 }
3512}
3513
Eli Friedman629ffb92009-08-20 04:21:42 +00003514/// \brief Whether this is a promotable bitfield reference according
3515/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3516///
3517/// \returns the type this bit-field will promote to, or NULL if no
3518/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003519QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003520 if (E->isTypeDependent() || E->isValueDependent())
3521 return QualType();
3522
Eli Friedman629ffb92009-08-20 04:21:42 +00003523 FieldDecl *Field = E->getBitField();
3524 if (!Field)
3525 return QualType();
3526
3527 QualType FT = Field->getType();
3528
3529 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3530 uint64_t BitWidth = BitWidthAP.getZExtValue();
3531 uint64_t IntSize = getTypeSize(IntTy);
3532 // GCC extension compatibility: if the bit-field size is less than or equal
3533 // to the size of int, it gets promoted no matter what its type is.
3534 // For instance, unsigned long bf : 4 gets promoted to signed int.
3535 if (BitWidth < IntSize)
3536 return IntTy;
3537
3538 if (BitWidth == IntSize)
3539 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3540
3541 // Types bigger than int are not subject to promotions, and therefore act
3542 // like the base type.
3543 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3544 // is ridiculous.
3545 return QualType();
3546}
3547
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003548/// getPromotedIntegerType - Returns the type that Promotable will
3549/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3550/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003551QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003552 assert(!Promotable.isNull());
3553 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003554 if (const EnumType *ET = Promotable->getAs<EnumType>())
3555 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003556 if (Promotable->isSignedIntegerType())
3557 return IntTy;
3558 uint64_t PromotableSize = getTypeSize(Promotable);
3559 uint64_t IntSize = getTypeSize(IntTy);
3560 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3561 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3562}
3563
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003564/// \brief Recurses in pointer/array types until it finds an objc retainable
3565/// type and returns its ownership.
3566Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3567 while (!T.isNull()) {
3568 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3569 return T.getObjCLifetime();
3570 if (T->isArrayType())
3571 T = getBaseElementType(T);
3572 else if (const PointerType *PT = T->getAs<PointerType>())
3573 T = PT->getPointeeType();
3574 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003575 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003576 else
3577 break;
3578 }
3579
3580 return Qualifiers::OCL_None;
3581}
3582
Mike Stump11289f42009-09-09 15:08:12 +00003583/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003584/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003585/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003586int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003587 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3588 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003589 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003590
Chris Lattner76a00cf2008-04-06 22:59:24 +00003591 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3592 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003593
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003594 unsigned LHSRank = getIntegerRank(LHSC);
3595 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003596
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003597 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3598 if (LHSRank == RHSRank) return 0;
3599 return LHSRank > RHSRank ? 1 : -1;
3600 }
Mike Stump11289f42009-09-09 15:08:12 +00003601
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003602 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3603 if (LHSUnsigned) {
3604 // If the unsigned [LHS] type is larger, return it.
3605 if (LHSRank >= RHSRank)
3606 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003607
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003608 // If the signed type can represent all values of the unsigned type, it
3609 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003610 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003611 return -1;
3612 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003613
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003614 // If the unsigned [RHS] type is larger, return it.
3615 if (RHSRank >= LHSRank)
3616 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003617
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003618 // If the signed type can represent all values of the unsigned type, it
3619 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003620 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003621 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003622}
Anders Carlsson98f07902007-08-17 05:31:46 +00003623
Anders Carlsson6d417272009-11-14 21:45:58 +00003624static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003625CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3626 DeclContext *DC, IdentifierInfo *Id) {
3627 SourceLocation Loc;
Anders Carlsson6d417272009-11-14 21:45:58 +00003628 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003629 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003630 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003631 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003632}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003633
Mike Stump11289f42009-09-09 15:08:12 +00003634// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003635QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003636 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003637 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003638 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003639 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003640 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003641
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003642 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003643
Anders Carlsson98f07902007-08-17 05:31:46 +00003644 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003645 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003646 // int flags;
3647 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003648 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003649 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003650 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003651 FieldTypes[3] = LongTy;
3652
Anders Carlsson98f07902007-08-17 05:31:46 +00003653 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003654 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003655 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003656 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003657 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003658 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003659 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003660 /*Mutable=*/false,
3661 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003662 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003663 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003664 }
3665
Douglas Gregord5058122010-02-11 01:19:42 +00003666 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003667 }
Mike Stump11289f42009-09-09 15:08:12 +00003668
Anders Carlsson98f07902007-08-17 05:31:46 +00003669 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003670}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003671
Douglas Gregor512b0772009-04-23 22:29:11 +00003672void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003673 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003674 assert(Rec && "Invalid CFConstantStringType");
3675 CFConstantStringTypeDecl = Rec->getDecl();
3676}
3677
Jay Foad39c79802011-01-12 09:06:06 +00003678QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003679 if (BlockDescriptorType)
3680 return getTagDeclType(BlockDescriptorType);
3681
3682 RecordDecl *T;
3683 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003684 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003685 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003686 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003687
3688 QualType FieldTypes[] = {
3689 UnsignedLongTy,
3690 UnsignedLongTy,
3691 };
3692
3693 const char *FieldNames[] = {
3694 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003695 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003696 };
3697
3698 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003699 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003700 SourceLocation(),
3701 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003702 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003703 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003704 /*Mutable=*/false,
3705 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003706 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003707 T->addDecl(Field);
3708 }
3709
Douglas Gregord5058122010-02-11 01:19:42 +00003710 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003711
3712 BlockDescriptorType = T;
3713
3714 return getTagDeclType(BlockDescriptorType);
3715}
3716
Jay Foad39c79802011-01-12 09:06:06 +00003717QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003718 if (BlockDescriptorExtendedType)
3719 return getTagDeclType(BlockDescriptorExtendedType);
3720
3721 RecordDecl *T;
3722 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003723 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003724 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003725 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003726
3727 QualType FieldTypes[] = {
3728 UnsignedLongTy,
3729 UnsignedLongTy,
3730 getPointerType(VoidPtrTy),
3731 getPointerType(VoidPtrTy)
3732 };
3733
3734 const char *FieldNames[] = {
3735 "reserved",
3736 "Size",
3737 "CopyFuncPtr",
3738 "DestroyFuncPtr"
3739 };
3740
3741 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003742 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003743 SourceLocation(),
3744 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003745 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003746 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003747 /*Mutable=*/false,
3748 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003749 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003750 T->addDecl(Field);
3751 }
3752
Douglas Gregord5058122010-02-11 01:19:42 +00003753 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003754
3755 BlockDescriptorExtendedType = T;
3756
3757 return getTagDeclType(BlockDescriptorExtendedType);
3758}
3759
Jay Foad39c79802011-01-12 09:06:06 +00003760bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00003761 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00003762 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003763 if (getLangOptions().CPlusPlus) {
3764 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3765 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00003766 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003767
3768 }
3769 }
Mike Stump94967902009-10-21 18:16:27 +00003770 return false;
3771}
3772
Jay Foad39c79802011-01-12 09:06:06 +00003773QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003774ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003775 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003776 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003777 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003778 // unsigned int __flags;
3779 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003780 // void *__copy_helper; // as needed
3781 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003782 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003783 // } *
3784
Mike Stump94967902009-10-21 18:16:27 +00003785 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3786
3787 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003788 llvm::SmallString<36> Name;
3789 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3790 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003791 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003792 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003793 T->startDefinition();
3794 QualType Int32Ty = IntTy;
3795 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3796 QualType FieldTypes[] = {
3797 getPointerType(VoidPtrTy),
3798 getPointerType(getTagDeclType(T)),
3799 Int32Ty,
3800 Int32Ty,
3801 getPointerType(VoidPtrTy),
3802 getPointerType(VoidPtrTy),
3803 Ty
3804 };
3805
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003806 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003807 "__isa",
3808 "__forwarding",
3809 "__flags",
3810 "__size",
3811 "__copy_helper",
3812 "__destroy_helper",
3813 DeclName,
3814 };
3815
3816 for (size_t i = 0; i < 7; ++i) {
3817 if (!HasCopyAndDispose && i >=4 && i <= 5)
3818 continue;
3819 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003820 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00003821 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003822 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003823 /*BitWidth=*/0, /*Mutable=*/false,
3824 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003825 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003826 T->addDecl(Field);
3827 }
3828
Douglas Gregord5058122010-02-11 01:19:42 +00003829 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003830
3831 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003832}
3833
Anders Carlsson18acd442007-10-29 06:33:42 +00003834// This returns true if a type has been typedefed to BOOL:
3835// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003836static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003837 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003838 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3839 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003840
Anders Carlssond8499822007-10-29 05:01:08 +00003841 return false;
3842}
3843
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003844/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003845/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00003846CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00003847 if (!type->isIncompleteArrayType() && type->isIncompleteType())
3848 return CharUnits::Zero();
3849
Ken Dyck40775002010-01-11 17:06:35 +00003850 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003851
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003852 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003853 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003854 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003855 // Treat arrays as pointers, since that's how they're passed in.
3856 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003857 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003858 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003859}
3860
3861static inline
3862std::string charUnitsToString(const CharUnits &CU) {
3863 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003864}
3865
John McCall351762c2011-02-07 10:33:21 +00003866/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003867/// declaration.
John McCall351762c2011-02-07 10:33:21 +00003868std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3869 std::string S;
3870
David Chisnall950a9512009-11-17 19:33:30 +00003871 const BlockDecl *Decl = Expr->getBlockDecl();
3872 QualType BlockTy =
3873 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3874 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003875 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003876 // Compute size of all parameters.
3877 // Start with computing size of a pointer in number of bytes.
3878 // FIXME: There might(should) be a better way of doing this computation!
3879 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003880 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3881 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003882 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003883 E = Decl->param_end(); PI != E; ++PI) {
3884 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003885 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003886 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003887 ParmOffset += sz;
3888 }
3889 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003890 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003891 // Block pointer and offset.
3892 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00003893
3894 // Argument types.
3895 ParmOffset = PtrSize;
3896 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3897 Decl->param_end(); PI != E; ++PI) {
3898 ParmVarDecl *PVDecl = *PI;
3899 QualType PType = PVDecl->getOriginalType();
3900 if (const ArrayType *AT =
3901 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3902 // Use array's original type only if it has known number of
3903 // elements.
3904 if (!isa<ConstantArrayType>(AT))
3905 PType = PVDecl->getType();
3906 } else if (PType->isFunctionType())
3907 PType = PVDecl->getType();
3908 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003909 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003910 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003911 }
John McCall351762c2011-02-07 10:33:21 +00003912
3913 return S;
David Chisnall950a9512009-11-17 19:33:30 +00003914}
3915
Douglas Gregora9d84932011-05-27 01:19:52 +00003916bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00003917 std::string& S) {
3918 // Encode result type.
3919 getObjCEncodingForType(Decl->getResultType(), S);
3920 CharUnits ParmOffset;
3921 // Compute size of all parameters.
3922 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3923 E = Decl->param_end(); PI != E; ++PI) {
3924 QualType PType = (*PI)->getType();
3925 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00003926 if (sz.isZero())
3927 return true;
3928
David Chisnall50e4eba2010-12-30 14:05:53 +00003929 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00003930 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00003931 ParmOffset += sz;
3932 }
3933 S += charUnitsToString(ParmOffset);
3934 ParmOffset = CharUnits::Zero();
3935
3936 // Argument types.
3937 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3938 E = Decl->param_end(); PI != E; ++PI) {
3939 ParmVarDecl *PVDecl = *PI;
3940 QualType PType = PVDecl->getOriginalType();
3941 if (const ArrayType *AT =
3942 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3943 // Use array's original type only if it has known number of
3944 // elements.
3945 if (!isa<ConstantArrayType>(AT))
3946 PType = PVDecl->getType();
3947 } else if (PType->isFunctionType())
3948 PType = PVDecl->getType();
3949 getObjCEncodingForType(PType, S);
3950 S += charUnitsToString(ParmOffset);
3951 ParmOffset += getObjCEncodingTypeSize(PType);
3952 }
Douglas Gregora9d84932011-05-27 01:19:52 +00003953
3954 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00003955}
3956
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003957/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003958/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00003959bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003960 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003961 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003962 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003963 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003964 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003965 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003966 // Compute size of all parameters.
3967 // Start with computing size of a pointer in number of bytes.
3968 // FIXME: There might(should) be a better way of doing this computation!
3969 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003970 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003971 // The first two arguments (self and _cmd) are pointers; account for
3972 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003973 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003974 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003975 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003976 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003977 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00003978 if (sz.isZero())
3979 return true;
3980
Ken Dyck40775002010-01-11 17:06:35 +00003981 assert (sz.isPositive() &&
3982 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003983 ParmOffset += sz;
3984 }
Ken Dyck40775002010-01-11 17:06:35 +00003985 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003986 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003987 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003988
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003989 // Argument types.
3990 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003991 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003992 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003993 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003994 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003995 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003996 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3997 // Use array's original type only if it has known number of
3998 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003999 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004000 PType = PVDecl->getType();
4001 } else if (PType->isFunctionType())
4002 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004003 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004004 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004005 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004006 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004007 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004008 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004009 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004010
4011 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004012}
4013
Daniel Dunbar4932b362008-08-28 04:38:10 +00004014/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004015/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004016/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4017/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004018/// Property attributes are stored as a comma-delimited C string. The simple
4019/// attributes readonly and bycopy are encoded as single characters. The
4020/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4021/// encoded as single characters, followed by an identifier. Property types
4022/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004023/// these attributes are defined by the following enumeration:
4024/// @code
4025/// enum PropertyAttributes {
4026/// kPropertyReadOnly = 'R', // property is read-only.
4027/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4028/// kPropertyByref = '&', // property is a reference to the value last assigned
4029/// kPropertyDynamic = 'D', // property is dynamic
4030/// kPropertyGetter = 'G', // followed by getter selector name
4031/// kPropertySetter = 'S', // followed by setter selector name
4032/// kPropertyInstanceVariable = 'V' // followed by instance variable name
4033/// kPropertyType = 't' // followed by old-style type encoding.
4034/// kPropertyWeak = 'W' // 'weak' property
4035/// kPropertyStrong = 'P' // property GC'able
4036/// kPropertyNonAtomic = 'N' // property non-atomic
4037/// };
4038/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004039void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004040 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004041 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004042 // Collect information from the property implementation decl(s).
4043 bool Dynamic = false;
4044 ObjCPropertyImplDecl *SynthesizePID = 0;
4045
4046 // FIXME: Duplicated code due to poor abstraction.
4047 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004048 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004049 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4050 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004051 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004052 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004053 ObjCPropertyImplDecl *PID = *i;
4054 if (PID->getPropertyDecl() == PD) {
4055 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4056 Dynamic = true;
4057 } else {
4058 SynthesizePID = PID;
4059 }
4060 }
4061 }
4062 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004063 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004064 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004065 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004066 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004067 ObjCPropertyImplDecl *PID = *i;
4068 if (PID->getPropertyDecl() == PD) {
4069 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4070 Dynamic = true;
4071 } else {
4072 SynthesizePID = PID;
4073 }
4074 }
Mike Stump11289f42009-09-09 15:08:12 +00004075 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004076 }
4077 }
4078
4079 // FIXME: This is not very efficient.
4080 S = "T";
4081
4082 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004083 // GCC has some special rules regarding encoding of properties which
4084 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004085 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004086 true /* outermost type */,
4087 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004088
4089 if (PD->isReadOnly()) {
4090 S += ",R";
4091 } else {
4092 switch (PD->getSetterKind()) {
4093 case ObjCPropertyDecl::Assign: break;
4094 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004095 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004096 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004097 }
4098 }
4099
4100 // It really isn't clear at all what this means, since properties
4101 // are "dynamic by default".
4102 if (Dynamic)
4103 S += ",D";
4104
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004105 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4106 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004107
Daniel Dunbar4932b362008-08-28 04:38:10 +00004108 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4109 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004110 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004111 }
4112
4113 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4114 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004115 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004116 }
4117
4118 if (SynthesizePID) {
4119 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4120 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004121 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004122 }
4123
4124 // FIXME: OBJCGC: weak & strong
4125}
4126
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004127/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004128/// Another legacy compatibility encoding: 32-bit longs are encoded as
4129/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004130/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4131///
4132void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004133 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004134 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004135 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004136 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004137 else
Jay Foad39c79802011-01-12 09:06:06 +00004138 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004139 PointeeTy = IntTy;
4140 }
4141 }
4142}
4143
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004144void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004145 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004146 // We follow the behavior of gcc, expanding structures which are
4147 // directly pointed to, and expanding embedded structures. Note that
4148 // these rules are sufficient to prevent recursive encoding of the
4149 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004150 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004151 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004152}
4153
David Chisnallb190a2c2010-06-04 01:10:52 +00004154static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4155 switch (T->getAs<BuiltinType>()->getKind()) {
4156 default: assert(0 && "Unhandled builtin type kind");
4157 case BuiltinType::Void: return 'v';
4158 case BuiltinType::Bool: return 'B';
4159 case BuiltinType::Char_U:
4160 case BuiltinType::UChar: return 'C';
4161 case BuiltinType::UShort: return 'S';
4162 case BuiltinType::UInt: return 'I';
4163 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004164 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004165 case BuiltinType::UInt128: return 'T';
4166 case BuiltinType::ULongLong: return 'Q';
4167 case BuiltinType::Char_S:
4168 case BuiltinType::SChar: return 'c';
4169 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004170 case BuiltinType::WChar_S:
4171 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004172 case BuiltinType::Int: return 'i';
4173 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004174 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004175 case BuiltinType::LongLong: return 'q';
4176 case BuiltinType::Int128: return 't';
4177 case BuiltinType::Float: return 'f';
4178 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004179 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004180 }
4181}
4182
Jay Foad39c79802011-01-12 09:06:06 +00004183static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004184 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004185 const Expr *E = FD->getBitWidth();
4186 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004187 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004188 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4189 // The GNU runtime requires more information; bitfields are encoded as b,
4190 // then the offset (in bits) of the first element, then the type of the
4191 // bitfield, then the size in bits. For example, in this structure:
4192 //
4193 // struct
4194 // {
4195 // int integer;
4196 // int flags:2;
4197 // };
4198 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4199 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4200 // information is not especially sensible, but we're stuck with it for
4201 // compatibility with GCC, although providing it breaks anything that
4202 // actually uses runtime introspection and wants to work on both runtimes...
4203 if (!Ctx->getLangOptions().NeXTRuntime) {
4204 const RecordDecl *RD = FD->getParent();
4205 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004206 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
David Chisnall6f0a7d22010-12-26 20:12:30 +00004207 if (T->isEnumeralType())
4208 S += 'i';
4209 else
Jay Foad39c79802011-01-12 09:06:06 +00004210 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004211 }
4212 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004213 S += llvm::utostr(N);
4214}
4215
Daniel Dunbar07d07852009-10-18 21:17:35 +00004216// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004217void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4218 bool ExpandPointedToStructures,
4219 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004220 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004221 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004222 bool EncodingProperty,
4223 bool StructField) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004224 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004225 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004226 return EncodeBitField(this, S, T, FD);
4227 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004228 return;
4229 }
Mike Stump11289f42009-09-09 15:08:12 +00004230
John McCall9dd450b2009-09-21 23:43:11 +00004231 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004232 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004233 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004234 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004235 return;
4236 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004237
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004238 // encoding for pointer or r3eference types.
4239 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004240 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004241 if (PT->isObjCSelType()) {
4242 S += ':';
4243 return;
4244 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004245 PointeeTy = PT->getPointeeType();
4246 }
4247 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4248 PointeeTy = RT->getPointeeType();
4249 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004250 bool isReadOnly = false;
4251 // For historical/compatibility reasons, the read-only qualifier of the
4252 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4253 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004254 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004255 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004256 if (OutermostType && T.isConstQualified()) {
4257 isReadOnly = true;
4258 S += 'r';
4259 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004260 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004261 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004262 while (P->getAs<PointerType>())
4263 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004264 if (P.isConstQualified()) {
4265 isReadOnly = true;
4266 S += 'r';
4267 }
4268 }
4269 if (isReadOnly) {
4270 // Another legacy compatibility encoding. Some ObjC qualifier and type
4271 // combinations need to be rearranged.
4272 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004273 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004274 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004275 }
Mike Stump11289f42009-09-09 15:08:12 +00004276
Anders Carlssond8499822007-10-29 05:01:08 +00004277 if (PointeeTy->isCharType()) {
4278 // char pointer types should be encoded as '*' unless it is a
4279 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004280 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004281 S += '*';
4282 return;
4283 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004284 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004285 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4286 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4287 S += '#';
4288 return;
4289 }
4290 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4291 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4292 S += '@';
4293 return;
4294 }
4295 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004296 }
Anders Carlssond8499822007-10-29 05:01:08 +00004297 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004298 getLegacyIntegralTypeEncoding(PointeeTy);
4299
Mike Stump11289f42009-09-09 15:08:12 +00004300 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004301 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004302 return;
4303 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004304
Chris Lattnere7cabb92009-07-13 00:10:46 +00004305 if (const ArrayType *AT =
4306 // Ignore type qualifiers etc.
4307 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004308 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004309 // Incomplete arrays are encoded as a pointer to the array element.
4310 S += '^';
4311
Mike Stump11289f42009-09-09 15:08:12 +00004312 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004313 false, ExpandStructures, FD);
4314 } else {
4315 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004316
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004317 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4318 if (getTypeSize(CAT->getElementType()) == 0)
4319 S += '0';
4320 else
4321 S += llvm::utostr(CAT->getSize().getZExtValue());
4322 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004323 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004324 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4325 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004326 S += '0';
4327 }
Mike Stump11289f42009-09-09 15:08:12 +00004328
4329 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004330 false, ExpandStructures, FD);
4331 S += ']';
4332 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004333 return;
4334 }
Mike Stump11289f42009-09-09 15:08:12 +00004335
John McCall9dd450b2009-09-21 23:43:11 +00004336 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004337 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004338 return;
4339 }
Mike Stump11289f42009-09-09 15:08:12 +00004340
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004341 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004342 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004343 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004344 // Anonymous structures print as '?'
4345 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4346 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004347 if (ClassTemplateSpecializationDecl *Spec
4348 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4349 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4350 std::string TemplateArgsStr
4351 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004352 TemplateArgs.data(),
4353 TemplateArgs.size(),
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004354 (*this).PrintingPolicy);
4355
4356 S += TemplateArgsStr;
4357 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004358 } else {
4359 S += '?';
4360 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004361 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004362 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004363 if (!RDecl->isUnion()) {
4364 getObjCEncodingForStructureImpl(RDecl, S, FD);
4365 } else {
4366 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4367 FieldEnd = RDecl->field_end();
4368 Field != FieldEnd; ++Field) {
4369 if (FD) {
4370 S += '"';
4371 S += Field->getNameAsString();
4372 S += '"';
4373 }
Mike Stump11289f42009-09-09 15:08:12 +00004374
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004375 // Special case bit-fields.
4376 if (Field->isBitField()) {
4377 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4378 (*Field));
4379 } else {
4380 QualType qt = Field->getType();
4381 getLegacyIntegralTypeEncoding(qt);
4382 getObjCEncodingForTypeImpl(qt, S, false, true,
4383 FD, /*OutermostType*/false,
4384 /*EncodingProperty*/false,
4385 /*StructField*/true);
4386 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004387 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004388 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004389 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004390 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004391 return;
4392 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004393
Chris Lattnere7cabb92009-07-13 00:10:46 +00004394 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004395 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004396 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004397 else
4398 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004399 return;
4400 }
Mike Stump11289f42009-09-09 15:08:12 +00004401
Chris Lattnere7cabb92009-07-13 00:10:46 +00004402 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004403 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00004404 return;
4405 }
Mike Stump11289f42009-09-09 15:08:12 +00004406
John McCall8b07ec22010-05-15 11:32:37 +00004407 // Ignore protocol qualifiers when mangling at this level.
4408 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4409 T = OT->getBaseType();
4410
John McCall8ccfcb52009-09-24 19:53:00 +00004411 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004412 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004413 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004414 S += '{';
4415 const IdentifierInfo *II = OI->getIdentifier();
4416 S += II->getName();
4417 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004418 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004419 DeepCollectObjCIvars(OI, true, Ivars);
4420 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004421 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004422 if (Field->isBitField())
4423 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004424 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004425 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004426 }
4427 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004428 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004429 }
Mike Stump11289f42009-09-09 15:08:12 +00004430
John McCall9dd450b2009-09-21 23:43:11 +00004431 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004432 if (OPT->isObjCIdType()) {
4433 S += '@';
4434 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004435 }
Mike Stump11289f42009-09-09 15:08:12 +00004436
Steve Narofff0c86112009-10-28 22:03:49 +00004437 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4438 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4439 // Since this is a binary compatibility issue, need to consult with runtime
4440 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004441 S += '#';
4442 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004443 }
Mike Stump11289f42009-09-09 15:08:12 +00004444
Chris Lattnere7cabb92009-07-13 00:10:46 +00004445 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004446 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004447 ExpandPointedToStructures,
4448 ExpandStructures, FD);
4449 if (FD || EncodingProperty) {
4450 // Note that we do extended encoding of protocol qualifer list
4451 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004452 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004453 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4454 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004455 S += '<';
4456 S += (*I)->getNameAsString();
4457 S += '>';
4458 }
4459 S += '"';
4460 }
4461 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004462 }
Mike Stump11289f42009-09-09 15:08:12 +00004463
Chris Lattnere7cabb92009-07-13 00:10:46 +00004464 QualType PointeeTy = OPT->getPointeeType();
4465 if (!EncodingProperty &&
4466 isa<TypedefType>(PointeeTy.getTypePtr())) {
4467 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004468 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004469 // {...};
4470 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004471 getObjCEncodingForTypeImpl(PointeeTy, S,
4472 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004473 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004474 return;
4475 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004476
4477 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00004478 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004479 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004480 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004481 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4482 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004483 S += '<';
4484 S += (*I)->getNameAsString();
4485 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004486 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004487 S += '"';
4488 }
4489 return;
4490 }
Mike Stump11289f42009-09-09 15:08:12 +00004491
John McCalla9e6e8d2010-05-17 23:56:34 +00004492 // gcc just blithely ignores member pointers.
4493 // TODO: maybe there should be a mangling for these
4494 if (T->getAs<MemberPointerType>())
4495 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004496
4497 if (T->isVectorType()) {
4498 // This matches gcc's encoding, even though technically it is
4499 // insufficient.
4500 // FIXME. We should do a better job than gcc.
4501 return;
4502 }
4503
Chris Lattnere7cabb92009-07-13 00:10:46 +00004504 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004505}
4506
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004507void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4508 std::string &S,
4509 const FieldDecl *FD,
4510 bool includeVBases) const {
4511 assert(RDecl && "Expected non-null RecordDecl");
4512 assert(!RDecl->isUnion() && "Should not be called for unions");
4513 if (!RDecl->getDefinition())
4514 return;
4515
4516 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4517 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4518 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4519
4520 if (CXXRec) {
4521 for (CXXRecordDecl::base_class_iterator
4522 BI = CXXRec->bases_begin(),
4523 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4524 if (!BI->isVirtual()) {
4525 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004526 if (base->isEmpty())
4527 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004528 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4529 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4530 std::make_pair(offs, base));
4531 }
4532 }
4533 }
4534
4535 unsigned i = 0;
4536 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4537 FieldEnd = RDecl->field_end();
4538 Field != FieldEnd; ++Field, ++i) {
4539 uint64_t offs = layout.getFieldOffset(i);
4540 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4541 std::make_pair(offs, *Field));
4542 }
4543
4544 if (CXXRec && includeVBases) {
4545 for (CXXRecordDecl::base_class_iterator
4546 BI = CXXRec->vbases_begin(),
4547 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4548 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004549 if (base->isEmpty())
4550 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004551 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
4552 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4553 std::make_pair(offs, base));
4554 }
4555 }
4556
4557 CharUnits size;
4558 if (CXXRec) {
4559 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4560 } else {
4561 size = layout.getSize();
4562 }
4563
4564 uint64_t CurOffs = 0;
4565 std::multimap<uint64_t, NamedDecl *>::iterator
4566 CurLayObj = FieldOrBaseOffsets.begin();
4567
Argyrios Kyrtzidisc7e50c52011-08-22 16:03:14 +00004568 if ((CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) ||
4569 (CurLayObj == FieldOrBaseOffsets.end() &&
4570 CXXRec && CXXRec->isDynamicClass())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004571 assert(CXXRec && CXXRec->isDynamicClass() &&
4572 "Offset 0 was empty but no VTable ?");
4573 if (FD) {
4574 S += "\"_vptr$";
4575 std::string recname = CXXRec->getNameAsString();
4576 if (recname.empty()) recname = "?";
4577 S += recname;
4578 S += '"';
4579 }
4580 S += "^^?";
4581 CurOffs += getTypeSize(VoidPtrTy);
4582 }
4583
4584 if (!RDecl->hasFlexibleArrayMember()) {
4585 // Mark the end of the structure.
4586 uint64_t offs = toBits(size);
4587 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4588 std::make_pair(offs, (NamedDecl*)0));
4589 }
4590
4591 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4592 assert(CurOffs <= CurLayObj->first);
4593
4594 if (CurOffs < CurLayObj->first) {
4595 uint64_t padding = CurLayObj->first - CurOffs;
4596 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4597 // packing/alignment of members is different that normal, in which case
4598 // the encoding will be out-of-sync with the real layout.
4599 // If the runtime switches to just consider the size of types without
4600 // taking into account alignment, we could make padding explicit in the
4601 // encoding (e.g. using arrays of chars). The encoding strings would be
4602 // longer then though.
4603 CurOffs += padding;
4604 }
4605
4606 NamedDecl *dcl = CurLayObj->second;
4607 if (dcl == 0)
4608 break; // reached end of structure.
4609
4610 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4611 // We expand the bases without their virtual bases since those are going
4612 // in the initial structure. Note that this differs from gcc which
4613 // expands virtual bases each time one is encountered in the hierarchy,
4614 // making the encoding type bigger than it really is.
4615 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004616 assert(!base->isEmpty());
4617 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004618 } else {
4619 FieldDecl *field = cast<FieldDecl>(dcl);
4620 if (FD) {
4621 S += '"';
4622 S += field->getNameAsString();
4623 S += '"';
4624 }
4625
4626 if (field->isBitField()) {
4627 EncodeBitField(this, S, field->getType(), field);
4628 CurOffs += field->getBitWidth()->EvaluateAsInt(*this).getZExtValue();
4629 } else {
4630 QualType qt = field->getType();
4631 getLegacyIntegralTypeEncoding(qt);
4632 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4633 /*OutermostType*/false,
4634 /*EncodingProperty*/false,
4635 /*StructField*/true);
4636 CurOffs += getTypeSize(field->getType());
4637 }
4638 }
4639 }
4640}
4641
Mike Stump11289f42009-09-09 15:08:12 +00004642void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004643 std::string& S) const {
4644 if (QT & Decl::OBJC_TQ_In)
4645 S += 'n';
4646 if (QT & Decl::OBJC_TQ_Inout)
4647 S += 'N';
4648 if (QT & Decl::OBJC_TQ_Out)
4649 S += 'o';
4650 if (QT & Decl::OBJC_TQ_Bycopy)
4651 S += 'O';
4652 if (QT & Decl::OBJC_TQ_Byref)
4653 S += 'R';
4654 if (QT & Decl::OBJC_TQ_Oneway)
4655 S += 'V';
4656}
4657
Chris Lattnere7cabb92009-07-13 00:10:46 +00004658void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004659 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004660
Anders Carlsson87c149b2007-10-11 01:00:40 +00004661 BuiltinVaListType = T;
4662}
4663
Douglas Gregor3ea72692011-08-12 05:46:01 +00004664TypedefDecl *ASTContext::getObjCIdDecl() const {
4665 if (!ObjCIdDecl) {
4666 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4667 T = getObjCObjectPointerType(T);
4668 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4669 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4670 getTranslationUnitDecl(),
4671 SourceLocation(), SourceLocation(),
4672 &Idents.get("id"), IdInfo);
4673 }
4674
4675 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00004676}
4677
Douglas Gregor52e02802011-08-12 06:17:30 +00004678TypedefDecl *ASTContext::getObjCSelDecl() const {
4679 if (!ObjCSelDecl) {
4680 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4681 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4682 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4683 getTranslationUnitDecl(),
4684 SourceLocation(), SourceLocation(),
4685 &Idents.get("SEL"), SelInfo);
4686 }
4687 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004688}
4689
Chris Lattnere7cabb92009-07-13 00:10:46 +00004690void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004691 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004692}
4693
Douglas Gregor0a586182011-08-12 05:59:41 +00004694TypedefDecl *ASTContext::getObjCClassDecl() const {
4695 if (!ObjCClassDecl) {
4696 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4697 T = getObjCObjectPointerType(T);
4698 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4699 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4700 getTranslationUnitDecl(),
4701 SourceLocation(), SourceLocation(),
4702 &Idents.get("Class"), ClassInfo);
4703 }
4704
4705 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004706}
4707
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004708void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004709 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004710 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004711
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004712 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004713}
4714
John McCalld28ae272009-12-02 08:04:21 +00004715/// \brief Retrieve the template name that corresponds to a non-empty
4716/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004717TemplateName
4718ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4719 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004720 unsigned size = End - Begin;
4721 assert(size > 1 && "set is not overloaded!");
4722
4723 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4724 size * sizeof(FunctionTemplateDecl*));
4725 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4726
4727 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004728 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004729 NamedDecl *D = *I;
4730 assert(isa<FunctionTemplateDecl>(D) ||
4731 (isa<UsingShadowDecl>(D) &&
4732 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4733 *Storage++ = D;
4734 }
4735
4736 return TemplateName(OT);
4737}
4738
Douglas Gregordc572a32009-03-30 22:58:21 +00004739/// \brief Retrieve the template name that represents a qualified
4740/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004741TemplateName
4742ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4743 bool TemplateKeyword,
4744 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00004745 assert(NNS && "Missing nested-name-specifier in qualified template name");
4746
Douglas Gregorc42075a2010-02-04 18:10:26 +00004747 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004748 llvm::FoldingSetNodeID ID;
4749 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4750
4751 void *InsertPos = 0;
4752 QualifiedTemplateName *QTN =
4753 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4754 if (!QTN) {
4755 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4756 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4757 }
4758
4759 return TemplateName(QTN);
4760}
4761
4762/// \brief Retrieve the template name that represents a dependent
4763/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004764TemplateName
4765ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4766 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004767 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004768 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004769
4770 llvm::FoldingSetNodeID ID;
4771 DependentTemplateName::Profile(ID, NNS, Name);
4772
4773 void *InsertPos = 0;
4774 DependentTemplateName *QTN =
4775 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4776
4777 if (QTN)
4778 return TemplateName(QTN);
4779
4780 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4781 if (CanonNNS == NNS) {
4782 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4783 } else {
4784 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4785 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004786 DependentTemplateName *CheckQTN =
4787 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4788 assert(!CheckQTN && "Dependent type name canonicalization broken");
4789 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004790 }
4791
4792 DependentTemplateNames.InsertNode(QTN, InsertPos);
4793 return TemplateName(QTN);
4794}
4795
Douglas Gregor71395fa2009-11-04 00:56:37 +00004796/// \brief Retrieve the template name that represents a dependent
4797/// template name such as \c MetaFun::template operator+.
4798TemplateName
4799ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00004800 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00004801 assert((!NNS || NNS->isDependent()) &&
4802 "Nested name specifier must be dependent");
4803
4804 llvm::FoldingSetNodeID ID;
4805 DependentTemplateName::Profile(ID, NNS, Operator);
4806
4807 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004808 DependentTemplateName *QTN
4809 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004810
4811 if (QTN)
4812 return TemplateName(QTN);
4813
4814 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4815 if (CanonNNS == NNS) {
4816 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4817 } else {
4818 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4819 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004820
4821 DependentTemplateName *CheckQTN
4822 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4823 assert(!CheckQTN && "Dependent template name canonicalization broken");
4824 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004825 }
4826
4827 DependentTemplateNames.InsertNode(QTN, InsertPos);
4828 return TemplateName(QTN);
4829}
4830
Douglas Gregor5590be02011-01-15 06:45:20 +00004831TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00004832ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
4833 TemplateName replacement) const {
4834 llvm::FoldingSetNodeID ID;
4835 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
4836
4837 void *insertPos = 0;
4838 SubstTemplateTemplateParmStorage *subst
4839 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
4840
4841 if (!subst) {
4842 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
4843 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
4844 }
4845
4846 return TemplateName(subst);
4847}
4848
4849TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00004850ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4851 const TemplateArgument &ArgPack) const {
4852 ASTContext &Self = const_cast<ASTContext &>(*this);
4853 llvm::FoldingSetNodeID ID;
4854 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4855
4856 void *InsertPos = 0;
4857 SubstTemplateTemplateParmPackStorage *Subst
4858 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4859
4860 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00004861 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00004862 ArgPack.pack_size(),
4863 ArgPack.pack_begin());
4864 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4865 }
4866
4867 return TemplateName(Subst);
4868}
4869
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004870/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004871/// TargetInfo, produce the corresponding type. The unsigned @p Type
4872/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004873CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004874 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004875 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004876 case TargetInfo::SignedShort: return ShortTy;
4877 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4878 case TargetInfo::SignedInt: return IntTy;
4879 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4880 case TargetInfo::SignedLong: return LongTy;
4881 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4882 case TargetInfo::SignedLongLong: return LongLongTy;
4883 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4884 }
4885
4886 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004887 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004888}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004889
4890//===----------------------------------------------------------------------===//
4891// Type Predicates.
4892//===----------------------------------------------------------------------===//
4893
Fariborz Jahanian96207692009-02-18 21:49:28 +00004894/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4895/// garbage collection attribute.
4896///
John McCall553d45a2011-01-12 00:34:59 +00004897Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4898 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4899 return Qualifiers::GCNone;
4900
4901 assert(getLangOptions().ObjC1);
4902 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4903
4904 // Default behaviour under objective-C's gc is for ObjC pointers
4905 // (or pointers to them) be treated as though they were declared
4906 // as __strong.
4907 if (GCAttrs == Qualifiers::GCNone) {
4908 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4909 return Qualifiers::Strong;
4910 else if (Ty->isPointerType())
4911 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4912 } else {
4913 // It's not valid to set GC attributes on anything that isn't a
4914 // pointer.
4915#ifndef NDEBUG
4916 QualType CT = Ty->getCanonicalTypeInternal();
4917 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4918 CT = AT->getElementType();
4919 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4920#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00004921 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004922 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004923}
4924
Chris Lattner49af6a42008-04-07 06:51:04 +00004925//===----------------------------------------------------------------------===//
4926// Type Compatibility Testing
4927//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004928
Mike Stump11289f42009-09-09 15:08:12 +00004929/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004930/// compatible.
4931static bool areCompatVectorTypes(const VectorType *LHS,
4932 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004933 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004934 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004935 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004936}
4937
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004938bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4939 QualType SecondVec) {
4940 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4941 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4942
4943 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4944 return true;
4945
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004946 // Treat Neon vector types and most AltiVec vector types as if they are the
4947 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004948 const VectorType *First = FirstVec->getAs<VectorType>();
4949 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004950 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004951 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004952 First->getVectorKind() != VectorType::AltiVecPixel &&
4953 First->getVectorKind() != VectorType::AltiVecBool &&
4954 Second->getVectorKind() != VectorType::AltiVecPixel &&
4955 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004956 return true;
4957
4958 return false;
4959}
4960
Steve Naroff8e6aee52009-07-23 01:01:38 +00004961//===----------------------------------------------------------------------===//
4962// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4963//===----------------------------------------------------------------------===//
4964
4965/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4966/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00004967bool
4968ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4969 ObjCProtocolDecl *rProto) const {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004970 if (lProto == rProto)
4971 return true;
4972 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4973 E = rProto->protocol_end(); PI != E; ++PI)
4974 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4975 return true;
4976 return false;
4977}
4978
Steve Naroff8e6aee52009-07-23 01:01:38 +00004979/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4980/// return true if lhs's protocols conform to rhs's protocol; false
4981/// otherwise.
4982bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4983 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4984 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4985 return false;
4986}
4987
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004988/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4989/// Class<p1, ...>.
4990bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4991 QualType rhs) {
4992 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4993 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4994 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4995
4996 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4997 E = lhsQID->qual_end(); I != E; ++I) {
4998 bool match = false;
4999 ObjCProtocolDecl *lhsProto = *I;
5000 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5001 E = rhsOPT->qual_end(); J != E; ++J) {
5002 ObjCProtocolDecl *rhsProto = *J;
5003 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5004 match = true;
5005 break;
5006 }
5007 }
5008 if (!match)
5009 return false;
5010 }
5011 return true;
5012}
5013
Steve Naroff8e6aee52009-07-23 01:01:38 +00005014/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5015/// ObjCQualifiedIDType.
5016bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5017 bool compare) {
5018 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005019 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005020 lhs->isObjCIdType() || lhs->isObjCClassType())
5021 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005022 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005023 rhs->isObjCIdType() || rhs->isObjCClassType())
5024 return true;
5025
5026 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005027 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005028
Steve Naroff8e6aee52009-07-23 01:01:38 +00005029 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005030
Steve Naroff8e6aee52009-07-23 01:01:38 +00005031 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005032 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005033 // make sure we check the class hierarchy.
5034 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5035 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5036 E = lhsQID->qual_end(); I != E; ++I) {
5037 // when comparing an id<P> on lhs with a static type on rhs,
5038 // see if static class implements all of id's protocols, directly or
5039 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005040 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005041 return false;
5042 }
5043 }
5044 // If there are no qualifiers and no interface, we have an 'id'.
5045 return true;
5046 }
Mike Stump11289f42009-09-09 15:08:12 +00005047 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005048 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5049 E = lhsQID->qual_end(); I != E; ++I) {
5050 ObjCProtocolDecl *lhsProto = *I;
5051 bool match = false;
5052
5053 // when comparing an id<P> on lhs with a static type on rhs,
5054 // see if static class implements all of id's protocols, directly or
5055 // through its super class and categories.
5056 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5057 E = rhsOPT->qual_end(); J != E; ++J) {
5058 ObjCProtocolDecl *rhsProto = *J;
5059 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5060 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5061 match = true;
5062 break;
5063 }
5064 }
Mike Stump11289f42009-09-09 15:08:12 +00005065 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005066 // make sure we check the class hierarchy.
5067 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5068 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5069 E = lhsQID->qual_end(); I != E; ++I) {
5070 // when comparing an id<P> on lhs with a static type on rhs,
5071 // see if static class implements all of id's protocols, directly or
5072 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005073 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005074 match = true;
5075 break;
5076 }
5077 }
5078 }
5079 if (!match)
5080 return false;
5081 }
Mike Stump11289f42009-09-09 15:08:12 +00005082
Steve Naroff8e6aee52009-07-23 01:01:38 +00005083 return true;
5084 }
Mike Stump11289f42009-09-09 15:08:12 +00005085
Steve Naroff8e6aee52009-07-23 01:01:38 +00005086 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5087 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5088
Mike Stump11289f42009-09-09 15:08:12 +00005089 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005090 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005091 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005092 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5093 E = lhsOPT->qual_end(); I != E; ++I) {
5094 ObjCProtocolDecl *lhsProto = *I;
5095 bool match = false;
5096
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005097 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005098 // see if static class implements all of id's protocols, directly or
5099 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005100 // First, lhs protocols in the qualifier list must be found, direct
5101 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005102 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5103 E = rhsQID->qual_end(); J != E; ++J) {
5104 ObjCProtocolDecl *rhsProto = *J;
5105 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5106 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5107 match = true;
5108 break;
5109 }
5110 }
5111 if (!match)
5112 return false;
5113 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005114
5115 // Static class's protocols, or its super class or category protocols
5116 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5117 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5118 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5119 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5120 // This is rather dubious but matches gcc's behavior. If lhs has
5121 // no type qualifier and its class has no static protocol(s)
5122 // assume that it is mismatch.
5123 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5124 return false;
5125 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5126 LHSInheritedProtocols.begin(),
5127 E = LHSInheritedProtocols.end(); I != E; ++I) {
5128 bool match = false;
5129 ObjCProtocolDecl *lhsProto = (*I);
5130 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5131 E = rhsQID->qual_end(); J != E; ++J) {
5132 ObjCProtocolDecl *rhsProto = *J;
5133 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5134 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5135 match = true;
5136 break;
5137 }
5138 }
5139 if (!match)
5140 return false;
5141 }
5142 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005143 return true;
5144 }
5145 return false;
5146}
5147
Eli Friedman47f77112008-08-22 00:56:42 +00005148/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005149/// compatible for assignment from RHS to LHS. This handles validation of any
5150/// protocol qualifiers on the LHS or RHS.
5151///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005152bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5153 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005154 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5155 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5156
Steve Naroff1329fa02009-07-15 18:40:39 +00005157 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005158 if (LHS->isObjCUnqualifiedIdOrClass() ||
5159 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005160 return true;
5161
John McCall8b07ec22010-05-15 11:32:37 +00005162 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005163 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5164 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005165 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005166
5167 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5168 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5169 QualType(RHSOPT,0));
5170
John McCall8b07ec22010-05-15 11:32:37 +00005171 // If we have 2 user-defined types, fall into that path.
5172 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005173 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005174
Steve Naroff8e6aee52009-07-23 01:01:38 +00005175 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005176}
5177
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005178/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005179/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005180/// arguments in block literals. When passed as arguments, passing 'A*' where
5181/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5182/// not OK. For the return type, the opposite is not OK.
5183bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5184 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005185 const ObjCObjectPointerType *RHSOPT,
5186 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005187 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005188 return true;
5189
5190 if (LHSOPT->isObjCBuiltinType()) {
5191 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5192 }
5193
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005194 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005195 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5196 QualType(RHSOPT,0),
5197 false);
5198
5199 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5200 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5201 if (LHS && RHS) { // We have 2 user-defined types.
5202 if (LHS != RHS) {
5203 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005204 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005205 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005206 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005207 }
5208 else
5209 return true;
5210 }
5211 return false;
5212}
5213
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005214/// getIntersectionOfProtocols - This routine finds the intersection of set
5215/// of protocols inherited from two distinct objective-c pointer objects.
5216/// It is used to build composite qualifier list of the composite type of
5217/// the conditional expression involving two objective-c pointer objects.
5218static
5219void getIntersectionOfProtocols(ASTContext &Context,
5220 const ObjCObjectPointerType *LHSOPT,
5221 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005222 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005223
John McCall8b07ec22010-05-15 11:32:37 +00005224 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5225 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5226 assert(LHS->getInterface() && "LHS must have an interface base");
5227 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005228
5229 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5230 unsigned LHSNumProtocols = LHS->getNumProtocols();
5231 if (LHSNumProtocols > 0)
5232 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5233 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005234 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005235 Context.CollectInheritedProtocols(LHS->getInterface(),
5236 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005237 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5238 LHSInheritedProtocols.end());
5239 }
5240
5241 unsigned RHSNumProtocols = RHS->getNumProtocols();
5242 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005243 ObjCProtocolDecl **RHSProtocols =
5244 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005245 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5246 if (InheritedProtocolSet.count(RHSProtocols[i]))
5247 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00005248 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005249 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005250 Context.CollectInheritedProtocols(RHS->getInterface(),
5251 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005252 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5253 RHSInheritedProtocols.begin(),
5254 E = RHSInheritedProtocols.end(); I != E; ++I)
5255 if (InheritedProtocolSet.count((*I)))
5256 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005257 }
5258}
5259
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005260/// areCommonBaseCompatible - Returns common base class of the two classes if
5261/// one found. Note that this is O'2 algorithm. But it will be called as the
5262/// last type comparison in a ?-exp of ObjC pointer types before a
5263/// warning is issued. So, its invokation is extremely rare.
5264QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005265 const ObjCObjectPointerType *Lptr,
5266 const ObjCObjectPointerType *Rptr) {
5267 const ObjCObjectType *LHS = Lptr->getObjectType();
5268 const ObjCObjectType *RHS = Rptr->getObjectType();
5269 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5270 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005271 if (!LDecl || !RDecl || (LDecl == RDecl))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005272 return QualType();
5273
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005274 do {
John McCall8b07ec22010-05-15 11:32:37 +00005275 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005276 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005277 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00005278 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5279
5280 QualType Result = QualType(LHS, 0);
5281 if (!Protocols.empty())
5282 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5283 Result = getObjCObjectPointerType(Result);
5284 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005285 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005286 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005287
5288 return QualType();
5289}
5290
John McCall8b07ec22010-05-15 11:32:37 +00005291bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5292 const ObjCObjectType *RHS) {
5293 assert(LHS->getInterface() && "LHS is not an interface type");
5294 assert(RHS->getInterface() && "RHS is not an interface type");
5295
Chris Lattner49af6a42008-04-07 06:51:04 +00005296 // Verify that the base decls are compatible: the RHS must be a subclass of
5297 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005298 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005299 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005300
Chris Lattner49af6a42008-04-07 06:51:04 +00005301 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5302 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005303 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005304 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005305
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005306 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5307 // more detailed analysis is required.
5308 if (RHS->getNumProtocols() == 0) {
5309 // OK, if LHS is a superclass of RHS *and*
5310 // this superclass is assignment compatible with LHS.
5311 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005312 bool IsSuperClass =
5313 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5314 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005315 // OK if conversion of LHS to SuperClass results in narrowing of types
5316 // ; i.e., SuperClass may implement at least one of the protocols
5317 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5318 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5319 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005320 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005321 // If super class has no protocols, it is not a match.
5322 if (SuperClassInheritedProtocols.empty())
5323 return false;
5324
5325 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5326 LHSPE = LHS->qual_end();
5327 LHSPI != LHSPE; LHSPI++) {
5328 bool SuperImplementsProtocol = false;
5329 ObjCProtocolDecl *LHSProto = (*LHSPI);
5330
5331 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5332 SuperClassInheritedProtocols.begin(),
5333 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5334 ObjCProtocolDecl *SuperClassProto = (*I);
5335 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5336 SuperImplementsProtocol = true;
5337 break;
5338 }
5339 }
5340 if (!SuperImplementsProtocol)
5341 return false;
5342 }
5343 return true;
5344 }
5345 return false;
5346 }
Mike Stump11289f42009-09-09 15:08:12 +00005347
John McCall8b07ec22010-05-15 11:32:37 +00005348 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5349 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005350 LHSPI != LHSPE; LHSPI++) {
5351 bool RHSImplementsProtocol = false;
5352
5353 // If the RHS doesn't implement the protocol on the left, the types
5354 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005355 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5356 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005357 RHSPI != RHSPE; RHSPI++) {
5358 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005359 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005360 break;
5361 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005362 }
5363 // FIXME: For better diagnostics, consider passing back the protocol name.
5364 if (!RHSImplementsProtocol)
5365 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005366 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005367 // The RHS implements all protocols listed on the LHS.
5368 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005369}
5370
Steve Naroffb7605152009-02-12 17:52:19 +00005371bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5372 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005373 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5374 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005375
Steve Naroff7cae42b2009-07-10 23:34:53 +00005376 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005377 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005378
5379 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5380 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005381}
5382
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005383bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5384 return canAssignObjCInterfaces(
5385 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5386 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5387}
5388
Mike Stump11289f42009-09-09 15:08:12 +00005389/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005390/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005391/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005392/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005393bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5394 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00005395 if (getLangOptions().CPlusPlus)
5396 return hasSameType(LHS, RHS);
5397
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005398 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005399}
5400
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005401bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00005402 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005403}
5404
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005405bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5406 return !mergeTypes(LHS, RHS, true).isNull();
5407}
5408
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005409/// mergeTransparentUnionType - if T is a transparent union type and a member
5410/// of T is compatible with SubType, return the merged type, else return
5411/// QualType()
5412QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5413 bool OfBlockPointer,
5414 bool Unqualified) {
5415 if (const RecordType *UT = T->getAsUnionType()) {
5416 RecordDecl *UD = UT->getDecl();
5417 if (UD->hasAttr<TransparentUnionAttr>()) {
5418 for (RecordDecl::field_iterator it = UD->field_begin(),
5419 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005420 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005421 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5422 if (!MT.isNull())
5423 return MT;
5424 }
5425 }
5426 }
5427
5428 return QualType();
5429}
5430
5431/// mergeFunctionArgumentTypes - merge two types which appear as function
5432/// argument types
5433QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5434 bool OfBlockPointer,
5435 bool Unqualified) {
5436 // GNU extension: two types are compatible if they appear as a function
5437 // argument, one of the types is a transparent union type and the other
5438 // type is compatible with a union member
5439 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5440 Unqualified);
5441 if (!lmerge.isNull())
5442 return lmerge;
5443
5444 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5445 Unqualified);
5446 if (!rmerge.isNull())
5447 return rmerge;
5448
5449 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5450}
5451
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005452QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005453 bool OfBlockPointer,
5454 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005455 const FunctionType *lbase = lhs->getAs<FunctionType>();
5456 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005457 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5458 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005459 bool allLTypes = true;
5460 bool allRTypes = true;
5461
5462 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005463 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00005464 if (OfBlockPointer) {
5465 QualType RHS = rbase->getResultType();
5466 QualType LHS = lbase->getResultType();
5467 bool UnqualifiedResult = Unqualified;
5468 if (!UnqualifiedResult)
5469 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005470 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00005471 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005472 else
John McCall8c6b56f2010-12-15 01:06:38 +00005473 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5474 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005475 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005476
5477 if (Unqualified)
5478 retType = retType.getUnqualifiedType();
5479
5480 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5481 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5482 if (Unqualified) {
5483 LRetType = LRetType.getUnqualifiedType();
5484 RRetType = RRetType.getUnqualifiedType();
5485 }
5486
5487 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005488 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005489 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005490 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005491
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005492 // FIXME: double check this
5493 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5494 // rbase->getRegParmAttr() != 0 &&
5495 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005496 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5497 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005498
Douglas Gregor8c940862010-01-18 17:14:39 +00005499 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005500 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005501 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005502
John McCall8c6b56f2010-12-15 01:06:38 +00005503 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00005504 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5505 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00005506 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5507 return QualType();
5508
John McCall31168b02011-06-15 23:02:42 +00005509 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5510 return QualType();
5511
John McCall8c6b56f2010-12-15 01:06:38 +00005512 // It's noreturn if either type is.
5513 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5514 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5515 if (NoReturn != lbaseInfo.getNoReturn())
5516 allLTypes = false;
5517 if (NoReturn != rbaseInfo.getNoReturn())
5518 allRTypes = false;
5519
John McCall31168b02011-06-15 23:02:42 +00005520 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00005521
Eli Friedman47f77112008-08-22 00:56:42 +00005522 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005523 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5524 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005525 unsigned lproto_nargs = lproto->getNumArgs();
5526 unsigned rproto_nargs = rproto->getNumArgs();
5527
5528 // Compatible functions must have the same number of arguments
5529 if (lproto_nargs != rproto_nargs)
5530 return QualType();
5531
5532 // Variadic and non-variadic functions aren't compatible
5533 if (lproto->isVariadic() != rproto->isVariadic())
5534 return QualType();
5535
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005536 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5537 return QualType();
5538
Eli Friedman47f77112008-08-22 00:56:42 +00005539 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005540 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00005541 for (unsigned i = 0; i < lproto_nargs; i++) {
5542 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5543 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005544 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5545 OfBlockPointer,
5546 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005547 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005548
5549 if (Unqualified)
5550 argtype = argtype.getUnqualifiedType();
5551
Eli Friedman47f77112008-08-22 00:56:42 +00005552 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005553 if (Unqualified) {
5554 largtype = largtype.getUnqualifiedType();
5555 rargtype = rargtype.getUnqualifiedType();
5556 }
5557
Chris Lattner465fa322008-10-05 17:34:18 +00005558 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5559 allLTypes = false;
5560 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5561 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005562 }
5563 if (allLTypes) return lhs;
5564 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005565
5566 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5567 EPI.ExtInfo = einfo;
5568 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005569 }
5570
5571 if (lproto) allRTypes = false;
5572 if (rproto) allLTypes = false;
5573
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005574 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005575 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005576 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005577 if (proto->isVariadic()) return QualType();
5578 // Check that the types are compatible with the types that
5579 // would result from default argument promotions (C99 6.7.5.3p15).
5580 // The only types actually affected are promotable integer
5581 // types and floats, which would be passed as a different
5582 // type depending on whether the prototype is visible.
5583 unsigned proto_nargs = proto->getNumArgs();
5584 for (unsigned i = 0; i < proto_nargs; ++i) {
5585 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005586
5587 // Look at the promotion type of enum types, since that is the type used
5588 // to pass enum values.
5589 if (const EnumType *Enum = argTy->getAs<EnumType>())
5590 argTy = Enum->getDecl()->getPromotionType();
5591
Eli Friedman47f77112008-08-22 00:56:42 +00005592 if (argTy->isPromotableIntegerType() ||
5593 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5594 return QualType();
5595 }
5596
5597 if (allLTypes) return lhs;
5598 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005599
5600 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5601 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005602 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005603 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005604 }
5605
5606 if (allLTypes) return lhs;
5607 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005608 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005609}
5610
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005611QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005612 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005613 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005614 // C++ [expr]: If an expression initially has the type "reference to T", the
5615 // type is adjusted to "T" prior to any further analysis, the expression
5616 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005617 // expression is an lvalue unless the reference is an rvalue reference and
5618 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005619 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5620 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005621
5622 if (Unqualified) {
5623 LHS = LHS.getUnqualifiedType();
5624 RHS = RHS.getUnqualifiedType();
5625 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005626
Eli Friedman47f77112008-08-22 00:56:42 +00005627 QualType LHSCan = getCanonicalType(LHS),
5628 RHSCan = getCanonicalType(RHS);
5629
5630 // If two types are identical, they are compatible.
5631 if (LHSCan == RHSCan)
5632 return LHS;
5633
John McCall8ccfcb52009-09-24 19:53:00 +00005634 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005635 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5636 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005637 if (LQuals != RQuals) {
5638 // If any of these qualifiers are different, we have a type
5639 // mismatch.
5640 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00005641 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5642 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00005643 return QualType();
5644
5645 // Exactly one GC qualifier difference is allowed: __strong is
5646 // okay if the other type has no GC qualifier but is an Objective
5647 // C object pointer (i.e. implicitly strong by default). We fix
5648 // this by pretending that the unqualified type was actually
5649 // qualified __strong.
5650 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5651 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5652 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5653
5654 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5655 return QualType();
5656
5657 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5658 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5659 }
5660 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5661 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5662 }
Eli Friedman47f77112008-08-22 00:56:42 +00005663 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005664 }
5665
5666 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005667
Eli Friedmandcca6332009-06-01 01:22:52 +00005668 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5669 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005670
Chris Lattnerfd652912008-01-14 05:45:46 +00005671 // We want to consider the two function types to be the same for these
5672 // comparisons, just force one to the other.
5673 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5674 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005675
5676 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005677 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5678 LHSClass = Type::ConstantArray;
5679 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5680 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005681
John McCall8b07ec22010-05-15 11:32:37 +00005682 // ObjCInterfaces are just specialized ObjCObjects.
5683 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5684 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5685
Nate Begemance4d7fc2008-04-18 23:10:10 +00005686 // Canonicalize ExtVector -> Vector.
5687 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5688 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005689
Chris Lattner95554662008-04-07 05:43:21 +00005690 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005691 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005692 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005693 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005694 // Compatibility is based on the underlying type, not the promotion
5695 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005696 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005697 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5698 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005699 }
John McCall9dd450b2009-09-21 23:43:11 +00005700 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005701 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5702 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005703 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005704
Eli Friedman47f77112008-08-22 00:56:42 +00005705 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005706 }
Eli Friedman47f77112008-08-22 00:56:42 +00005707
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005708 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005709 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005710#define TYPE(Class, Base)
5711#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005712#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005713#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5714#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5715#include "clang/AST/TypeNodes.def"
5716 assert(false && "Non-canonical and dependent types shouldn't get here");
5717 return QualType();
5718
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005719 case Type::LValueReference:
5720 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005721 case Type::MemberPointer:
5722 assert(false && "C++ should never be in mergeTypes");
5723 return QualType();
5724
John McCall8b07ec22010-05-15 11:32:37 +00005725 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005726 case Type::IncompleteArray:
5727 case Type::VariableArray:
5728 case Type::FunctionProto:
5729 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005730 assert(false && "Types are eliminated above");
5731 return QualType();
5732
Chris Lattnerfd652912008-01-14 05:45:46 +00005733 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005734 {
5735 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005736 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5737 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005738 if (Unqualified) {
5739 LHSPointee = LHSPointee.getUnqualifiedType();
5740 RHSPointee = RHSPointee.getUnqualifiedType();
5741 }
5742 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5743 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005744 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005745 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005746 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005747 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005748 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005749 return getPointerType(ResultType);
5750 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005751 case Type::BlockPointer:
5752 {
5753 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005754 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5755 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005756 if (Unqualified) {
5757 LHSPointee = LHSPointee.getUnqualifiedType();
5758 RHSPointee = RHSPointee.getUnqualifiedType();
5759 }
5760 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5761 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005762 if (ResultType.isNull()) return QualType();
5763 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5764 return LHS;
5765 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5766 return RHS;
5767 return getBlockPointerType(ResultType);
5768 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005769 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00005770 {
5771 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5772 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5773 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5774 return QualType();
5775
5776 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5777 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005778 if (Unqualified) {
5779 LHSElem = LHSElem.getUnqualifiedType();
5780 RHSElem = RHSElem.getUnqualifiedType();
5781 }
5782
5783 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005784 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00005785 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5786 return LHS;
5787 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5788 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00005789 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5790 ArrayType::ArraySizeModifier(), 0);
5791 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5792 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005793 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5794 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00005795 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5796 return LHS;
5797 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5798 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005799 if (LVAT) {
5800 // FIXME: This isn't correct! But tricky to implement because
5801 // the array's size has to be the size of LHS, but the type
5802 // has to be different.
5803 return LHS;
5804 }
5805 if (RVAT) {
5806 // FIXME: This isn't correct! But tricky to implement because
5807 // the array's size has to be the size of RHS, but the type
5808 // has to be different.
5809 return RHS;
5810 }
Eli Friedman3e62c212008-08-22 01:48:21 +00005811 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5812 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00005813 return getIncompleteArrayType(ResultType,
5814 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005815 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005816 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005817 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005818 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005819 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00005820 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00005821 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005822 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00005823 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00005824 case Type::Complex:
5825 // Distinct complex types are incompatible.
5826 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005827 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00005828 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00005829 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5830 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00005831 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00005832 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00005833 case Type::ObjCObject: {
5834 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00005835 // FIXME: This should be type compatibility, e.g. whether
5836 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00005837 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5838 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5839 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00005840 return LHS;
5841
Eli Friedman47f77112008-08-22 00:56:42 +00005842 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00005843 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005844 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005845 if (OfBlockPointer) {
5846 if (canAssignObjCInterfacesInBlockPointer(
5847 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005848 RHS->getAs<ObjCObjectPointerType>(),
5849 BlockReturnType))
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005850 return LHS;
5851 return QualType();
5852 }
John McCall9dd450b2009-09-21 23:43:11 +00005853 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5854 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005855 return LHS;
5856
Steve Naroffc68cfcf2008-12-10 22:14:21 +00005857 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005858 }
Steve Naroff32e44c02007-10-15 20:41:53 +00005859 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005860
5861 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005862}
Ted Kremenekfc581a92007-10-31 17:10:13 +00005863
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005864/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5865/// 'RHS' attributes and returns the merged version; including for function
5866/// return types.
5867QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5868 QualType LHSCan = getCanonicalType(LHS),
5869 RHSCan = getCanonicalType(RHS);
5870 // If two types are identical, they are compatible.
5871 if (LHSCan == RHSCan)
5872 return LHS;
5873 if (RHSCan->isFunctionType()) {
5874 if (!LHSCan->isFunctionType())
5875 return QualType();
5876 QualType OldReturnType =
5877 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5878 QualType NewReturnType =
5879 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5880 QualType ResReturnType =
5881 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5882 if (ResReturnType.isNull())
5883 return QualType();
5884 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5885 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5886 // In either case, use OldReturnType to build the new function type.
5887 const FunctionType *F = LHS->getAs<FunctionType>();
5888 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00005889 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5890 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005891 QualType ResultType
5892 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005893 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005894 return ResultType;
5895 }
5896 }
5897 return QualType();
5898 }
5899
5900 // If the qualifiers are different, the types can still be merged.
5901 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5902 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5903 if (LQuals != RQuals) {
5904 // If any of these qualifiers are different, we have a type mismatch.
5905 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5906 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5907 return QualType();
5908
5909 // Exactly one GC qualifier difference is allowed: __strong is
5910 // okay if the other type has no GC qualifier but is an Objective
5911 // C object pointer (i.e. implicitly strong by default). We fix
5912 // this by pretending that the unqualified type was actually
5913 // qualified __strong.
5914 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5915 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5916 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5917
5918 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5919 return QualType();
5920
5921 if (GC_L == Qualifiers::Strong)
5922 return LHS;
5923 if (GC_R == Qualifiers::Strong)
5924 return RHS;
5925 return QualType();
5926 }
5927
5928 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5929 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5930 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5931 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5932 if (ResQT == LHSBaseQT)
5933 return LHS;
5934 if (ResQT == RHSBaseQT)
5935 return RHS;
5936 }
5937 return QualType();
5938}
5939
Chris Lattner4ba0cef2008-04-07 07:01:58 +00005940//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005941// Integer Predicates
5942//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00005943
Jay Foad39c79802011-01-12 09:06:06 +00005944unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00005945 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00005946 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00005947 if (T->isBooleanType())
5948 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00005949 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005950 return (unsigned)getTypeSize(T);
5951}
5952
5953QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005954 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00005955
5956 // Turn <4 x signed int> -> <4 x unsigned int>
5957 if (const VectorType *VTy = T->getAs<VectorType>())
5958 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00005959 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00005960
5961 // For enums, we return the unsigned version of the base type.
5962 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005963 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00005964
5965 const BuiltinType *BTy = T->getAs<BuiltinType>();
5966 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005967 switch (BTy->getKind()) {
5968 case BuiltinType::Char_S:
5969 case BuiltinType::SChar:
5970 return UnsignedCharTy;
5971 case BuiltinType::Short:
5972 return UnsignedShortTy;
5973 case BuiltinType::Int:
5974 return UnsignedIntTy;
5975 case BuiltinType::Long:
5976 return UnsignedLongTy;
5977 case BuiltinType::LongLong:
5978 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00005979 case BuiltinType::Int128:
5980 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005981 default:
5982 assert(0 && "Unexpected signed integer type");
5983 return QualType();
5984 }
5985}
5986
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005987ASTMutationListener::~ASTMutationListener() { }
5988
Chris Lattnerecd79c62009-06-14 00:45:47 +00005989
5990//===----------------------------------------------------------------------===//
5991// Builtin Type Computation
5992//===----------------------------------------------------------------------===//
5993
5994/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00005995/// pointer over the consumed characters. This returns the resultant type. If
5996/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5997/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5998/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005999///
6000/// RequiresICE is filled in on return to indicate whether the value is required
6001/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006002static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006003 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006004 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006005 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006006 // Modifiers.
6007 int HowLong = 0;
6008 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006009 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006010
Chris Lattnerdc226c22010-10-01 22:42:38 +00006011 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006012 bool Done = false;
6013 while (!Done) {
6014 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006015 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006016 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006017 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006018 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006019 case 'S':
6020 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6021 assert(!Signed && "Can't use 'S' modifier multiple times!");
6022 Signed = true;
6023 break;
6024 case 'U':
6025 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6026 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6027 Unsigned = true;
6028 break;
6029 case 'L':
6030 assert(HowLong <= 2 && "Can't have LLLL modifier");
6031 ++HowLong;
6032 break;
6033 }
6034 }
6035
6036 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006037
Chris Lattnerecd79c62009-06-14 00:45:47 +00006038 // Read the base type.
6039 switch (*Str++) {
6040 default: assert(0 && "Unknown builtin type letter!");
6041 case 'v':
6042 assert(HowLong == 0 && !Signed && !Unsigned &&
6043 "Bad modifiers used with 'v'!");
6044 Type = Context.VoidTy;
6045 break;
6046 case 'f':
6047 assert(HowLong == 0 && !Signed && !Unsigned &&
6048 "Bad modifiers used with 'f'!");
6049 Type = Context.FloatTy;
6050 break;
6051 case 'd':
6052 assert(HowLong < 2 && !Signed && !Unsigned &&
6053 "Bad modifiers used with 'd'!");
6054 if (HowLong)
6055 Type = Context.LongDoubleTy;
6056 else
6057 Type = Context.DoubleTy;
6058 break;
6059 case 's':
6060 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6061 if (Unsigned)
6062 Type = Context.UnsignedShortTy;
6063 else
6064 Type = Context.ShortTy;
6065 break;
6066 case 'i':
6067 if (HowLong == 3)
6068 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6069 else if (HowLong == 2)
6070 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6071 else if (HowLong == 1)
6072 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6073 else
6074 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6075 break;
6076 case 'c':
6077 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6078 if (Signed)
6079 Type = Context.SignedCharTy;
6080 else if (Unsigned)
6081 Type = Context.UnsignedCharTy;
6082 else
6083 Type = Context.CharTy;
6084 break;
6085 case 'b': // boolean
6086 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6087 Type = Context.BoolTy;
6088 break;
6089 case 'z': // size_t.
6090 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6091 Type = Context.getSizeType();
6092 break;
6093 case 'F':
6094 Type = Context.getCFConstantStringType();
6095 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006096 case 'G':
6097 Type = Context.getObjCIdType();
6098 break;
6099 case 'H':
6100 Type = Context.getObjCSelType();
6101 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006102 case 'a':
6103 Type = Context.getBuiltinVaListType();
6104 assert(!Type.isNull() && "builtin va list type not initialized!");
6105 break;
6106 case 'A':
6107 // This is a "reference" to a va_list; however, what exactly
6108 // this means depends on how va_list is defined. There are two
6109 // different kinds of va_list: ones passed by value, and ones
6110 // passed by reference. An example of a by-value va_list is
6111 // x86, where va_list is a char*. An example of by-ref va_list
6112 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6113 // we want this argument to be a char*&; for x86-64, we want
6114 // it to be a __va_list_tag*.
6115 Type = Context.getBuiltinVaListType();
6116 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006117 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006118 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006119 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006120 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006121 break;
6122 case 'V': {
6123 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006124 unsigned NumElements = strtoul(Str, &End, 10);
6125 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006126 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006127
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006128 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6129 RequiresICE, false);
6130 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006131
6132 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006133 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006134 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006135 break;
6136 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006137 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006138 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6139 false);
6140 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006141 Type = Context.getComplexType(ElementType);
6142 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00006143 }
6144 case 'Y' : {
6145 Type = Context.getPointerDiffType();
6146 break;
6147 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006148 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006149 Type = Context.getFILEType();
6150 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006151 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006152 return QualType();
6153 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006154 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006155 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006156 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006157 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006158 else
6159 Type = Context.getjmp_bufType();
6160
Mike Stump2adb4da2009-07-28 23:47:15 +00006161 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006162 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006163 return QualType();
6164 }
6165 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006166 }
Mike Stump11289f42009-09-09 15:08:12 +00006167
Chris Lattnerdc226c22010-10-01 22:42:38 +00006168 // If there are modifiers and if we're allowed to parse them, go for it.
6169 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006170 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006171 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006172 default: Done = true; --Str; break;
6173 case '*':
6174 case '&': {
6175 // Both pointers and references can have their pointee types
6176 // qualified with an address space.
6177 char *End;
6178 unsigned AddrSpace = strtoul(Str, &End, 10);
6179 if (End != Str && AddrSpace != 0) {
6180 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6181 Str = End;
6182 }
6183 if (c == '*')
6184 Type = Context.getPointerType(Type);
6185 else
6186 Type = Context.getLValueReferenceType(Type);
6187 break;
6188 }
6189 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6190 case 'C':
6191 Type = Type.withConst();
6192 break;
6193 case 'D':
6194 Type = Context.getVolatileType(Type);
6195 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006196 }
6197 }
Chris Lattner84733392010-10-01 07:13:18 +00006198
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006199 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006200 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006201
Chris Lattnerecd79c62009-06-14 00:45:47 +00006202 return Type;
6203}
6204
6205/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006206QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006207 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006208 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006209 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006210
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006211 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006212
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006213 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006214 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006215 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6216 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006217 if (Error != GE_None)
6218 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006219
6220 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6221
Chris Lattnerecd79c62009-06-14 00:45:47 +00006222 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006223 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006224 if (Error != GE_None)
6225 return QualType();
6226
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006227 // If this argument is required to be an IntegerConstantExpression and the
6228 // caller cares, fill in the bitmask we return.
6229 if (RequiresICE && IntegerConstantArgs)
6230 *IntegerConstantArgs |= 1 << ArgTypes.size();
6231
Chris Lattnerecd79c62009-06-14 00:45:47 +00006232 // Do array -> pointer decay. The builtin should use the decayed type.
6233 if (Ty->isArrayType())
6234 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006235
Chris Lattnerecd79c62009-06-14 00:45:47 +00006236 ArgTypes.push_back(Ty);
6237 }
6238
6239 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6240 "'.' should only occur at end of builtin type list!");
6241
John McCall991eb4b2010-12-21 00:44:39 +00006242 FunctionType::ExtInfo EI;
6243 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6244
6245 bool Variadic = (TypeStr[0] == '.');
6246
6247 // We really shouldn't be making a no-proto type here, especially in C++.
6248 if (ArgTypes.empty() && Variadic)
6249 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006250
John McCalldb40c7f2010-12-14 08:05:40 +00006251 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006252 EPI.ExtInfo = EI;
6253 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006254
6255 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006256}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006257
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006258GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6259 GVALinkage External = GVA_StrongExternal;
6260
6261 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006262 switch (L) {
6263 case NoLinkage:
6264 case InternalLinkage:
6265 case UniqueExternalLinkage:
6266 return GVA_Internal;
6267
6268 case ExternalLinkage:
6269 switch (FD->getTemplateSpecializationKind()) {
6270 case TSK_Undeclared:
6271 case TSK_ExplicitSpecialization:
6272 External = GVA_StrongExternal;
6273 break;
6274
6275 case TSK_ExplicitInstantiationDefinition:
6276 return GVA_ExplicitTemplateInstantiation;
6277
6278 case TSK_ExplicitInstantiationDeclaration:
6279 case TSK_ImplicitInstantiation:
6280 External = GVA_TemplateInstantiation;
6281 break;
6282 }
6283 }
6284
6285 if (!FD->isInlined())
6286 return External;
6287
6288 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6289 // GNU or C99 inline semantics. Determine whether this symbol should be
6290 // externally visible.
6291 if (FD->isInlineDefinitionExternallyVisible())
6292 return External;
6293
6294 // C99 inline semantics, where the symbol is not externally visible.
6295 return GVA_C99Inline;
6296 }
6297
6298 // C++0x [temp.explicit]p9:
6299 // [ Note: The intent is that an inline function that is the subject of
6300 // an explicit instantiation declaration will still be implicitly
6301 // instantiated when used so that the body can be considered for
6302 // inlining, but that no out-of-line copy of the inline function would be
6303 // generated in the translation unit. -- end note ]
6304 if (FD->getTemplateSpecializationKind()
6305 == TSK_ExplicitInstantiationDeclaration)
6306 return GVA_C99Inline;
6307
6308 return GVA_CXXInline;
6309}
6310
6311GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6312 // If this is a static data member, compute the kind of template
6313 // specialization. Otherwise, this variable is not part of a
6314 // template.
6315 TemplateSpecializationKind TSK = TSK_Undeclared;
6316 if (VD->isStaticDataMember())
6317 TSK = VD->getTemplateSpecializationKind();
6318
6319 Linkage L = VD->getLinkage();
6320 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6321 VD->getType()->getLinkage() == UniqueExternalLinkage)
6322 L = UniqueExternalLinkage;
6323
6324 switch (L) {
6325 case NoLinkage:
6326 case InternalLinkage:
6327 case UniqueExternalLinkage:
6328 return GVA_Internal;
6329
6330 case ExternalLinkage:
6331 switch (TSK) {
6332 case TSK_Undeclared:
6333 case TSK_ExplicitSpecialization:
6334 return GVA_StrongExternal;
6335
6336 case TSK_ExplicitInstantiationDeclaration:
6337 llvm_unreachable("Variable should not be instantiated");
6338 // Fall through to treat this like any other instantiation.
6339
6340 case TSK_ExplicitInstantiationDefinition:
6341 return GVA_ExplicitTemplateInstantiation;
6342
6343 case TSK_ImplicitInstantiation:
6344 return GVA_TemplateInstantiation;
6345 }
6346 }
6347
6348 return GVA_StrongExternal;
6349}
6350
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00006351bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006352 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6353 if (!VD->isFileVarDecl())
6354 return false;
6355 } else if (!isa<FunctionDecl>(D))
6356 return false;
6357
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006358 // Weak references don't produce any output by themselves.
6359 if (D->hasAttr<WeakRefAttr>())
6360 return false;
6361
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006362 // Aliases and used decls are required.
6363 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6364 return true;
6365
6366 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6367 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00006368 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00006369 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006370
6371 // Constructors and destructors are required.
6372 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6373 return true;
6374
6375 // The key function for a class is required.
6376 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6377 const CXXRecordDecl *RD = MD->getParent();
6378 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6379 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6380 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6381 return true;
6382 }
6383 }
6384
6385 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6386
6387 // static, static inline, always_inline, and extern inline functions can
6388 // always be deferred. Normal inline functions can be deferred in C99/C++.
6389 // Implicit template instantiations can also be deferred in C++.
6390 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6391 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6392 return false;
6393 return true;
6394 }
6395
6396 const VarDecl *VD = cast<VarDecl>(D);
6397 assert(VD->isFileVarDecl() && "Expected file scoped var");
6398
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006399 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6400 return false;
6401
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006402 // Structs that have non-trivial constructors or destructors are required.
6403
6404 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00006405 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006406 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6407 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00006408 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6409 RD->hasTrivialCopyConstructor() &&
6410 RD->hasTrivialMoveConstructor() &&
6411 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006412 return true;
6413 }
6414 }
6415
6416 GVALinkage L = GetGVALinkageForVariable(VD);
6417 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6418 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6419 return false;
6420 }
6421
6422 return true;
6423}
Charles Davis53c59df2010-08-16 03:33:14 +00006424
Charles Davis99202b32010-11-09 18:04:24 +00006425CallingConv ASTContext::getDefaultMethodCallConv() {
6426 // Pass through to the C++ ABI object
6427 return ABI->getDefaultMethodCallConv();
6428}
6429
Jay Foad39c79802011-01-12 09:06:06 +00006430bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00006431 // Pass through to the C++ ABI object
6432 return ABI->isNearlyEmpty(RD);
6433}
6434
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006435MangleContext *ASTContext::createMangleContext() {
6436 switch (Target.getCXXABI()) {
6437 case CXXABI_ARM:
6438 case CXXABI_Itanium:
6439 return createItaniumMangleContext(*this, getDiagnostics());
6440 case CXXABI_Microsoft:
6441 return createMicrosoftMangleContext(*this, getDiagnostics());
6442 }
6443 assert(0 && "Unsupported ABI");
6444 return 0;
6445}
6446
Charles Davis53c59df2010-08-16 03:33:14 +00006447CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006448
6449size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00006450 return ASTRecordLayouts.getMemorySize()
6451 + llvm::capacity_in_bytes(ObjCLayouts)
6452 + llvm::capacity_in_bytes(KeyFunctions)
6453 + llvm::capacity_in_bytes(ObjCImpls)
6454 + llvm::capacity_in_bytes(BlockVarCopyInits)
6455 + llvm::capacity_in_bytes(DeclAttrs)
6456 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6457 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6458 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6459 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6460 + llvm::capacity_in_bytes(OverriddenMethods)
6461 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006462 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00006463 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006464}