blob: e122df9d23527e752ddf5e0460a74fbdd6744a22 [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 {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000053 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000054};
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 }
David Blaikie8a40f702012-01-17 06:56:22 +0000196 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000197}
198
Douglas Gregore8bbc122011-09-02 00:18:52 +0000199static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000200 const LangOptions &LOpts) {
201 if (LOpts.FakeAddressSpaceMap) {
202 // The fake address space map must have a distinct entry for each
203 // language-specific address space.
204 static const unsigned FakeAddrSpaceMap[] = {
205 1, // opencl_global
206 2, // opencl_local
207 3 // opencl_constant
208 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000209 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000210 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000211 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000212 }
213}
214
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000215ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +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 Gregore8bbc122011-09-02 00:18:52 +0000219 unsigned size_reserve,
220 bool DelayInitialization)
221 : FunctionProtoTypes(this_()),
222 TemplateSpecializationTypes(this_()),
223 DependentTemplateSpecializationTypes(this_()),
224 SubstTemplateTemplateParmPacks(this_()),
225 GlobalNestedNameSpecifier(0),
226 Int128Decl(0), UInt128Decl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000227 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000228 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000229 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000230 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
231 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
232 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000233 NullTypeSourceInfo(QualType()),
234 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000235 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000236 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000237 Idents(idents), Selectors(sels),
238 BuiltinInfo(builtins),
239 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000240 ExternalSource(0), Listener(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000241 LastSDM(0, 0),
242 UniqueBlockByRefTypeID(0)
243{
Mike Stump11289f42009-09-09 15:08:12 +0000244 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000245 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000246
247 if (!DelayInitialization) {
248 assert(t && "No target supplied for ASTContext initialization");
249 InitBuiltinTypes(*t);
250 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000251}
252
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000253ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000254 // Release the DenseMaps associated with DeclContext objects.
255 // FIXME: Is this the ideal solution?
256 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000257
Douglas Gregor5b11d492010-07-25 17:53:33 +0000258 // Call all of the deallocation functions.
259 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
260 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000261
Ted Kremenek076baeb2010-06-08 23:00:58 +0000262 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000263 // because they can contain DenseMaps.
264 for (llvm::DenseMap<const ObjCContainerDecl*,
265 const ASTRecordLayout*>::iterator
266 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
267 // Increment in loop to prevent using deallocated memory.
268 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
269 R->Destroy(*this);
270
Ted Kremenek076baeb2010-06-08 23:00:58 +0000271 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
272 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
273 // Increment in loop to prevent using deallocated memory.
274 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
275 R->Destroy(*this);
276 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000277
278 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
279 AEnd = DeclAttrs.end();
280 A != AEnd; ++A)
281 A->second->~AttrVec();
282}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000283
Douglas Gregor1a809332010-05-23 18:26:36 +0000284void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
285 Deallocations.push_back(std::make_pair(Callback, Data));
286}
287
Mike Stump11289f42009-09-09 15:08:12 +0000288void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000289ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000290 ExternalSource.reset(Source.take());
291}
292
Chris Lattner4eb445d2007-01-26 01:27:23 +0000293void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000294 llvm::errs() << "\n*** AST Context Stats:\n";
295 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000296
Douglas Gregora30d0462009-05-26 14:40:08 +0000297 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000298#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000299#define ABSTRACT_TYPE(Name, Parent)
300#include "clang/AST/TypeNodes.def"
301 0 // Extra
302 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000303
Chris Lattner4eb445d2007-01-26 01:27:23 +0000304 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
305 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000306 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000307 }
308
Douglas Gregora30d0462009-05-26 14:40:08 +0000309 unsigned Idx = 0;
310 unsigned TotalBytes = 0;
311#define TYPE(Name, Parent) \
312 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000313 llvm::errs() << " " << counts[Idx] << " " << #Name \
314 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000315 TotalBytes += counts[Idx] * sizeof(Name##Type); \
316 ++Idx;
317#define ABSTRACT_TYPE(Name, Parent)
318#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000319
Chandler Carruth3c147a72011-07-04 05:32:14 +0000320 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
321
Douglas Gregor7454c562010-07-02 20:37:36 +0000322 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000323 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
324 << NumImplicitDefaultConstructors
325 << " implicit default constructors created\n";
326 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
327 << NumImplicitCopyConstructors
328 << " implicit copy constructors created\n";
Alexis Huntfcaeae42011-05-25 20:50:04 +0000329 if (getLangOptions().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000330 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
331 << NumImplicitMoveConstructors
332 << " implicit move constructors created\n";
333 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
334 << NumImplicitCopyAssignmentOperators
335 << " implicit copy assignment operators created\n";
Alexis Huntfcaeae42011-05-25 20:50:04 +0000336 if (getLangOptions().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000337 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
338 << NumImplicitMoveAssignmentOperators
339 << " implicit move assignment operators created\n";
340 llvm::errs() << NumImplicitDestructorsDeclared << "/"
341 << NumImplicitDestructors
342 << " implicit destructors created\n";
343
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000344 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000345 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000346 ExternalSource->PrintStats();
347 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000348
Douglas Gregor5b11d492010-07-25 17:53:33 +0000349 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000350}
351
Douglas Gregor801c99d2011-08-12 06:49:56 +0000352TypedefDecl *ASTContext::getInt128Decl() const {
353 if (!Int128Decl) {
354 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
355 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
356 getTranslationUnitDecl(),
357 SourceLocation(),
358 SourceLocation(),
359 &Idents.get("__int128_t"),
360 TInfo);
361 }
362
363 return Int128Decl;
364}
365
366TypedefDecl *ASTContext::getUInt128Decl() const {
367 if (!UInt128Decl) {
368 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
369 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
370 getTranslationUnitDecl(),
371 SourceLocation(),
372 SourceLocation(),
373 &Idents.get("__uint128_t"),
374 TInfo);
375 }
376
377 return UInt128Decl;
378}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000379
John McCall48f2d582009-10-23 23:03:21 +0000380void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000381 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000382 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000383 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000384}
385
Douglas Gregore8bbc122011-09-02 00:18:52 +0000386void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
387 assert((!this->Target || this->Target == &Target) &&
388 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000389 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000390
Douglas Gregore8bbc122011-09-02 00:18:52 +0000391 this->Target = &Target;
392
393 ABI.reset(createCXXABI(Target));
394 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
395
Chris Lattner970e54e2006-11-12 00:37:36 +0000396 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000397 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000398
Chris Lattner970e54e2006-11-12 00:37:36 +0000399 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000400 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000401 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000402 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000403 InitBuiltinType(CharTy, BuiltinType::Char_S);
404 else
405 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000406 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000407 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
408 InitBuiltinType(ShortTy, BuiltinType::Short);
409 InitBuiltinType(IntTy, BuiltinType::Int);
410 InitBuiltinType(LongTy, BuiltinType::Long);
411 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000412
Chris Lattner970e54e2006-11-12 00:37:36 +0000413 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000414 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
415 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
416 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
417 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
418 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000419
Chris Lattner970e54e2006-11-12 00:37:36 +0000420 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000421 InitBuiltinType(FloatTy, BuiltinType::Float);
422 InitBuiltinType(DoubleTy, BuiltinType::Double);
423 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000424
Chris Lattnerf122cef2009-04-30 02:43:43 +0000425 // GNU extension, 128-bit integers.
426 InitBuiltinType(Int128Ty, BuiltinType::Int128);
427 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
428
Chris Lattnerad3467e2010-12-25 23:25:43 +0000429 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000430 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000431 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
432 else // -fshort-wchar makes wchar_t be unsigned.
433 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
434 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000435 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000436
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000437 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
438 InitBuiltinType(Char16Ty, BuiltinType::Char16);
439 else // C99
440 Char16Ty = getFromTargetType(Target.getChar16Type());
441
442 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
443 InitBuiltinType(Char32Ty, BuiltinType::Char32);
444 else // C99
445 Char32Ty = getFromTargetType(Target.getChar32Type());
446
Douglas Gregor4619e432008-12-05 23:32:09 +0000447 // Placeholder type for type-dependent expressions whose type is
448 // completely unknown. No code should ever check a type against
449 // DependentTy and users should never see it; however, it is here to
450 // help diagnose failures to properly check for type-dependent
451 // expressions.
452 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000453
John McCall36e7fe32010-10-12 00:20:44 +0000454 // Placeholder type for functions.
455 InitBuiltinType(OverloadTy, BuiltinType::Overload);
456
John McCall0009fcc2011-04-26 20:42:42 +0000457 // Placeholder type for bound members.
458 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
459
John McCall526ab472011-10-25 17:37:35 +0000460 // Placeholder type for pseudo-objects.
461 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
462
John McCall31996342011-04-07 08:22:57 +0000463 // "any" type; useful for debugger-like clients.
464 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
465
John McCall8a6b59a2011-10-17 18:09:15 +0000466 // Placeholder type for unbridged ARC casts.
467 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
468
Chris Lattner970e54e2006-11-12 00:37:36 +0000469 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000470 FloatComplexTy = getComplexType(FloatTy);
471 DoubleComplexTy = getComplexType(DoubleTy);
472 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000473
Steve Naroff66e9f332007-10-15 14:41:52 +0000474 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000475
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000476 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000477 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
478 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000479 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000480
481 // Builtin type for __objc_yes and __objc_no
482 ObjCBuiltinBoolTy = SignedCharTy;
483
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000484 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000485
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000486 // void * type
487 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000488
489 // nullptr type (C++0x 2.14.7)
490 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000491
492 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
493 InitBuiltinType(HalfTy, BuiltinType::Half);
Chris Lattner970e54e2006-11-12 00:37:36 +0000494}
495
David Blaikie9c902b52011-09-25 23:23:43 +0000496DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000497 return SourceMgr.getDiagnostics();
498}
499
Douglas Gregor561eceb2010-08-30 16:49:28 +0000500AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
501 AttrVec *&Result = DeclAttrs[D];
502 if (!Result) {
503 void *Mem = Allocate(sizeof(AttrVec));
504 Result = new (Mem) AttrVec;
505 }
506
507 return *Result;
508}
509
510/// \brief Erase the attributes corresponding to the given declaration.
511void ASTContext::eraseDeclAttrs(const Decl *D) {
512 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
513 if (Pos != DeclAttrs.end()) {
514 Pos->second->~AttrVec();
515 DeclAttrs.erase(Pos);
516 }
517}
518
Douglas Gregor86d142a2009-10-08 07:24:58 +0000519MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000520ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000521 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000522 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000523 = InstantiatedFromStaticDataMember.find(Var);
524 if (Pos == InstantiatedFromStaticDataMember.end())
525 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000526
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000527 return Pos->second;
528}
529
Mike Stump11289f42009-09-09 15:08:12 +0000530void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000531ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000532 TemplateSpecializationKind TSK,
533 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000534 assert(Inst->isStaticDataMember() && "Not a static data member");
535 assert(Tmpl->isStaticDataMember() && "Not a static data member");
536 assert(!InstantiatedFromStaticDataMember[Inst] &&
537 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000538 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000539 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000540}
541
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000542FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
543 const FunctionDecl *FD){
544 assert(FD && "Specialization is 0");
545 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000546 = ClassScopeSpecializationPattern.find(FD);
547 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000548 return 0;
549
550 return Pos->second;
551}
552
553void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
554 FunctionDecl *Pattern) {
555 assert(FD && "Specialization is 0");
556 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000557 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000558}
559
John McCalle61f2ba2009-11-18 02:36:19 +0000560NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000561ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000562 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000563 = InstantiatedFromUsingDecl.find(UUD);
564 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000565 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000566
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000567 return Pos->second;
568}
569
570void
John McCallb96ec562009-12-04 22:46:56 +0000571ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
572 assert((isa<UsingDecl>(Pattern) ||
573 isa<UnresolvedUsingValueDecl>(Pattern) ||
574 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
575 "pattern decl is not a using decl");
576 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
577 InstantiatedFromUsingDecl[Inst] = Pattern;
578}
579
580UsingShadowDecl *
581ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
582 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
583 = InstantiatedFromUsingShadowDecl.find(Inst);
584 if (Pos == InstantiatedFromUsingShadowDecl.end())
585 return 0;
586
587 return Pos->second;
588}
589
590void
591ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
592 UsingShadowDecl *Pattern) {
593 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
594 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000595}
596
Anders Carlsson5da84842009-09-01 04:26:58 +0000597FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
598 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
599 = InstantiatedFromUnnamedFieldDecl.find(Field);
600 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
601 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000602
Anders Carlsson5da84842009-09-01 04:26:58 +0000603 return Pos->second;
604}
605
606void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
607 FieldDecl *Tmpl) {
608 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
609 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
610 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
611 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000612
Anders Carlsson5da84842009-09-01 04:26:58 +0000613 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
614}
615
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000616bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
617 const FieldDecl *LastFD) const {
618 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000619 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000620}
621
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000622bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
623 const FieldDecl *LastFD) const {
624 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000625 FD->getBitWidthValue(*this) == 0 &&
626 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000627}
628
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000629bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
630 const FieldDecl *LastFD) const {
631 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000632 FD->getBitWidthValue(*this) &&
633 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000634}
635
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000636bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000637 const FieldDecl *LastFD) const {
638 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000639 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000640}
641
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000642bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000643 const FieldDecl *LastFD) const {
644 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000645 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000646}
647
Douglas Gregor832940b2010-03-02 23:58:15 +0000648ASTContext::overridden_cxx_method_iterator
649ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
650 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
651 = OverriddenMethods.find(Method);
652 if (Pos == OverriddenMethods.end())
653 return 0;
654
655 return Pos->second.begin();
656}
657
658ASTContext::overridden_cxx_method_iterator
659ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
660 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
661 = OverriddenMethods.find(Method);
662 if (Pos == OverriddenMethods.end())
663 return 0;
664
665 return Pos->second.end();
666}
667
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000668unsigned
669ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
670 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
671 = OverriddenMethods.find(Method);
672 if (Pos == OverriddenMethods.end())
673 return 0;
674
675 return Pos->second.size();
676}
677
Douglas Gregor832940b2010-03-02 23:58:15 +0000678void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
679 const CXXMethodDecl *Overridden) {
680 OverriddenMethods[Method].push_back(Overridden);
681}
682
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000683void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
684 assert(!Import->NextLocalImport && "Import declaration already in the chain");
685 assert(!Import->isFromASTFile() && "Non-local import declaration");
686 if (!FirstLocalImport) {
687 FirstLocalImport = Import;
688 LastLocalImport = Import;
689 return;
690 }
691
692 LastLocalImport->NextLocalImport = Import;
693 LastLocalImport = Import;
694}
695
Chris Lattner53cfe802007-07-18 17:52:12 +0000696//===----------------------------------------------------------------------===//
697// Type Sizing and Analysis
698//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000699
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000700/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
701/// scalar floating point type.
702const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000703 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000704 assert(BT && "Not a floating point type!");
705 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000706 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000707 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +0000708 case BuiltinType::Float: return Target->getFloatFormat();
709 case BuiltinType::Double: return Target->getDoubleFormat();
710 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000711 }
712}
713
Ken Dyck160146e2010-01-27 17:10:57 +0000714/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000715/// specified decl. Note that bitfields do not have a valid alignment, so
716/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000717/// If @p RefAsPointee, references are treated like their underlying type
718/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000719CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000720 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +0000721
John McCall94268702010-10-08 18:24:19 +0000722 bool UseAlignAttrOnly = false;
723 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
724 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000725
John McCall94268702010-10-08 18:24:19 +0000726 // __attribute__((aligned)) can increase or decrease alignment
727 // *except* on a struct or struct member, where it only increases
728 // alignment unless 'packed' is also specified.
729 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +0000730 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +0000731 // ignore that possibility; Sema should diagnose it.
732 if (isa<FieldDecl>(D)) {
733 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
734 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
735 } else {
736 UseAlignAttrOnly = true;
737 }
738 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000739 else if (isa<FieldDecl>(D))
740 UseAlignAttrOnly =
741 D->hasAttr<PackedAttr>() ||
742 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000743
John McCall4e819612011-01-20 07:57:12 +0000744 // If we're using the align attribute only, just ignore everything
745 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000746 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000747 // do nothing
748
John McCall94268702010-10-08 18:24:19 +0000749 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000750 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000751 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000752 if (RefAsPointee)
753 T = RT->getPointeeType();
754 else
755 T = getPointerType(RT->getPointeeType());
756 }
757 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000758 // Adjust alignments of declarations with array type by the
759 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +0000760 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000761 const ArrayType *arrayType;
762 if (MinWidth && (arrayType = getAsArrayType(T))) {
763 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000764 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +0000765 else if (isa<ConstantArrayType>(arrayType) &&
766 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000767 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000768
John McCall33ddac02011-01-19 10:06:00 +0000769 // Walk through any array types while we're at it.
770 T = getBaseElementType(arrayType);
771 }
Chad Rosier99ee7822011-07-26 07:03:04 +0000772 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +0000773 }
John McCall4e819612011-01-20 07:57:12 +0000774
775 // Fields can be subject to extra alignment constraints, like if
776 // the field is packed, the struct is packed, or the struct has a
777 // a max-field-alignment constraint (#pragma pack). So calculate
778 // the actual alignment of the field within the struct, and then
779 // (as we're expected to) constrain that by the alignment of the type.
780 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
781 // So calculate the alignment of the field.
782 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
783
784 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000785 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000786
787 // Use the GCD of that and the offset within the record.
788 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
789 if (offset > 0) {
790 // Alignment is always a power of 2, so the GCD will be a power of 2,
791 // which means we get to do this crazy thing instead of Euclid's.
792 uint64_t lowBitOfOffset = offset & (~offset + 1);
793 if (lowBitOfOffset < fieldAlign)
794 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
795 }
796
797 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000798 }
Chris Lattner68061312009-01-24 21:53:27 +0000799 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000800
Ken Dyckcc56c542011-01-15 18:38:59 +0000801 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000802}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000803
John McCall87fe5d52010-05-20 01:18:31 +0000804std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000805ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000806 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000807 return std::make_pair(toCharUnitsFromBits(Info.first),
808 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000809}
810
811std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000812ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000813 return getTypeInfoInChars(T.getTypePtr());
814}
815
Chris Lattner983a8bb2007-07-13 22:13:22 +0000816/// getTypeSize - Return the size of the specified type, in bits. This method
817/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000818///
819/// FIXME: Pointers into different addr spaces could have different sizes and
820/// alignment requirements: getPointerInfo should take an AddrSpace, this
821/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000822std::pair<uint64_t, unsigned>
Jay Foad39c79802011-01-12 09:06:06 +0000823ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000824 uint64_t Width=0;
825 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000826 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000827#define TYPE(Class, Base)
828#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000829#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000830#define DEPENDENT_TYPE(Class, Base) case Type::Class:
831#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +0000832 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000833
Chris Lattner355332d2007-07-13 22:27:08 +0000834 case Type::FunctionNoProto:
835 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000836 // GCC extension: alignof(function) = 32 bits
837 Width = 0;
838 Align = 32;
839 break;
840
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000841 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000842 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000843 Width = 0;
844 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
845 break;
846
Steve Naroff5c131802007-08-30 01:06:46 +0000847 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000848 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000849
Chris Lattner37e05872008-03-05 18:54:05 +0000850 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +0000851 uint64_t Size = CAT->getSize().getZExtValue();
852 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) && "Overflow in array type bit size evaluation");
853 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000854 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +0000855 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000856 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000857 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000858 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000859 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000860 const VectorType *VT = cast<VectorType>(T);
861 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
862 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000863 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000864 // If the alignment is not a power of 2, round up to the next power of 2.
865 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000866 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000867 Align = llvm::NextPowerOf2(Align);
868 Width = llvm::RoundUpToAlignment(Width, Align);
869 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000870 break;
871 }
Chris Lattner647fb222007-07-18 18:26:58 +0000872
Chris Lattner7570e9c2008-03-08 08:52:55 +0000873 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000874 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000875 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000876 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000877 // GCC extension: alignof(void) = 8 bits.
878 Width = 0;
879 Align = 8;
880 break;
881
Chris Lattner6a4f7452007-12-19 19:23:28 +0000882 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000883 Width = Target->getBoolWidth();
884 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000885 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000886 case BuiltinType::Char_S:
887 case BuiltinType::Char_U:
888 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000889 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000890 Width = Target->getCharWidth();
891 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000892 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000893 case BuiltinType::WChar_S:
894 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000895 Width = Target->getWCharWidth();
896 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000897 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000898 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000899 Width = Target->getChar16Width();
900 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000901 break;
902 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000903 Width = Target->getChar32Width();
904 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000905 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000906 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000907 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000908 Width = Target->getShortWidth();
909 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000910 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000911 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000912 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000913 Width = Target->getIntWidth();
914 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000915 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000916 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000917 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000918 Width = Target->getLongWidth();
919 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000920 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000921 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000922 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000923 Width = Target->getLongLongWidth();
924 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000925 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000926 case BuiltinType::Int128:
927 case BuiltinType::UInt128:
928 Width = 128;
929 Align = 128; // int128_t is 128-bit aligned on all targets.
930 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000931 case BuiltinType::Half:
932 Width = Target->getHalfWidth();
933 Align = Target->getHalfAlign();
934 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000935 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000936 Width = Target->getFloatWidth();
937 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000938 break;
939 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000940 Width = Target->getDoubleWidth();
941 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000942 break;
943 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000944 Width = Target->getLongDoubleWidth();
945 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000946 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000947 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000948 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
949 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000950 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000951 case BuiltinType::ObjCId:
952 case BuiltinType::ObjCClass:
953 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000954 Width = Target->getPointerWidth(0);
955 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000956 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000957 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000958 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000959 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000960 Width = Target->getPointerWidth(0);
961 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000962 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000963 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000964 unsigned AS = getTargetAddressSpace(
965 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000966 Width = Target->getPointerWidth(AS);
967 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +0000968 break;
969 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000970 case Type::LValueReference:
971 case Type::RValueReference: {
972 // alignof and sizeof should never enter this code path here, so we go
973 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000974 unsigned AS = getTargetAddressSpace(
975 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000976 Width = Target->getPointerWidth(AS);
977 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000978 break;
979 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000980 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000981 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000982 Width = Target->getPointerWidth(AS);
983 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000984 break;
985 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000986 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000987 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000988 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000989 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000990 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000991 Align = PtrDiffInfo.second;
992 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000993 }
Chris Lattner647fb222007-07-18 18:26:58 +0000994 case Type::Complex: {
995 // Complex types have the same alignment as their elements, but twice the
996 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000997 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000998 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000999 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001000 Align = EltInfo.second;
1001 break;
1002 }
John McCall8b07ec22010-05-15 11:32:37 +00001003 case Type::ObjCObject:
1004 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001005 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001006 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001007 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001008 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001009 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001010 break;
1011 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001012 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001013 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001014 const TagType *TT = cast<TagType>(T);
1015
1016 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001017 Width = 8;
1018 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001019 break;
1020 }
Mike Stump11289f42009-09-09 15:08:12 +00001021
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001022 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001023 return getTypeInfo(ET->getDecl()->getIntegerType());
1024
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001025 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001026 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001027 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001028 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001029 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001030 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001031
Chris Lattner63d2b362009-10-22 05:17:15 +00001032 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001033 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1034 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001035
Richard Smith30482bc2011-02-20 03:19:35 +00001036 case Type::Auto: {
1037 const AutoType *A = cast<AutoType>(T);
1038 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001039 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001040 }
1041
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001042 case Type::Paren:
1043 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1044
Douglas Gregoref462e62009-04-30 17:32:17 +00001045 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001046 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001047 std::pair<uint64_t, unsigned> Info
1048 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001049 // If the typedef has an aligned attribute on it, it overrides any computed
1050 // alignment we have. This violates the GCC documentation (which says that
1051 // attribute(aligned) can only round up) but matches its implementation.
1052 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1053 Align = AttrAlign;
1054 else
1055 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001056 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001057 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001058 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001059
1060 case Type::TypeOfExpr:
1061 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1062 .getTypePtr());
1063
1064 case Type::TypeOf:
1065 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1066
Anders Carlsson81df7b82009-06-24 19:06:50 +00001067 case Type::Decltype:
1068 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1069 .getTypePtr());
1070
Alexis Hunte852b102011-05-24 22:41:36 +00001071 case Type::UnaryTransform:
1072 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1073
Abramo Bagnara6150c882010-05-11 21:36:43 +00001074 case Type::Elaborated:
1075 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001076
John McCall81904512011-01-06 01:58:22 +00001077 case Type::Attributed:
1078 return getTypeInfo(
1079 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1080
Richard Smith3f1b5d02011-05-05 21:57:07 +00001081 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001082 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001083 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001084 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1085 // A type alias template specialization may refer to a typedef with the
1086 // aligned attribute on it.
1087 if (TST->isTypeAlias())
1088 return getTypeInfo(TST->getAliasedType().getTypePtr());
1089 else
1090 return getTypeInfo(getCanonicalType(T));
1091 }
1092
Eli Friedman0dfb8892011-10-06 23:00:33 +00001093 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001094 std::pair<uint64_t, unsigned> Info
1095 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1096 Width = Info.first;
1097 Align = Info.second;
1098 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1099 llvm::isPowerOf2_64(Width)) {
1100 // We can potentially perform lock-free atomic operations for this
1101 // type; promote the alignment appropriately.
1102 // FIXME: We could potentially promote the width here as well...
1103 // is that worthwhile? (Non-struct atomic types generally have
1104 // power-of-two size anyway, but structs might not. Requires a bit
1105 // of implementation work to make sure we zero out the extra bits.)
1106 Align = static_cast<unsigned>(Width);
1107 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001108 }
1109
Douglas Gregoref462e62009-04-30 17:32:17 +00001110 }
Mike Stump11289f42009-09-09 15:08:12 +00001111
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001112 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001113 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001114}
1115
Ken Dyckcc56c542011-01-15 18:38:59 +00001116/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1117CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1118 return CharUnits::fromQuantity(BitSize / getCharWidth());
1119}
1120
Ken Dyckb0fcc592011-02-11 01:54:29 +00001121/// toBits - Convert a size in characters to a size in characters.
1122int64_t ASTContext::toBits(CharUnits CharSize) const {
1123 return CharSize.getQuantity() * getCharWidth();
1124}
1125
Ken Dyck8c89d592009-12-22 14:23:30 +00001126/// getTypeSizeInChars - Return the size of the specified type, in characters.
1127/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001128CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001129 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001130}
Jay Foad39c79802011-01-12 09:06:06 +00001131CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001132 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001133}
1134
Ken Dycka6046ab2010-01-26 17:25:18 +00001135/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001136/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001137CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001138 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001139}
Jay Foad39c79802011-01-12 09:06:06 +00001140CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001141 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001142}
1143
Chris Lattnera3402cd2009-01-27 18:08:34 +00001144/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1145/// type for the current target in bits. This can be different than the ABI
1146/// alignment in cases where it is beneficial for performance to overalign
1147/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001148unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001149 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001150
1151 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001152 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001153 T = CT->getElementType().getTypePtr();
1154 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1155 T->isSpecificBuiltinType(BuiltinType::LongLong))
1156 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1157
Chris Lattnera3402cd2009-01-27 18:08:34 +00001158 return ABIAlign;
1159}
1160
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001161/// DeepCollectObjCIvars -
1162/// This routine first collects all declared, but not synthesized, ivars in
1163/// super class and then collects all ivars, including those synthesized for
1164/// current class. This routine is used for implementation of current class
1165/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001166///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001167void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1168 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001169 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001170 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1171 DeepCollectObjCIvars(SuperClass, false, Ivars);
1172 if (!leafClass) {
1173 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1174 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +00001175 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001176 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001177 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001178 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001179 Iv= Iv->getNextIvar())
1180 Ivars.push_back(Iv);
1181 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001182}
1183
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001184/// CollectInheritedProtocols - Collect all protocols in current class and
1185/// those inherited by it.
1186void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001187 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001188 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001189 // We can use protocol_iterator here instead of
1190 // all_referenced_protocol_iterator since we are walking all categories.
1191 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1192 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001193 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001194 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001195 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001196 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001197 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001198 CollectInheritedProtocols(*P, Protocols);
1199 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001200 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001201
1202 // Categories of this Interface.
1203 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1204 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1205 CollectInheritedProtocols(CDeclChain, Protocols);
1206 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1207 while (SD) {
1208 CollectInheritedProtocols(SD, Protocols);
1209 SD = SD->getSuperClass();
1210 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001211 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001212 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001213 PE = OC->protocol_end(); P != PE; ++P) {
1214 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001215 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001216 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1217 PE = Proto->protocol_end(); P != PE; ++P)
1218 CollectInheritedProtocols(*P, Protocols);
1219 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001220 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001221 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1222 PE = OP->protocol_end(); P != PE; ++P) {
1223 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001224 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001225 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1226 PE = Proto->protocol_end(); P != PE; ++P)
1227 CollectInheritedProtocols(*P, Protocols);
1228 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001229 }
1230}
1231
Jay Foad39c79802011-01-12 09:06:06 +00001232unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001233 unsigned count = 0;
1234 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001235 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1236 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001237 count += CDecl->ivar_size();
1238
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001239 // Count ivar defined in this class's implementation. This
1240 // includes synthesized ivars.
1241 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001242 count += ImplDecl->ivar_size();
1243
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001244 return count;
1245}
1246
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001247bool ASTContext::isSentinelNullExpr(const Expr *E) {
1248 if (!E)
1249 return false;
1250
1251 // nullptr_t is always treated as null.
1252 if (E->getType()->isNullPtrType()) return true;
1253
1254 if (E->getType()->isAnyPointerType() &&
1255 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1256 Expr::NPC_ValueDependentIsNull))
1257 return true;
1258
1259 // Unfortunately, __null has type 'int'.
1260 if (isa<GNUNullExpr>(E)) return true;
1261
1262 return false;
1263}
1264
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001265/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1266ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1267 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1268 I = ObjCImpls.find(D);
1269 if (I != ObjCImpls.end())
1270 return cast<ObjCImplementationDecl>(I->second);
1271 return 0;
1272}
1273/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1274ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1275 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1276 I = ObjCImpls.find(D);
1277 if (I != ObjCImpls.end())
1278 return cast<ObjCCategoryImplDecl>(I->second);
1279 return 0;
1280}
1281
1282/// \brief Set the implementation of ObjCInterfaceDecl.
1283void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1284 ObjCImplementationDecl *ImplD) {
1285 assert(IFaceD && ImplD && "Passed null params");
1286 ObjCImpls[IFaceD] = ImplD;
1287}
1288/// \brief Set the implementation of ObjCCategoryDecl.
1289void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1290 ObjCCategoryImplDecl *ImplD) {
1291 assert(CatD && ImplD && "Passed null params");
1292 ObjCImpls[CatD] = ImplD;
1293}
1294
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001295ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1296 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1297 return ID;
1298 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1299 return CD->getClassInterface();
1300 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1301 return IMD->getClassInterface();
1302
1303 return 0;
1304}
1305
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001306/// \brief Get the copy initialization expression of VarDecl,or NULL if
1307/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001308Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001309 assert(VD && "Passed null params");
1310 assert(VD->hasAttr<BlocksAttr>() &&
1311 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001312 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001313 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001314 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1315}
1316
1317/// \brief Set the copy inialization expression of a block var decl.
1318void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1319 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001320 assert(VD->hasAttr<BlocksAttr>() &&
1321 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001322 BlockVarCopyInits[VD] = Init;
1323}
1324
John McCallbcd03502009-12-07 02:54:59 +00001325/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001326///
John McCallbcd03502009-12-07 02:54:59 +00001327/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001328/// the TypeLoc wrappers.
1329///
1330/// \param T the type that will be the basis for type source info. This type
1331/// should refer to how the declarator was written in source code, not to
1332/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001333TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001334 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001335 if (!DataSize)
1336 DataSize = TypeLoc::getFullDataSizeForType(T);
1337 else
1338 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001339 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001340
John McCallbcd03502009-12-07 02:54:59 +00001341 TypeSourceInfo *TInfo =
1342 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1343 new (TInfo) TypeSourceInfo(T);
1344 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001345}
1346
John McCallbcd03502009-12-07 02:54:59 +00001347TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001348 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001349 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001350 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001351 return DI;
1352}
1353
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001354const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001355ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001356 return getObjCLayout(D, 0);
1357}
1358
1359const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001360ASTContext::getASTObjCImplementationLayout(
1361 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001362 return getObjCLayout(D->getClassInterface(), D);
1363}
1364
Chris Lattner983a8bb2007-07-13 22:13:22 +00001365//===----------------------------------------------------------------------===//
1366// Type creation/memoization methods
1367//===----------------------------------------------------------------------===//
1368
Jay Foad39c79802011-01-12 09:06:06 +00001369QualType
John McCall33ddac02011-01-19 10:06:00 +00001370ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1371 unsigned fastQuals = quals.getFastQualifiers();
1372 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001373
1374 // Check if we've already instantiated this type.
1375 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001376 ExtQuals::Profile(ID, baseType, quals);
1377 void *insertPos = 0;
1378 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1379 assert(eq->getQualifiers() == quals);
1380 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001381 }
1382
John McCall33ddac02011-01-19 10:06:00 +00001383 // If the base type is not canonical, make the appropriate canonical type.
1384 QualType canon;
1385 if (!baseType->isCanonicalUnqualified()) {
1386 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001387 canonSplit.Quals.addConsistentQualifiers(quals);
1388 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001389
1390 // Re-find the insert position.
1391 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1392 }
1393
1394 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1395 ExtQualNodes.InsertNode(eq, insertPos);
1396 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001397}
1398
Jay Foad39c79802011-01-12 09:06:06 +00001399QualType
1400ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001401 QualType CanT = getCanonicalType(T);
1402 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001403 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001404
John McCall8ccfcb52009-09-24 19:53:00 +00001405 // If we are composing extended qualifiers together, merge together
1406 // into one ExtQuals node.
1407 QualifierCollector Quals;
1408 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001409
John McCall8ccfcb52009-09-24 19:53:00 +00001410 // If this type already has an address space specified, it cannot get
1411 // another one.
1412 assert(!Quals.hasAddressSpace() &&
1413 "Type cannot be in multiple addr spaces!");
1414 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001415
John McCall8ccfcb52009-09-24 19:53:00 +00001416 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001417}
1418
Chris Lattnerd60183d2009-02-18 22:53:11 +00001419QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001420 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001421 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001422 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001423 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001424
John McCall53fa7142010-12-24 02:08:15 +00001425 if (const PointerType *ptr = T->getAs<PointerType>()) {
1426 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001427 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001428 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1429 return getPointerType(ResultType);
1430 }
1431 }
Mike Stump11289f42009-09-09 15:08:12 +00001432
John McCall8ccfcb52009-09-24 19:53:00 +00001433 // If we are composing extended qualifiers together, merge together
1434 // into one ExtQuals node.
1435 QualifierCollector Quals;
1436 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001437
John McCall8ccfcb52009-09-24 19:53:00 +00001438 // If this type already has an ObjCGC specified, it cannot get
1439 // another one.
1440 assert(!Quals.hasObjCGCAttr() &&
1441 "Type cannot have multiple ObjCGCs!");
1442 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001443
John McCall8ccfcb52009-09-24 19:53:00 +00001444 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001445}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001446
John McCall4f5019e2010-12-19 02:44:49 +00001447const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1448 FunctionType::ExtInfo Info) {
1449 if (T->getExtInfo() == Info)
1450 return T;
1451
1452 QualType Result;
1453 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1454 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1455 } else {
1456 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1457 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1458 EPI.ExtInfo = Info;
1459 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1460 FPT->getNumArgs(), EPI);
1461 }
1462
1463 return cast<FunctionType>(Result.getTypePtr());
1464}
1465
Chris Lattnerc6395932007-06-22 20:56:16 +00001466/// getComplexType - Return the uniqued reference to the type for a complex
1467/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001468QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001469 // Unique pointers, to guarantee there is only one pointer of a particular
1470 // structure.
1471 llvm::FoldingSetNodeID ID;
1472 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001473
Chris Lattnerc6395932007-06-22 20:56:16 +00001474 void *InsertPos = 0;
1475 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1476 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001477
Chris Lattnerc6395932007-06-22 20:56:16 +00001478 // If the pointee type isn't canonical, this won't be a canonical type either,
1479 // so fill in the canonical type field.
1480 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001481 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001482 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001483
Chris Lattnerc6395932007-06-22 20:56:16 +00001484 // Get the new insert position for the node we care about.
1485 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001486 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001487 }
John McCall90d1c2d2009-09-24 23:30:46 +00001488 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001489 Types.push_back(New);
1490 ComplexTypes.InsertNode(New, InsertPos);
1491 return QualType(New, 0);
1492}
1493
Chris Lattner970e54e2006-11-12 00:37:36 +00001494/// getPointerType - Return the uniqued reference to the type for a pointer to
1495/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001496QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001497 // Unique pointers, to guarantee there is only one pointer of a particular
1498 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001499 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001500 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001501
Chris Lattner67521df2007-01-27 01:29:36 +00001502 void *InsertPos = 0;
1503 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001504 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001505
Chris Lattner7ccecb92006-11-12 08:50:50 +00001506 // If the pointee type isn't canonical, this won't be a canonical type either,
1507 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001508 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001509 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001510 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001511
Chris Lattner67521df2007-01-27 01:29:36 +00001512 // Get the new insert position for the node we care about.
1513 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001514 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001515 }
John McCall90d1c2d2009-09-24 23:30:46 +00001516 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001517 Types.push_back(New);
1518 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001519 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001520}
1521
Mike Stump11289f42009-09-09 15:08:12 +00001522/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001523/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001524QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001525 assert(T->isFunctionType() && "block of function types only");
1526 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001527 // structure.
1528 llvm::FoldingSetNodeID ID;
1529 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001530
Steve Naroffec33ed92008-08-27 16:04:49 +00001531 void *InsertPos = 0;
1532 if (BlockPointerType *PT =
1533 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1534 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001535
1536 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001537 // type either so fill in the canonical type field.
1538 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001539 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001540 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001541
Steve Naroffec33ed92008-08-27 16:04:49 +00001542 // Get the new insert position for the node we care about.
1543 BlockPointerType *NewIP =
1544 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001545 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001546 }
John McCall90d1c2d2009-09-24 23:30:46 +00001547 BlockPointerType *New
1548 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001549 Types.push_back(New);
1550 BlockPointerTypes.InsertNode(New, InsertPos);
1551 return QualType(New, 0);
1552}
1553
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001554/// getLValueReferenceType - Return the uniqued reference to the type for an
1555/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001556QualType
1557ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001558 assert(getCanonicalType(T) != OverloadTy &&
1559 "Unresolved overloaded function type");
1560
Bill Wendling3708c182007-05-27 10:15:43 +00001561 // Unique pointers, to guarantee there is only one pointer of a particular
1562 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001563 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001564 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001565
1566 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001567 if (LValueReferenceType *RT =
1568 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001569 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001570
John McCallfc93cf92009-10-22 22:37:11 +00001571 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1572
Bill Wendling3708c182007-05-27 10:15:43 +00001573 // If the referencee type isn't canonical, this won't be a canonical type
1574 // either, so fill in the canonical type field.
1575 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001576 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1577 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1578 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001579
Bill Wendling3708c182007-05-27 10:15:43 +00001580 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001581 LValueReferenceType *NewIP =
1582 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001583 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001584 }
1585
John McCall90d1c2d2009-09-24 23:30:46 +00001586 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001587 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1588 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001589 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001590 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001591
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001592 return QualType(New, 0);
1593}
1594
1595/// getRValueReferenceType - Return the uniqued reference to the type for an
1596/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001597QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001598 // Unique pointers, to guarantee there is only one pointer of a particular
1599 // structure.
1600 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001601 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001602
1603 void *InsertPos = 0;
1604 if (RValueReferenceType *RT =
1605 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1606 return QualType(RT, 0);
1607
John McCallfc93cf92009-10-22 22:37:11 +00001608 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1609
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001610 // If the referencee type isn't canonical, this won't be a canonical type
1611 // either, so fill in the canonical type field.
1612 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001613 if (InnerRef || !T.isCanonical()) {
1614 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1615 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001616
1617 // Get the new insert position for the node we care about.
1618 RValueReferenceType *NewIP =
1619 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001620 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001621 }
1622
John McCall90d1c2d2009-09-24 23:30:46 +00001623 RValueReferenceType *New
1624 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001625 Types.push_back(New);
1626 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001627 return QualType(New, 0);
1628}
1629
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001630/// getMemberPointerType - Return the uniqued reference to the type for a
1631/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001632QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001633 // Unique pointers, to guarantee there is only one pointer of a particular
1634 // structure.
1635 llvm::FoldingSetNodeID ID;
1636 MemberPointerType::Profile(ID, T, Cls);
1637
1638 void *InsertPos = 0;
1639 if (MemberPointerType *PT =
1640 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1641 return QualType(PT, 0);
1642
1643 // If the pointee or class type isn't canonical, this won't be a canonical
1644 // type either, so fill in the canonical type field.
1645 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001646 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001647 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1648
1649 // Get the new insert position for the node we care about.
1650 MemberPointerType *NewIP =
1651 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001652 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001653 }
John McCall90d1c2d2009-09-24 23:30:46 +00001654 MemberPointerType *New
1655 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001656 Types.push_back(New);
1657 MemberPointerTypes.InsertNode(New, InsertPos);
1658 return QualType(New, 0);
1659}
1660
Mike Stump11289f42009-09-09 15:08:12 +00001661/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001662/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001663QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001664 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001665 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001666 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001667 assert((EltTy->isDependentType() ||
1668 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001669 "Constant array of VLAs is illegal!");
1670
Chris Lattnere2df3f92009-05-13 04:12:56 +00001671 // Convert the array size into a canonical width matching the pointer size for
1672 // the target.
1673 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001674 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001675 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001676
Chris Lattner23b7eb62007-06-15 23:05:46 +00001677 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001678 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001679
Chris Lattner36f8e652007-01-27 08:31:04 +00001680 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001681 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001682 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001683 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001684
John McCall33ddac02011-01-19 10:06:00 +00001685 // If the element type isn't canonical or has qualifiers, this won't
1686 // be a canonical type either, so fill in the canonical type field.
1687 QualType Canon;
1688 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1689 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001690 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001691 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00001692 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001693
Chris Lattner36f8e652007-01-27 08:31:04 +00001694 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001695 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001696 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001697 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001698 }
Mike Stump11289f42009-09-09 15:08:12 +00001699
John McCall90d1c2d2009-09-24 23:30:46 +00001700 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001701 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001702 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001703 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001704 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001705}
1706
John McCall06549462011-01-18 08:40:38 +00001707/// getVariableArrayDecayedType - Turns the given type, which may be
1708/// variably-modified, into the corresponding type with all the known
1709/// sizes replaced with [*].
1710QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1711 // Vastly most common case.
1712 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001713
John McCall06549462011-01-18 08:40:38 +00001714 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001715
John McCall06549462011-01-18 08:40:38 +00001716 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00001717 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00001718 switch (ty->getTypeClass()) {
1719#define TYPE(Class, Base)
1720#define ABSTRACT_TYPE(Class, Base)
1721#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1722#include "clang/AST/TypeNodes.def"
1723 llvm_unreachable("didn't desugar past all non-canonical types?");
1724
1725 // These types should never be variably-modified.
1726 case Type::Builtin:
1727 case Type::Complex:
1728 case Type::Vector:
1729 case Type::ExtVector:
1730 case Type::DependentSizedExtVector:
1731 case Type::ObjCObject:
1732 case Type::ObjCInterface:
1733 case Type::ObjCObjectPointer:
1734 case Type::Record:
1735 case Type::Enum:
1736 case Type::UnresolvedUsing:
1737 case Type::TypeOfExpr:
1738 case Type::TypeOf:
1739 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001740 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001741 case Type::DependentName:
1742 case Type::InjectedClassName:
1743 case Type::TemplateSpecialization:
1744 case Type::DependentTemplateSpecialization:
1745 case Type::TemplateTypeParm:
1746 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001747 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001748 case Type::PackExpansion:
1749 llvm_unreachable("type should never be variably-modified");
1750
1751 // These types can be variably-modified but should never need to
1752 // further decay.
1753 case Type::FunctionNoProto:
1754 case Type::FunctionProto:
1755 case Type::BlockPointer:
1756 case Type::MemberPointer:
1757 return type;
1758
1759 // These types can be variably-modified. All these modifications
1760 // preserve structure except as noted by comments.
1761 // TODO: if we ever care about optimizing VLAs, there are no-op
1762 // optimizations available here.
1763 case Type::Pointer:
1764 result = getPointerType(getVariableArrayDecayedType(
1765 cast<PointerType>(ty)->getPointeeType()));
1766 break;
1767
1768 case Type::LValueReference: {
1769 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1770 result = getLValueReferenceType(
1771 getVariableArrayDecayedType(lv->getPointeeType()),
1772 lv->isSpelledAsLValue());
1773 break;
1774 }
1775
1776 case Type::RValueReference: {
1777 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1778 result = getRValueReferenceType(
1779 getVariableArrayDecayedType(lv->getPointeeType()));
1780 break;
1781 }
1782
Eli Friedman0dfb8892011-10-06 23:00:33 +00001783 case Type::Atomic: {
1784 const AtomicType *at = cast<AtomicType>(ty);
1785 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1786 break;
1787 }
1788
John McCall06549462011-01-18 08:40:38 +00001789 case Type::ConstantArray: {
1790 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1791 result = getConstantArrayType(
1792 getVariableArrayDecayedType(cat->getElementType()),
1793 cat->getSize(),
1794 cat->getSizeModifier(),
1795 cat->getIndexTypeCVRQualifiers());
1796 break;
1797 }
1798
1799 case Type::DependentSizedArray: {
1800 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1801 result = getDependentSizedArrayType(
1802 getVariableArrayDecayedType(dat->getElementType()),
1803 dat->getSizeExpr(),
1804 dat->getSizeModifier(),
1805 dat->getIndexTypeCVRQualifiers(),
1806 dat->getBracketsRange());
1807 break;
1808 }
1809
1810 // Turn incomplete types into [*] types.
1811 case Type::IncompleteArray: {
1812 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1813 result = getVariableArrayType(
1814 getVariableArrayDecayedType(iat->getElementType()),
1815 /*size*/ 0,
1816 ArrayType::Normal,
1817 iat->getIndexTypeCVRQualifiers(),
1818 SourceRange());
1819 break;
1820 }
1821
1822 // Turn VLA types into [*] types.
1823 case Type::VariableArray: {
1824 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1825 result = getVariableArrayType(
1826 getVariableArrayDecayedType(vat->getElementType()),
1827 /*size*/ 0,
1828 ArrayType::Star,
1829 vat->getIndexTypeCVRQualifiers(),
1830 vat->getBracketsRange());
1831 break;
1832 }
1833 }
1834
1835 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00001836 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00001837}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001838
Steve Naroffcadebd02007-08-30 18:14:25 +00001839/// getVariableArrayType - Returns a non-unique reference to the type for a
1840/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001841QualType ASTContext::getVariableArrayType(QualType EltTy,
1842 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001843 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001844 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001845 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001846 // Since we don't unique expressions, it isn't possible to unique VLA's
1847 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001848 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001849
John McCall33ddac02011-01-19 10:06:00 +00001850 // Be sure to pull qualifiers off the element type.
1851 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1852 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001853 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001854 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00001855 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001856 }
1857
John McCall90d1c2d2009-09-24 23:30:46 +00001858 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001859 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001860
1861 VariableArrayTypes.push_back(New);
1862 Types.push_back(New);
1863 return QualType(New, 0);
1864}
1865
Douglas Gregor4619e432008-12-05 23:32:09 +00001866/// getDependentSizedArrayType - Returns a non-unique reference to
1867/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001868/// type.
John McCall33ddac02011-01-19 10:06:00 +00001869QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1870 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001871 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001872 unsigned elementTypeQuals,
1873 SourceRange brackets) const {
1874 assert((!numElements || numElements->isTypeDependent() ||
1875 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001876 "Size must be type- or value-dependent!");
1877
John McCall33ddac02011-01-19 10:06:00 +00001878 // Dependently-sized array types that do not have a specified number
1879 // of elements will have their sizes deduced from a dependent
1880 // initializer. We do no canonicalization here at all, which is okay
1881 // because they can't be used in most locations.
1882 if (!numElements) {
1883 DependentSizedArrayType *newType
1884 = new (*this, TypeAlignment)
1885 DependentSizedArrayType(*this, elementType, QualType(),
1886 numElements, ASM, elementTypeQuals,
1887 brackets);
1888 Types.push_back(newType);
1889 return QualType(newType, 0);
1890 }
1891
1892 // Otherwise, we actually build a new type every time, but we
1893 // also build a canonical type.
1894
1895 SplitQualType canonElementType = getCanonicalType(elementType).split();
1896
1897 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001898 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001899 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00001900 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00001901 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001902
John McCall33ddac02011-01-19 10:06:00 +00001903 // Look for an existing type with these properties.
1904 DependentSizedArrayType *canonTy =
1905 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001906
John McCall33ddac02011-01-19 10:06:00 +00001907 // If we don't have one, build one.
1908 if (!canonTy) {
1909 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00001910 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00001911 QualType(), numElements, ASM, elementTypeQuals,
1912 brackets);
1913 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1914 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001915 }
1916
John McCall33ddac02011-01-19 10:06:00 +00001917 // Apply qualifiers from the element type to the array.
1918 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00001919 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00001920
John McCall33ddac02011-01-19 10:06:00 +00001921 // If we didn't need extra canonicalization for the element type,
1922 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00001923 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00001924 return canon;
1925
1926 // Otherwise, we need to build a type which follows the spelling
1927 // of the element type.
1928 DependentSizedArrayType *sugaredType
1929 = new (*this, TypeAlignment)
1930 DependentSizedArrayType(*this, elementType, canon, numElements,
1931 ASM, elementTypeQuals, brackets);
1932 Types.push_back(sugaredType);
1933 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00001934}
1935
John McCall33ddac02011-01-19 10:06:00 +00001936QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00001937 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001938 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001939 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001940 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001941
John McCall33ddac02011-01-19 10:06:00 +00001942 void *insertPos = 0;
1943 if (IncompleteArrayType *iat =
1944 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1945 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00001946
1947 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00001948 // either, so fill in the canonical type field. We also have to pull
1949 // qualifiers off the element type.
1950 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00001951
John McCall33ddac02011-01-19 10:06:00 +00001952 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1953 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00001954 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00001955 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00001956 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001957
1958 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00001959 IncompleteArrayType *existing =
1960 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1961 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001962 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001963
John McCall33ddac02011-01-19 10:06:00 +00001964 IncompleteArrayType *newType = new (*this, TypeAlignment)
1965 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001966
John McCall33ddac02011-01-19 10:06:00 +00001967 IncompleteArrayTypes.InsertNode(newType, insertPos);
1968 Types.push_back(newType);
1969 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001970}
1971
Steve Naroff91fcddb2007-07-18 18:00:27 +00001972/// getVectorType - Return the unique reference to a vector type of
1973/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001974QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001975 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00001976 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001977
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001978 // Check if we've already instantiated a vector of this type.
1979 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001980 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001981
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001982 void *InsertPos = 0;
1983 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1984 return QualType(VTP, 0);
1985
1986 // If the element type isn't canonical, this won't be a canonical type either,
1987 // so fill in the canonical type field.
1988 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001989 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001990 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001991
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001992 // Get the new insert position for the node we care about.
1993 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001994 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001995 }
John McCall90d1c2d2009-09-24 23:30:46 +00001996 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001997 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001998 VectorTypes.InsertNode(New, InsertPos);
1999 Types.push_back(New);
2000 return QualType(New, 0);
2001}
2002
Nate Begemance4d7fc2008-04-18 23:10:10 +00002003/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002004/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002005QualType
2006ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002007 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002008
Steve Naroff91fcddb2007-07-18 18:00:27 +00002009 // Check if we've already instantiated a vector of this type.
2010 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002011 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002012 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002013 void *InsertPos = 0;
2014 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2015 return QualType(VTP, 0);
2016
2017 // If the element type isn't canonical, this won't be a canonical type either,
2018 // so fill in the canonical type field.
2019 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002020 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002021 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002022
Steve Naroff91fcddb2007-07-18 18:00:27 +00002023 // Get the new insert position for the node we care about.
2024 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002025 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002026 }
John McCall90d1c2d2009-09-24 23:30:46 +00002027 ExtVectorType *New = new (*this, TypeAlignment)
2028 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002029 VectorTypes.InsertNode(New, InsertPos);
2030 Types.push_back(New);
2031 return QualType(New, 0);
2032}
2033
Jay Foad39c79802011-01-12 09:06:06 +00002034QualType
2035ASTContext::getDependentSizedExtVectorType(QualType vecType,
2036 Expr *SizeExpr,
2037 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002038 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002039 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002040 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002041
Douglas Gregor352169a2009-07-31 03:54:25 +00002042 void *InsertPos = 0;
2043 DependentSizedExtVectorType *Canon
2044 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2045 DependentSizedExtVectorType *New;
2046 if (Canon) {
2047 // We already have a canonical version of this array type; use it as
2048 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002049 New = new (*this, TypeAlignment)
2050 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2051 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002052 } else {
2053 QualType CanonVecTy = getCanonicalType(vecType);
2054 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002055 New = new (*this, TypeAlignment)
2056 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2057 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002058
2059 DependentSizedExtVectorType *CanonCheck
2060 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2061 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2062 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002063 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2064 } else {
2065 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2066 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002067 New = new (*this, TypeAlignment)
2068 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002069 }
2070 }
Mike Stump11289f42009-09-09 15:08:12 +00002071
Douglas Gregor758a8692009-06-17 21:51:59 +00002072 Types.push_back(New);
2073 return QualType(New, 0);
2074}
2075
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002076/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002077///
Jay Foad39c79802011-01-12 09:06:06 +00002078QualType
2079ASTContext::getFunctionNoProtoType(QualType ResultTy,
2080 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002081 const CallingConv DefaultCC = Info.getCC();
2082 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2083 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002084 // Unique functions, to guarantee there is only one function of a particular
2085 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002086 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002087 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002088
Chris Lattner47955de2007-01-27 08:37:20 +00002089 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002090 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002091 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002092 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002093
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002094 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002095 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002096 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002097 Canonical =
2098 getFunctionNoProtoType(getCanonicalType(ResultTy),
2099 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002100
Chris Lattner47955de2007-01-27 08:37:20 +00002101 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002102 FunctionNoProtoType *NewIP =
2103 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002104 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002105 }
Mike Stump11289f42009-09-09 15:08:12 +00002106
Roman Divacky65b88cd2011-03-01 17:40:53 +00002107 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002108 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002109 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002110 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002111 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002112 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002113}
2114
2115/// getFunctionType - Return a normal function type with a typed argument
2116/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002117QualType
2118ASTContext::getFunctionType(QualType ResultTy,
2119 const QualType *ArgArray, unsigned NumArgs,
2120 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002121 // Unique functions, to guarantee there is only one function of a particular
2122 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002123 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002124 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002125
2126 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002127 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002128 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002129 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002130
2131 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002132 bool isCanonical =
2133 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2134 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002135 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002136 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002137 isCanonical = false;
2138
Roman Divacky65b88cd2011-03-01 17:40:53 +00002139 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2140 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2141 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002142
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002143 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002144 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002145 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002146 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002147 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002148 CanonicalArgs.reserve(NumArgs);
2149 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002150 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002151
John McCalldb40c7f2010-12-14 08:05:40 +00002152 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002153 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002154 CanonicalEPI.ExceptionSpecType = EST_None;
2155 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002156 CanonicalEPI.ExtInfo
2157 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2158
Chris Lattner76a00cf2008-04-06 22:59:24 +00002159 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002160 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002161 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002162
Chris Lattnerfd4de792007-01-27 01:15:32 +00002163 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002164 FunctionProtoType *NewIP =
2165 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002166 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002167 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002168
John McCall31168b02011-06-15 23:02:42 +00002169 // FunctionProtoType objects are allocated with extra bytes after
2170 // them for three variable size arrays at the end:
2171 // - parameter types
2172 // - exception types
2173 // - consumed-arguments flags
2174 // Instead of the exception types, there could be a noexcept
2175 // expression.
John McCalldb40c7f2010-12-14 08:05:40 +00002176 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002177 NumArgs * sizeof(QualType);
2178 if (EPI.ExceptionSpecType == EST_Dynamic)
2179 Size += EPI.NumExceptions * sizeof(QualType);
2180 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002181 Size += sizeof(Expr*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002182 }
John McCall31168b02011-06-15 23:02:42 +00002183 if (EPI.ConsumedArguments)
2184 Size += NumArgs * sizeof(bool);
2185
John McCalldb40c7f2010-12-14 08:05:40 +00002186 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002187 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2188 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002189 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002190 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002191 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002192 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002193}
Chris Lattneref51c202006-11-10 07:17:23 +00002194
John McCalle78aac42010-03-10 03:28:59 +00002195#ifndef NDEBUG
2196static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2197 if (!isa<CXXRecordDecl>(D)) return false;
2198 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2199 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2200 return true;
2201 if (RD->getDescribedClassTemplate() &&
2202 !isa<ClassTemplateSpecializationDecl>(RD))
2203 return true;
2204 return false;
2205}
2206#endif
2207
2208/// getInjectedClassNameType - Return the unique reference to the
2209/// injected class name type for the specified templated declaration.
2210QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002211 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002212 assert(NeedsInjectedClassNameType(Decl));
2213 if (Decl->TypeForDecl) {
2214 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002215 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002216 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2217 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2218 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2219 } else {
John McCall424cec92011-01-19 06:33:43 +00002220 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002221 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002222 Decl->TypeForDecl = newType;
2223 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002224 }
2225 return QualType(Decl->TypeForDecl, 0);
2226}
2227
Douglas Gregor83a586e2008-04-13 21:07:44 +00002228/// getTypeDeclType - Return the unique reference to the type for the
2229/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002230QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002231 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002232 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002233
Richard Smithdda56e42011-04-15 14:24:37 +00002234 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002235 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002236
John McCall96f0b5f2010-03-10 06:48:02 +00002237 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2238 "Template type parameter types are always available.");
2239
John McCall81e38502010-02-16 03:57:14 +00002240 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002241 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002242 "struct/union has previous declaration");
2243 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002244 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002245 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002246 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002247 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002248 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002249 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002250 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002251 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2252 Decl->TypeForDecl = newType;
2253 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002254 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002255 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002256
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002257 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002258}
2259
Chris Lattner32d920b2007-01-26 02:01:53 +00002260/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002261/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002262QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002263ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2264 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002265 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002266
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002267 if (Canonical.isNull())
2268 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002269 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002270 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002271 Decl->TypeForDecl = newType;
2272 Types.push_back(newType);
2273 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002274}
2275
Jay Foad39c79802011-01-12 09:06:06 +00002276QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002277 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2278
Douglas Gregorec9fd132012-01-14 16:38:05 +00002279 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002280 if (PrevDecl->TypeForDecl)
2281 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2282
John McCall424cec92011-01-19 06:33:43 +00002283 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2284 Decl->TypeForDecl = newType;
2285 Types.push_back(newType);
2286 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002287}
2288
Jay Foad39c79802011-01-12 09:06:06 +00002289QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002290 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2291
Douglas Gregorec9fd132012-01-14 16:38:05 +00002292 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002293 if (PrevDecl->TypeForDecl)
2294 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2295
John McCall424cec92011-01-19 06:33:43 +00002296 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2297 Decl->TypeForDecl = newType;
2298 Types.push_back(newType);
2299 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002300}
2301
John McCall81904512011-01-06 01:58:22 +00002302QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2303 QualType modifiedType,
2304 QualType equivalentType) {
2305 llvm::FoldingSetNodeID id;
2306 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2307
2308 void *insertPos = 0;
2309 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2310 if (type) return QualType(type, 0);
2311
2312 QualType canon = getCanonicalType(equivalentType);
2313 type = new (*this, TypeAlignment)
2314 AttributedType(canon, attrKind, modifiedType, equivalentType);
2315
2316 Types.push_back(type);
2317 AttributedTypes.InsertNode(type, insertPos);
2318
2319 return QualType(type, 0);
2320}
2321
2322
John McCallcebee162009-10-18 09:09:24 +00002323/// \brief Retrieve a substitution-result type.
2324QualType
2325ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002326 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002327 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002328 && "replacement types must always be canonical");
2329
2330 llvm::FoldingSetNodeID ID;
2331 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2332 void *InsertPos = 0;
2333 SubstTemplateTypeParmType *SubstParm
2334 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2335
2336 if (!SubstParm) {
2337 SubstParm = new (*this, TypeAlignment)
2338 SubstTemplateTypeParmType(Parm, Replacement);
2339 Types.push_back(SubstParm);
2340 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2341 }
2342
2343 return QualType(SubstParm, 0);
2344}
2345
Douglas Gregorada4b792011-01-14 02:55:32 +00002346/// \brief Retrieve a
2347QualType ASTContext::getSubstTemplateTypeParmPackType(
2348 const TemplateTypeParmType *Parm,
2349 const TemplateArgument &ArgPack) {
2350#ifndef NDEBUG
2351 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2352 PEnd = ArgPack.pack_end();
2353 P != PEnd; ++P) {
2354 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2355 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2356 }
2357#endif
2358
2359 llvm::FoldingSetNodeID ID;
2360 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2361 void *InsertPos = 0;
2362 if (SubstTemplateTypeParmPackType *SubstParm
2363 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2364 return QualType(SubstParm, 0);
2365
2366 QualType Canon;
2367 if (!Parm->isCanonicalUnqualified()) {
2368 Canon = getCanonicalType(QualType(Parm, 0));
2369 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2370 ArgPack);
2371 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2372 }
2373
2374 SubstTemplateTypeParmPackType *SubstParm
2375 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2376 ArgPack);
2377 Types.push_back(SubstParm);
2378 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2379 return QualType(SubstParm, 0);
2380}
2381
Douglas Gregoreff93e02009-02-05 23:33:38 +00002382/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002383/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002384/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002385QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002386 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002387 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002388 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002389 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002390 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002391 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002392 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2393
2394 if (TypeParm)
2395 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002396
Chandler Carruth08836322011-05-01 00:51:33 +00002397 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002398 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002399 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002400
2401 TemplateTypeParmType *TypeCheck
2402 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2403 assert(!TypeCheck && "Template type parameter canonical type broken");
2404 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002405 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002406 TypeParm = new (*this, TypeAlignment)
2407 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002408
2409 Types.push_back(TypeParm);
2410 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2411
2412 return QualType(TypeParm, 0);
2413}
2414
John McCalle78aac42010-03-10 03:28:59 +00002415TypeSourceInfo *
2416ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2417 SourceLocation NameLoc,
2418 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002419 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002420 assert(!Name.getAsDependentTemplateName() &&
2421 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002422 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002423
2424 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2425 TemplateSpecializationTypeLoc TL
2426 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002427 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002428 TL.setTemplateNameLoc(NameLoc);
2429 TL.setLAngleLoc(Args.getLAngleLoc());
2430 TL.setRAngleLoc(Args.getRAngleLoc());
2431 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2432 TL.setArgLocInfo(i, Args[i].getLocInfo());
2433 return DI;
2434}
2435
Mike Stump11289f42009-09-09 15:08:12 +00002436QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002437ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002438 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002439 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002440 assert(!Template.getAsDependentTemplateName() &&
2441 "No dependent template names here!");
2442
John McCall6b51f282009-11-23 01:53:49 +00002443 unsigned NumArgs = Args.size();
2444
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002445 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002446 ArgVec.reserve(NumArgs);
2447 for (unsigned i = 0; i != NumArgs; ++i)
2448 ArgVec.push_back(Args[i].getArgument());
2449
John McCall2408e322010-04-27 00:57:59 +00002450 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002451 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002452}
2453
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002454#ifndef NDEBUG
2455static bool hasAnyPackExpansions(const TemplateArgument *Args,
2456 unsigned NumArgs) {
2457 for (unsigned I = 0; I != NumArgs; ++I)
2458 if (Args[I].isPackExpansion())
2459 return true;
2460
2461 return true;
2462}
2463#endif
2464
John McCall0ad16662009-10-29 08:12:44 +00002465QualType
2466ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002467 const TemplateArgument *Args,
2468 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002469 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002470 assert(!Template.getAsDependentTemplateName() &&
2471 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002472 // Look through qualified template names.
2473 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2474 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002475
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002476 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002477 Template.getAsTemplateDecl() &&
2478 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002479 QualType CanonType;
2480 if (!Underlying.isNull())
2481 CanonType = getCanonicalType(Underlying);
2482 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002483 // We can get here with an alias template when the specialization contains
2484 // a pack expansion that does not match up with a parameter pack.
2485 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2486 "Caller must compute aliased type");
2487 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002488 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2489 NumArgs);
2490 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002491
Douglas Gregora8e02e72009-07-28 23:00:59 +00002492 // Allocate the (non-canonical) template specialization type, but don't
2493 // try to unique it: these types typically have location information that
2494 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002495 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2496 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002497 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002498 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002499 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002500 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2501 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002502
Douglas Gregor8bf42052009-02-09 18:46:07 +00002503 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002504 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002505}
2506
Mike Stump11289f42009-09-09 15:08:12 +00002507QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002508ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2509 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002510 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002511 assert(!Template.getAsDependentTemplateName() &&
2512 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002513
Douglas Gregore29139c2011-03-03 17:04:51 +00002514 // Look through qualified template names.
2515 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2516 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002517
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002518 // Build the canonical template specialization type.
2519 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002520 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002521 CanonArgs.reserve(NumArgs);
2522 for (unsigned I = 0; I != NumArgs; ++I)
2523 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2524
2525 // Determine whether this canonical template specialization type already
2526 // exists.
2527 llvm::FoldingSetNodeID ID;
2528 TemplateSpecializationType::Profile(ID, CanonTemplate,
2529 CanonArgs.data(), NumArgs, *this);
2530
2531 void *InsertPos = 0;
2532 TemplateSpecializationType *Spec
2533 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2534
2535 if (!Spec) {
2536 // Allocate a new canonical template specialization type.
2537 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2538 sizeof(TemplateArgument) * NumArgs),
2539 TypeAlignment);
2540 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2541 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002542 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002543 Types.push_back(Spec);
2544 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2545 }
2546
2547 assert(Spec->isDependentType() &&
2548 "Non-dependent template-id type must have a canonical type");
2549 return QualType(Spec, 0);
2550}
2551
2552QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002553ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2554 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002555 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002556 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002557 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002558
2559 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002560 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002561 if (T)
2562 return QualType(T, 0);
2563
Douglas Gregorc42075a2010-02-04 18:10:26 +00002564 QualType Canon = NamedType;
2565 if (!Canon.isCanonical()) {
2566 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002567 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2568 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002569 (void)CheckT;
2570 }
2571
Abramo Bagnara6150c882010-05-11 21:36:43 +00002572 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002573 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002574 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002575 return QualType(T, 0);
2576}
2577
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002578QualType
Jay Foad39c79802011-01-12 09:06:06 +00002579ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002580 llvm::FoldingSetNodeID ID;
2581 ParenType::Profile(ID, InnerType);
2582
2583 void *InsertPos = 0;
2584 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2585 if (T)
2586 return QualType(T, 0);
2587
2588 QualType Canon = InnerType;
2589 if (!Canon.isCanonical()) {
2590 Canon = getCanonicalType(InnerType);
2591 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2592 assert(!CheckT && "Paren canonical type broken");
2593 (void)CheckT;
2594 }
2595
2596 T = new (*this) ParenType(InnerType, Canon);
2597 Types.push_back(T);
2598 ParenTypes.InsertNode(T, InsertPos);
2599 return QualType(T, 0);
2600}
2601
Douglas Gregor02085352010-03-31 20:19:30 +00002602QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2603 NestedNameSpecifier *NNS,
2604 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002605 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002606 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2607
2608 if (Canon.isNull()) {
2609 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002610 ElaboratedTypeKeyword CanonKeyword = Keyword;
2611 if (Keyword == ETK_None)
2612 CanonKeyword = ETK_Typename;
2613
2614 if (CanonNNS != NNS || CanonKeyword != Keyword)
2615 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002616 }
2617
2618 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002619 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002620
2621 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002622 DependentNameType *T
2623 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002624 if (T)
2625 return QualType(T, 0);
2626
Douglas Gregor02085352010-03-31 20:19:30 +00002627 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002628 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002629 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002630 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002631}
2632
Mike Stump11289f42009-09-09 15:08:12 +00002633QualType
John McCallc392f372010-06-11 00:33:02 +00002634ASTContext::getDependentTemplateSpecializationType(
2635 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002636 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002637 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002638 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002639 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002640 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002641 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2642 ArgCopy.push_back(Args[I].getArgument());
2643 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2644 ArgCopy.size(),
2645 ArgCopy.data());
2646}
2647
2648QualType
2649ASTContext::getDependentTemplateSpecializationType(
2650 ElaboratedTypeKeyword Keyword,
2651 NestedNameSpecifier *NNS,
2652 const IdentifierInfo *Name,
2653 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002654 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002655 assert((!NNS || NNS->isDependent()) &&
2656 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002657
Douglas Gregorc42075a2010-02-04 18:10:26 +00002658 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002659 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2660 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002661
2662 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002663 DependentTemplateSpecializationType *T
2664 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002665 if (T)
2666 return QualType(T, 0);
2667
John McCallc392f372010-06-11 00:33:02 +00002668 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002669
John McCallc392f372010-06-11 00:33:02 +00002670 ElaboratedTypeKeyword CanonKeyword = Keyword;
2671 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2672
2673 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002674 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002675 for (unsigned I = 0; I != NumArgs; ++I) {
2676 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2677 if (!CanonArgs[I].structurallyEquals(Args[I]))
2678 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002679 }
2680
John McCallc392f372010-06-11 00:33:02 +00002681 QualType Canon;
2682 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2683 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2684 Name, NumArgs,
2685 CanonArgs.data());
2686
2687 // Find the insert position again.
2688 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2689 }
2690
2691 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2692 sizeof(TemplateArgument) * NumArgs),
2693 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002694 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002695 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002696 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002697 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002698 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002699}
2700
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002701QualType ASTContext::getPackExpansionType(QualType Pattern,
2702 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002703 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002704 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002705
2706 assert(Pattern->containsUnexpandedParameterPack() &&
2707 "Pack expansions must expand one or more parameter packs");
2708 void *InsertPos = 0;
2709 PackExpansionType *T
2710 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2711 if (T)
2712 return QualType(T, 0);
2713
2714 QualType Canon;
2715 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002716 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002717
2718 // Find the insert position again.
2719 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2720 }
2721
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002722 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002723 Types.push_back(T);
2724 PackExpansionTypes.InsertNode(T, InsertPos);
2725 return QualType(T, 0);
2726}
2727
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002728/// CmpProtocolNames - Comparison predicate for sorting protocols
2729/// alphabetically.
2730static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2731 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002732 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002733}
2734
John McCall8b07ec22010-05-15 11:32:37 +00002735static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002736 unsigned NumProtocols) {
2737 if (NumProtocols == 0) return true;
2738
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002739 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2740 return false;
2741
John McCallfc93cf92009-10-22 22:37:11 +00002742 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002743 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2744 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00002745 return false;
2746 return true;
2747}
2748
2749static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002750 unsigned &NumProtocols) {
2751 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002752
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002753 // Sort protocols, keyed by name.
2754 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2755
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002756 // Canonicalize.
2757 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2758 Protocols[I] = Protocols[I]->getCanonicalDecl();
2759
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002760 // Remove duplicates.
2761 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2762 NumProtocols = ProtocolsEnd-Protocols;
2763}
2764
John McCall8b07ec22010-05-15 11:32:37 +00002765QualType ASTContext::getObjCObjectType(QualType BaseType,
2766 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002767 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002768 // If the base type is an interface and there aren't any protocols
2769 // to add, then the interface type will do just fine.
2770 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2771 return BaseType;
2772
2773 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002774 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002775 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002776 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002777 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2778 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002779
John McCall8b07ec22010-05-15 11:32:37 +00002780 // Build the canonical type, which has the canonical base type and
2781 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002782 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002783 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2784 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2785 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002786 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002787 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002788 unsigned UniqueCount = NumProtocols;
2789
John McCallfc93cf92009-10-22 22:37:11 +00002790 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002791 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2792 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002793 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002794 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2795 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002796 }
2797
2798 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002799 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2800 }
2801
2802 unsigned Size = sizeof(ObjCObjectTypeImpl);
2803 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2804 void *Mem = Allocate(Size, TypeAlignment);
2805 ObjCObjectTypeImpl *T =
2806 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2807
2808 Types.push_back(T);
2809 ObjCObjectTypes.InsertNode(T, InsertPos);
2810 return QualType(T, 0);
2811}
2812
2813/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2814/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002815QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002816 llvm::FoldingSetNodeID ID;
2817 ObjCObjectPointerType::Profile(ID, ObjectT);
2818
2819 void *InsertPos = 0;
2820 if (ObjCObjectPointerType *QT =
2821 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2822 return QualType(QT, 0);
2823
2824 // Find the canonical object type.
2825 QualType Canonical;
2826 if (!ObjectT.isCanonical()) {
2827 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2828
2829 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002830 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2831 }
2832
Douglas Gregorf85bee62010-02-08 22:59:26 +00002833 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002834 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2835 ObjCObjectPointerType *QType =
2836 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002837
Steve Narofffb4330f2009-06-17 22:40:22 +00002838 Types.push_back(QType);
2839 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002840 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002841}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002842
Douglas Gregor1c283312010-08-11 12:19:30 +00002843/// getObjCInterfaceType - Return the unique reference to the type for the
2844/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002845QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
2846 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002847 if (Decl->TypeForDecl)
2848 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002849
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002850 if (PrevDecl) {
2851 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
2852 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2853 return QualType(PrevDecl->TypeForDecl, 0);
2854 }
2855
Douglas Gregor7671e532011-12-16 16:34:57 +00002856 // Prefer the definition, if there is one.
2857 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
2858 Decl = Def;
2859
Douglas Gregor1c283312010-08-11 12:19:30 +00002860 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2861 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2862 Decl->TypeForDecl = T;
2863 Types.push_back(T);
2864 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002865}
2866
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002867/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2868/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002869/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002870/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002871/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002872QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002873 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002874 if (tofExpr->isTypeDependent()) {
2875 llvm::FoldingSetNodeID ID;
2876 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002877
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002878 void *InsertPos = 0;
2879 DependentTypeOfExprType *Canon
2880 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2881 if (Canon) {
2882 // We already have a "canonical" version of an identical, dependent
2883 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002884 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002885 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002886 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002887 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002888 Canon
2889 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002890 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2891 toe = Canon;
2892 }
2893 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002894 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002895 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002896 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002897 Types.push_back(toe);
2898 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002899}
2900
Steve Naroffa773cd52007-08-01 18:02:17 +00002901/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2902/// TypeOfType AST's. The only motivation to unique these nodes would be
2903/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002904/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002905/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002906QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002907 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002908 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002909 Types.push_back(tot);
2910 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002911}
2912
Anders Carlssonad6bd352009-06-24 21:24:56 +00002913
Anders Carlsson81df7b82009-06-24 19:06:50 +00002914/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2915/// DecltypeType AST's. The only motivation to unique these nodes would be
2916/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002917/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00002918/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00002919QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002920 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00002921
2922 // C++0x [temp.type]p2:
2923 // If an expression e involves a template parameter, decltype(e) denotes a
2924 // unique dependent type. Two such decltype-specifiers refer to the same
2925 // type only if their expressions are equivalent (14.5.6.1).
2926 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002927 llvm::FoldingSetNodeID ID;
2928 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002929
Douglas Gregora21f6c32009-07-30 23:36:40 +00002930 void *InsertPos = 0;
2931 DependentDecltypeType *Canon
2932 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2933 if (Canon) {
2934 // We already have a "canonical" version of an equivalent, dependent
2935 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002936 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002937 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002938 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002939 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002940 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002941 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2942 dt = Canon;
2943 }
2944 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00002945 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
2946 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00002947 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002948 Types.push_back(dt);
2949 return QualType(dt, 0);
2950}
2951
Alexis Hunte852b102011-05-24 22:41:36 +00002952/// getUnaryTransformationType - We don't unique these, since the memory
2953/// savings are minimal and these are rare.
2954QualType ASTContext::getUnaryTransformType(QualType BaseType,
2955 QualType UnderlyingType,
2956 UnaryTransformType::UTTKind Kind)
2957 const {
2958 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00002959 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2960 Kind,
2961 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00002962 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00002963 Types.push_back(Ty);
2964 return QualType(Ty, 0);
2965}
2966
Richard Smithb2bc2e62011-02-21 20:05:19 +00002967/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00002968QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00002969 void *InsertPos = 0;
2970 if (!DeducedType.isNull()) {
2971 // Look in the folding set for an existing type.
2972 llvm::FoldingSetNodeID ID;
2973 AutoType::Profile(ID, DeducedType);
2974 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2975 return QualType(AT, 0);
2976 }
2977
2978 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2979 Types.push_back(AT);
2980 if (InsertPos)
2981 AutoTypes.InsertNode(AT, InsertPos);
2982 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00002983}
2984
Eli Friedman0dfb8892011-10-06 23:00:33 +00002985/// getAtomicType - Return the uniqued reference to the atomic type for
2986/// the given value type.
2987QualType ASTContext::getAtomicType(QualType T) const {
2988 // Unique pointers, to guarantee there is only one pointer of a particular
2989 // structure.
2990 llvm::FoldingSetNodeID ID;
2991 AtomicType::Profile(ID, T);
2992
2993 void *InsertPos = 0;
2994 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
2995 return QualType(AT, 0);
2996
2997 // If the atomic value type isn't canonical, this won't be a canonical type
2998 // either, so fill in the canonical type field.
2999 QualType Canonical;
3000 if (!T.isCanonical()) {
3001 Canonical = getAtomicType(getCanonicalType(T));
3002
3003 // Get the new insert position for the node we care about.
3004 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3005 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3006 }
3007 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3008 Types.push_back(New);
3009 AtomicTypes.InsertNode(New, InsertPos);
3010 return QualType(New, 0);
3011}
3012
Richard Smith02e85f32011-04-14 22:09:26 +00003013/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3014QualType ASTContext::getAutoDeductType() const {
3015 if (AutoDeductTy.isNull())
3016 AutoDeductTy = getAutoType(QualType());
3017 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3018 return AutoDeductTy;
3019}
3020
3021/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3022QualType ASTContext::getAutoRRefDeductType() const {
3023 if (AutoRRefDeductTy.isNull())
3024 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3025 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3026 return AutoRRefDeductTy;
3027}
3028
Chris Lattnerfb072462007-01-23 05:45:31 +00003029/// getTagDeclType - Return the unique reference to the type for the
3030/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003031QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003032 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003033 // FIXME: What is the design on getTagDeclType when it requires casting
3034 // away const? mutable?
3035 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003036}
3037
Mike Stump11289f42009-09-09 15:08:12 +00003038/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3039/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3040/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003041CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003042 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003043}
Chris Lattnerfb072462007-01-23 05:45:31 +00003044
Hans Wennborg27541db2011-10-27 08:29:09 +00003045/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3046CanQualType ASTContext::getIntMaxType() const {
3047 return getFromTargetType(Target->getIntMaxType());
3048}
3049
3050/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3051CanQualType ASTContext::getUIntMaxType() const {
3052 return getFromTargetType(Target->getUIntMaxType());
3053}
3054
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003055/// getSignedWCharType - Return the type of "signed wchar_t".
3056/// Used when in C++, as a GCC extension.
3057QualType ASTContext::getSignedWCharType() const {
3058 // FIXME: derive from "Target" ?
3059 return WCharTy;
3060}
3061
3062/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3063/// Used when in C++, as a GCC extension.
3064QualType ASTContext::getUnsignedWCharType() const {
3065 // FIXME: derive from "Target" ?
3066 return UnsignedIntTy;
3067}
3068
Hans Wennborg27541db2011-10-27 08:29:09 +00003069/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003070/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3071QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003072 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003073}
3074
Chris Lattnera21ad802008-04-02 05:18:44 +00003075//===----------------------------------------------------------------------===//
3076// Type Operators
3077//===----------------------------------------------------------------------===//
3078
Jay Foad39c79802011-01-12 09:06:06 +00003079CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003080 // Push qualifiers into arrays, and then discard any remaining
3081 // qualifiers.
3082 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003083 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003084 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003085 QualType Result;
3086 if (isa<ArrayType>(Ty)) {
3087 Result = getArrayDecayedType(QualType(Ty,0));
3088 } else if (isa<FunctionType>(Ty)) {
3089 Result = getPointerType(QualType(Ty, 0));
3090 } else {
3091 Result = QualType(Ty, 0);
3092 }
3093
3094 return CanQualType::CreateUnsafe(Result);
3095}
3096
John McCall6c9dd522011-01-18 07:41:22 +00003097QualType ASTContext::getUnqualifiedArrayType(QualType type,
3098 Qualifiers &quals) {
3099 SplitQualType splitType = type.getSplitUnqualifiedType();
3100
3101 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3102 // the unqualified desugared type and then drops it on the floor.
3103 // We then have to strip that sugar back off with
3104 // getUnqualifiedDesugaredType(), which is silly.
3105 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003106 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003107
3108 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003109 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003110 quals = splitType.Quals;
3111 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003112 }
3113
John McCall6c9dd522011-01-18 07:41:22 +00003114 // Otherwise, recurse on the array's element type.
3115 QualType elementType = AT->getElementType();
3116 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3117
3118 // If that didn't change the element type, AT has no qualifiers, so we
3119 // can just use the results in splitType.
3120 if (elementType == unqualElementType) {
3121 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003122 quals = splitType.Quals;
3123 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003124 }
3125
3126 // Otherwise, add in the qualifiers from the outermost type, then
3127 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003128 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003129
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003130 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003131 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003132 CAT->getSizeModifier(), 0);
3133 }
3134
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003135 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003136 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003137 }
3138
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003139 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003140 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003141 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003142 VAT->getSizeModifier(),
3143 VAT->getIndexTypeCVRQualifiers(),
3144 VAT->getBracketsRange());
3145 }
3146
3147 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003148 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003149 DSAT->getSizeModifier(), 0,
3150 SourceRange());
3151}
3152
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003153/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3154/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3155/// they point to and return true. If T1 and T2 aren't pointer types
3156/// or pointer-to-member types, or if they are not similar at this
3157/// level, returns false and leaves T1 and T2 unchanged. Top-level
3158/// qualifiers on T1 and T2 are ignored. This function will typically
3159/// be called in a loop that successively "unwraps" pointer and
3160/// pointer-to-member types to compare them at each level.
3161bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3162 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3163 *T2PtrType = T2->getAs<PointerType>();
3164 if (T1PtrType && T2PtrType) {
3165 T1 = T1PtrType->getPointeeType();
3166 T2 = T2PtrType->getPointeeType();
3167 return true;
3168 }
3169
3170 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3171 *T2MPType = T2->getAs<MemberPointerType>();
3172 if (T1MPType && T2MPType &&
3173 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3174 QualType(T2MPType->getClass(), 0))) {
3175 T1 = T1MPType->getPointeeType();
3176 T2 = T2MPType->getPointeeType();
3177 return true;
3178 }
3179
3180 if (getLangOptions().ObjC1) {
3181 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3182 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3183 if (T1OPType && T2OPType) {
3184 T1 = T1OPType->getPointeeType();
3185 T2 = T2OPType->getPointeeType();
3186 return true;
3187 }
3188 }
3189
3190 // FIXME: Block pointers, too?
3191
3192 return false;
3193}
3194
Jay Foad39c79802011-01-12 09:06:06 +00003195DeclarationNameInfo
3196ASTContext::getNameForTemplate(TemplateName Name,
3197 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003198 switch (Name.getKind()) {
3199 case TemplateName::QualifiedTemplate:
3200 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003201 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003202 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3203 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003204
John McCalld9dfe3a2011-06-30 08:33:18 +00003205 case TemplateName::OverloadedTemplate: {
3206 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3207 // DNInfo work in progress: CHECKME: what about DNLoc?
3208 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3209 }
3210
3211 case TemplateName::DependentTemplate: {
3212 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003213 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003214 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003215 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3216 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003217 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003218 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3219 // DNInfo work in progress: FIXME: source locations?
3220 DeclarationNameLoc DNLoc;
3221 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3222 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3223 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003224 }
3225 }
3226
John McCalld9dfe3a2011-06-30 08:33:18 +00003227 case TemplateName::SubstTemplateTemplateParm: {
3228 SubstTemplateTemplateParmStorage *subst
3229 = Name.getAsSubstTemplateTemplateParm();
3230 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3231 NameLoc);
3232 }
3233
3234 case TemplateName::SubstTemplateTemplateParmPack: {
3235 SubstTemplateTemplateParmPackStorage *subst
3236 = Name.getAsSubstTemplateTemplateParmPack();
3237 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3238 NameLoc);
3239 }
3240 }
3241
3242 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003243}
3244
Jay Foad39c79802011-01-12 09:06:06 +00003245TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003246 switch (Name.getKind()) {
3247 case TemplateName::QualifiedTemplate:
3248 case TemplateName::Template: {
3249 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003250 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003251 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003252 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3253
3254 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003255 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003256 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003257
John McCalld9dfe3a2011-06-30 08:33:18 +00003258 case TemplateName::OverloadedTemplate:
3259 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003260
John McCalld9dfe3a2011-06-30 08:33:18 +00003261 case TemplateName::DependentTemplate: {
3262 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3263 assert(DTN && "Non-dependent template names must refer to template decls.");
3264 return DTN->CanonicalTemplateName;
3265 }
3266
3267 case TemplateName::SubstTemplateTemplateParm: {
3268 SubstTemplateTemplateParmStorage *subst
3269 = Name.getAsSubstTemplateTemplateParm();
3270 return getCanonicalTemplateName(subst->getReplacement());
3271 }
3272
3273 case TemplateName::SubstTemplateTemplateParmPack: {
3274 SubstTemplateTemplateParmPackStorage *subst
3275 = Name.getAsSubstTemplateTemplateParmPack();
3276 TemplateTemplateParmDecl *canonParameter
3277 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3278 TemplateArgument canonArgPack
3279 = getCanonicalTemplateArgument(subst->getArgumentPack());
3280 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3281 }
3282 }
3283
3284 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003285}
3286
Douglas Gregoradee3e32009-11-11 23:06:43 +00003287bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3288 X = getCanonicalTemplateName(X);
3289 Y = getCanonicalTemplateName(Y);
3290 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3291}
3292
Mike Stump11289f42009-09-09 15:08:12 +00003293TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003294ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003295 switch (Arg.getKind()) {
3296 case TemplateArgument::Null:
3297 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003298
Douglas Gregora8e02e72009-07-28 23:00:59 +00003299 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003300 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003301
Douglas Gregora8e02e72009-07-28 23:00:59 +00003302 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00003303 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003304
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003305 case TemplateArgument::Template:
3306 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003307
3308 case TemplateArgument::TemplateExpansion:
3309 return TemplateArgument(getCanonicalTemplateName(
3310 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003311 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003312
Douglas Gregora8e02e72009-07-28 23:00:59 +00003313 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00003314 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003315 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003316
Douglas Gregora8e02e72009-07-28 23:00:59 +00003317 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003318 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003319
Douglas Gregora8e02e72009-07-28 23:00:59 +00003320 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003321 if (Arg.pack_size() == 0)
3322 return Arg;
3323
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003324 TemplateArgument *CanonArgs
3325 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003326 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003327 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003328 AEnd = Arg.pack_end();
3329 A != AEnd; (void)++A, ++Idx)
3330 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003331
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003332 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003333 }
3334 }
3335
3336 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003337 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003338}
3339
Douglas Gregor333489b2009-03-27 23:10:48 +00003340NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003341ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003342 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003343 return 0;
3344
3345 switch (NNS->getKind()) {
3346 case NestedNameSpecifier::Identifier:
3347 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003348 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003349 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3350 NNS->getAsIdentifier());
3351
3352 case NestedNameSpecifier::Namespace:
3353 // A namespace is canonical; build a nested-name-specifier with
3354 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003355 return NestedNameSpecifier::Create(*this, 0,
3356 NNS->getAsNamespace()->getOriginalNamespace());
3357
3358 case NestedNameSpecifier::NamespaceAlias:
3359 // A namespace is canonical; build a nested-name-specifier with
3360 // this namespace and no prefix.
3361 return NestedNameSpecifier::Create(*this, 0,
3362 NNS->getAsNamespaceAlias()->getNamespace()
3363 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003364
3365 case NestedNameSpecifier::TypeSpec:
3366 case NestedNameSpecifier::TypeSpecWithTemplate: {
3367 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003368
3369 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3370 // break it apart into its prefix and identifier, then reconsititute those
3371 // as the canonical nested-name-specifier. This is required to canonicalize
3372 // a dependent nested-name-specifier involving typedefs of dependent-name
3373 // types, e.g.,
3374 // typedef typename T::type T1;
3375 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003376 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3377 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003378 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003379
Eli Friedman5358a0a2012-03-03 04:09:56 +00003380 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3381 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3382 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003383 return NestedNameSpecifier::Create(*this, 0, false,
3384 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003385 }
3386
3387 case NestedNameSpecifier::Global:
3388 // The global specifier is canonical and unique.
3389 return NNS;
3390 }
3391
David Blaikie8a40f702012-01-17 06:56:22 +00003392 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003393}
3394
Chris Lattner7adf0762008-08-04 07:31:14 +00003395
Jay Foad39c79802011-01-12 09:06:06 +00003396const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003397 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003398 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003399 // Handle the common positive case fast.
3400 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3401 return AT;
3402 }
Mike Stump11289f42009-09-09 15:08:12 +00003403
John McCall8ccfcb52009-09-24 19:53:00 +00003404 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003405 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003406 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003407
John McCall8ccfcb52009-09-24 19:53:00 +00003408 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003409 // implements C99 6.7.3p8: "If the specification of an array type includes
3410 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003411
Chris Lattner7adf0762008-08-04 07:31:14 +00003412 // If we get here, we either have type qualifiers on the type, or we have
3413 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003414 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003415
John McCall33ddac02011-01-19 10:06:00 +00003416 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003417 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003418
Chris Lattner7adf0762008-08-04 07:31:14 +00003419 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003420 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003421 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003422 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003423
Chris Lattner7adf0762008-08-04 07:31:14 +00003424 // Otherwise, we have an array and we have qualifiers on it. Push the
3425 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003426 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003427
Chris Lattner7adf0762008-08-04 07:31:14 +00003428 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3429 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3430 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003431 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003432 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3433 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3434 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003435 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003436
Mike Stump11289f42009-09-09 15:08:12 +00003437 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003438 = dyn_cast<DependentSizedArrayType>(ATy))
3439 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003440 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003441 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003442 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003443 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003444 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003445
Chris Lattner7adf0762008-08-04 07:31:14 +00003446 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003447 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003448 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003449 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003450 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003451 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003452}
3453
Douglas Gregor84280642011-07-12 04:42:08 +00003454QualType ASTContext::getAdjustedParameterType(QualType T) {
3455 // C99 6.7.5.3p7:
3456 // A declaration of a parameter as "array of type" shall be
3457 // adjusted to "qualified pointer to type", where the type
3458 // qualifiers (if any) are those specified within the [ and ] of
3459 // the array type derivation.
3460 if (T->isArrayType())
3461 return getArrayDecayedType(T);
3462
3463 // C99 6.7.5.3p8:
3464 // A declaration of a parameter as "function returning type"
3465 // shall be adjusted to "pointer to function returning type", as
3466 // in 6.3.2.1.
3467 if (T->isFunctionType())
3468 return getPointerType(T);
3469
3470 return T;
3471}
3472
3473QualType ASTContext::getSignatureParameterType(QualType T) {
3474 T = getVariableArrayDecayedType(T);
3475 T = getAdjustedParameterType(T);
3476 return T.getUnqualifiedType();
3477}
3478
Chris Lattnera21ad802008-04-02 05:18:44 +00003479/// getArrayDecayedType - Return the properly qualified result of decaying the
3480/// specified array type to a pointer. This operation is non-trivial when
3481/// handling typedefs etc. The canonical type of "T" must be an array type,
3482/// this returns a pointer to a properly qualified element of the array.
3483///
3484/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003485QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003486 // Get the element type with 'getAsArrayType' so that we don't lose any
3487 // typedefs in the element type of the array. This also handles propagation
3488 // of type qualifiers from the array type into the element type if present
3489 // (C99 6.7.3p8).
3490 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3491 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003492
Chris Lattner7adf0762008-08-04 07:31:14 +00003493 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003494
3495 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003496 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003497}
3498
John McCall33ddac02011-01-19 10:06:00 +00003499QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3500 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003501}
3502
John McCall33ddac02011-01-19 10:06:00 +00003503QualType ASTContext::getBaseElementType(QualType type) const {
3504 Qualifiers qs;
3505 while (true) {
3506 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003507 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00003508 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003509
John McCall33ddac02011-01-19 10:06:00 +00003510 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00003511 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003512 }
Mike Stump11289f42009-09-09 15:08:12 +00003513
John McCall33ddac02011-01-19 10:06:00 +00003514 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003515}
3516
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003517/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003518uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003519ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3520 uint64_t ElementCount = 1;
3521 do {
3522 ElementCount *= CA->getSize().getZExtValue();
3523 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3524 } while (CA);
3525 return ElementCount;
3526}
3527
Steve Naroff0af91202007-04-27 21:51:21 +00003528/// getFloatingRank - Return a relative rank for floating point types.
3529/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003530static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003531 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003532 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003533
John McCall9dd450b2009-09-21 23:43:11 +00003534 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3535 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003536 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003537 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003538 case BuiltinType::Float: return FloatRank;
3539 case BuiltinType::Double: return DoubleRank;
3540 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003541 }
3542}
3543
Mike Stump11289f42009-09-09 15:08:12 +00003544/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3545/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003546/// 'typeDomain' is a real floating point or complex type.
3547/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003548QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3549 QualType Domain) const {
3550 FloatingRank EltRank = getFloatingRank(Size);
3551 if (Domain->isComplexType()) {
3552 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003553 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00003554 case FloatRank: return FloatComplexTy;
3555 case DoubleRank: return DoubleComplexTy;
3556 case LongDoubleRank: return LongDoubleComplexTy;
3557 }
Steve Naroff0af91202007-04-27 21:51:21 +00003558 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003559
3560 assert(Domain->isRealFloatingType() && "Unknown domain!");
3561 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003562 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003563 case FloatRank: return FloatTy;
3564 case DoubleRank: return DoubleTy;
3565 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003566 }
David Blaikief47fa302012-01-17 02:30:50 +00003567 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00003568}
3569
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003570/// getFloatingTypeOrder - Compare the rank of the two specified floating
3571/// point types, ignoring the domain of the type (i.e. 'double' ==
3572/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003573/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003574int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003575 FloatingRank LHSR = getFloatingRank(LHS);
3576 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003577
Chris Lattnerb90739d2008-04-06 23:38:49 +00003578 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003579 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003580 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003581 return 1;
3582 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003583}
3584
Chris Lattner76a00cf2008-04-06 22:59:24 +00003585/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3586/// routine will assert if passed a built-in type that isn't an integer or enum,
3587/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003588unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003589 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003590
Chris Lattner76a00cf2008-04-06 22:59:24 +00003591 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003592 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003593 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003594 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003595 case BuiltinType::Char_S:
3596 case BuiltinType::Char_U:
3597 case BuiltinType::SChar:
3598 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003599 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003600 case BuiltinType::Short:
3601 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003602 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003603 case BuiltinType::Int:
3604 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003605 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003606 case BuiltinType::Long:
3607 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003608 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003609 case BuiltinType::LongLong:
3610 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003611 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003612 case BuiltinType::Int128:
3613 case BuiltinType::UInt128:
3614 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003615 }
3616}
3617
Eli Friedman629ffb92009-08-20 04:21:42 +00003618/// \brief Whether this is a promotable bitfield reference according
3619/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3620///
3621/// \returns the type this bit-field will promote to, or NULL if no
3622/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003623QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003624 if (E->isTypeDependent() || E->isValueDependent())
3625 return QualType();
3626
Eli Friedman629ffb92009-08-20 04:21:42 +00003627 FieldDecl *Field = E->getBitField();
3628 if (!Field)
3629 return QualType();
3630
3631 QualType FT = Field->getType();
3632
Richard Smithcaf33902011-10-10 18:28:20 +00003633 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00003634 uint64_t IntSize = getTypeSize(IntTy);
3635 // GCC extension compatibility: if the bit-field size is less than or equal
3636 // to the size of int, it gets promoted no matter what its type is.
3637 // For instance, unsigned long bf : 4 gets promoted to signed int.
3638 if (BitWidth < IntSize)
3639 return IntTy;
3640
3641 if (BitWidth == IntSize)
3642 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3643
3644 // Types bigger than int are not subject to promotions, and therefore act
3645 // like the base type.
3646 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3647 // is ridiculous.
3648 return QualType();
3649}
3650
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003651/// getPromotedIntegerType - Returns the type that Promotable will
3652/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3653/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003654QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003655 assert(!Promotable.isNull());
3656 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003657 if (const EnumType *ET = Promotable->getAs<EnumType>())
3658 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00003659
3660 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3661 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3662 // (3.9.1) can be converted to a prvalue of the first of the following
3663 // types that can represent all the values of its underlying type:
3664 // int, unsigned int, long int, unsigned long int, long long int, or
3665 // unsigned long long int [...]
3666 // FIXME: Is there some better way to compute this?
3667 if (BT->getKind() == BuiltinType::WChar_S ||
3668 BT->getKind() == BuiltinType::WChar_U ||
3669 BT->getKind() == BuiltinType::Char16 ||
3670 BT->getKind() == BuiltinType::Char32) {
3671 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3672 uint64_t FromSize = getTypeSize(BT);
3673 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3674 LongLongTy, UnsignedLongLongTy };
3675 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3676 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3677 if (FromSize < ToSize ||
3678 (FromSize == ToSize &&
3679 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3680 return PromoteTypes[Idx];
3681 }
3682 llvm_unreachable("char type should fit into long long");
3683 }
3684 }
3685
3686 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003687 if (Promotable->isSignedIntegerType())
3688 return IntTy;
3689 uint64_t PromotableSize = getTypeSize(Promotable);
3690 uint64_t IntSize = getTypeSize(IntTy);
3691 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3692 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3693}
3694
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003695/// \brief Recurses in pointer/array types until it finds an objc retainable
3696/// type and returns its ownership.
3697Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3698 while (!T.isNull()) {
3699 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3700 return T.getObjCLifetime();
3701 if (T->isArrayType())
3702 T = getBaseElementType(T);
3703 else if (const PointerType *PT = T->getAs<PointerType>())
3704 T = PT->getPointeeType();
3705 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003706 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003707 else
3708 break;
3709 }
3710
3711 return Qualifiers::OCL_None;
3712}
3713
Mike Stump11289f42009-09-09 15:08:12 +00003714/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003715/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003716/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003717int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003718 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3719 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003720 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003721
Chris Lattner76a00cf2008-04-06 22:59:24 +00003722 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3723 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003724
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003725 unsigned LHSRank = getIntegerRank(LHSC);
3726 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003727
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003728 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3729 if (LHSRank == RHSRank) return 0;
3730 return LHSRank > RHSRank ? 1 : -1;
3731 }
Mike Stump11289f42009-09-09 15:08:12 +00003732
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003733 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3734 if (LHSUnsigned) {
3735 // If the unsigned [LHS] type is larger, return it.
3736 if (LHSRank >= RHSRank)
3737 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003738
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003739 // If the signed type can represent all values of the unsigned type, it
3740 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003741 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003742 return -1;
3743 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003744
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003745 // If the unsigned [RHS] type is larger, return it.
3746 if (RHSRank >= LHSRank)
3747 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003748
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003749 // If the signed type can represent all values of the unsigned type, it
3750 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003751 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003752 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003753}
Anders Carlsson98f07902007-08-17 05:31:46 +00003754
Anders Carlsson6d417272009-11-14 21:45:58 +00003755static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003756CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3757 DeclContext *DC, IdentifierInfo *Id) {
3758 SourceLocation Loc;
Anders Carlsson6d417272009-11-14 21:45:58 +00003759 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003760 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003761 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003762 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003763}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003764
Mike Stump11289f42009-09-09 15:08:12 +00003765// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003766QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003767 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003768 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003769 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003770 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003771 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003772
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003773 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003774
Anders Carlsson98f07902007-08-17 05:31:46 +00003775 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003776 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003777 // int flags;
3778 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003779 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003780 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003781 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003782 FieldTypes[3] = LongTy;
3783
Anders Carlsson98f07902007-08-17 05:31:46 +00003784 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003785 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003786 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003787 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003788 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003789 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003790 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003791 /*Mutable=*/false,
3792 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003793 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003794 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003795 }
3796
Douglas Gregord5058122010-02-11 01:19:42 +00003797 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003798 }
Mike Stump11289f42009-09-09 15:08:12 +00003799
Anders Carlsson98f07902007-08-17 05:31:46 +00003800 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003801}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003802
Douglas Gregor512b0772009-04-23 22:29:11 +00003803void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003804 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003805 assert(Rec && "Invalid CFConstantStringType");
3806 CFConstantStringTypeDecl = Rec->getDecl();
3807}
3808
Jay Foad39c79802011-01-12 09:06:06 +00003809QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003810 if (BlockDescriptorType)
3811 return getTagDeclType(BlockDescriptorType);
3812
3813 RecordDecl *T;
3814 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003815 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003816 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003817 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003818
3819 QualType FieldTypes[] = {
3820 UnsignedLongTy,
3821 UnsignedLongTy,
3822 };
3823
3824 const char *FieldNames[] = {
3825 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003826 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003827 };
3828
3829 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003830 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003831 SourceLocation(),
3832 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003833 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003834 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003835 /*Mutable=*/false,
3836 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003837 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003838 T->addDecl(Field);
3839 }
3840
Douglas Gregord5058122010-02-11 01:19:42 +00003841 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003842
3843 BlockDescriptorType = T;
3844
3845 return getTagDeclType(BlockDescriptorType);
3846}
3847
Jay Foad39c79802011-01-12 09:06:06 +00003848QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003849 if (BlockDescriptorExtendedType)
3850 return getTagDeclType(BlockDescriptorExtendedType);
3851
3852 RecordDecl *T;
3853 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003854 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003855 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003856 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003857
3858 QualType FieldTypes[] = {
3859 UnsignedLongTy,
3860 UnsignedLongTy,
3861 getPointerType(VoidPtrTy),
3862 getPointerType(VoidPtrTy)
3863 };
3864
3865 const char *FieldNames[] = {
3866 "reserved",
3867 "Size",
3868 "CopyFuncPtr",
3869 "DestroyFuncPtr"
3870 };
3871
3872 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003873 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003874 SourceLocation(),
3875 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003876 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003877 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003878 /*Mutable=*/false,
3879 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003880 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003881 T->addDecl(Field);
3882 }
3883
Douglas Gregord5058122010-02-11 01:19:42 +00003884 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003885
3886 BlockDescriptorExtendedType = T;
3887
3888 return getTagDeclType(BlockDescriptorExtendedType);
3889}
3890
Jay Foad39c79802011-01-12 09:06:06 +00003891bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00003892 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00003893 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003894 if (getLangOptions().CPlusPlus) {
3895 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3896 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00003897 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003898
3899 }
3900 }
Mike Stump94967902009-10-21 18:16:27 +00003901 return false;
3902}
3903
Jay Foad39c79802011-01-12 09:06:06 +00003904QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003905ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003906 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003907 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003908 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003909 // unsigned int __flags;
3910 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003911 // void *__copy_helper; // as needed
3912 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003913 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003914 // } *
3915
Mike Stump94967902009-10-21 18:16:27 +00003916 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3917
3918 // FIXME: Move up
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003919 SmallString<36> Name;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003920 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3921 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003922 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003923 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003924 T->startDefinition();
3925 QualType Int32Ty = IntTy;
3926 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3927 QualType FieldTypes[] = {
3928 getPointerType(VoidPtrTy),
3929 getPointerType(getTagDeclType(T)),
3930 Int32Ty,
3931 Int32Ty,
3932 getPointerType(VoidPtrTy),
3933 getPointerType(VoidPtrTy),
3934 Ty
3935 };
3936
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003937 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003938 "__isa",
3939 "__forwarding",
3940 "__flags",
3941 "__size",
3942 "__copy_helper",
3943 "__destroy_helper",
3944 DeclName,
3945 };
3946
3947 for (size_t i = 0; i < 7; ++i) {
3948 if (!HasCopyAndDispose && i >=4 && i <= 5)
3949 continue;
3950 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003951 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00003952 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003953 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003954 /*BitWidth=*/0, /*Mutable=*/false,
3955 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003956 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003957 T->addDecl(Field);
3958 }
3959
Douglas Gregord5058122010-02-11 01:19:42 +00003960 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003961
3962 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003963}
3964
Douglas Gregorbab8a962011-09-08 01:46:34 +00003965TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
3966 if (!ObjCInstanceTypeDecl)
3967 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
3968 getTranslationUnitDecl(),
3969 SourceLocation(),
3970 SourceLocation(),
3971 &Idents.get("instancetype"),
3972 getTrivialTypeSourceInfo(getObjCIdType()));
3973 return ObjCInstanceTypeDecl;
3974}
3975
Anders Carlsson18acd442007-10-29 06:33:42 +00003976// This returns true if a type has been typedefed to BOOL:
3977// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003978static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003979 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003980 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3981 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003982
Anders Carlssond8499822007-10-29 05:01:08 +00003983 return false;
3984}
3985
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003986/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003987/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00003988CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00003989 if (!type->isIncompleteArrayType() && type->isIncompleteType())
3990 return CharUnits::Zero();
3991
Ken Dyck40775002010-01-11 17:06:35 +00003992 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003993
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003994 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003995 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003996 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003997 // Treat arrays as pointers, since that's how they're passed in.
3998 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003999 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004000 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004001}
4002
4003static inline
4004std::string charUnitsToString(const CharUnits &CU) {
4005 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004006}
4007
John McCall351762c2011-02-07 10:33:21 +00004008/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004009/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004010std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4011 std::string S;
4012
David Chisnall950a9512009-11-17 19:33:30 +00004013 const BlockDecl *Decl = Expr->getBlockDecl();
4014 QualType BlockTy =
4015 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4016 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00004017 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004018 // Compute size of all parameters.
4019 // Start with computing size of a pointer in number of bytes.
4020 // FIXME: There might(should) be a better way of doing this computation!
4021 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004022 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4023 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004024 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004025 E = Decl->param_end(); PI != E; ++PI) {
4026 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004027 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00004028 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004029 ParmOffset += sz;
4030 }
4031 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004032 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004033 // Block pointer and offset.
4034 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004035
4036 // Argument types.
4037 ParmOffset = PtrSize;
4038 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4039 Decl->param_end(); PI != E; ++PI) {
4040 ParmVarDecl *PVDecl = *PI;
4041 QualType PType = PVDecl->getOriginalType();
4042 if (const ArrayType *AT =
4043 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4044 // Use array's original type only if it has known number of
4045 // elements.
4046 if (!isa<ConstantArrayType>(AT))
4047 PType = PVDecl->getType();
4048 } else if (PType->isFunctionType())
4049 PType = PVDecl->getType();
4050 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004051 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004052 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004053 }
John McCall351762c2011-02-07 10:33:21 +00004054
4055 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004056}
4057
Douglas Gregora9d84932011-05-27 01:19:52 +00004058bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004059 std::string& S) {
4060 // Encode result type.
4061 getObjCEncodingForType(Decl->getResultType(), S);
4062 CharUnits ParmOffset;
4063 // Compute size of all parameters.
4064 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4065 E = Decl->param_end(); PI != E; ++PI) {
4066 QualType PType = (*PI)->getType();
4067 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004068 if (sz.isZero())
4069 return true;
4070
David Chisnall50e4eba2010-12-30 14:05:53 +00004071 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004072 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004073 ParmOffset += sz;
4074 }
4075 S += charUnitsToString(ParmOffset);
4076 ParmOffset = CharUnits::Zero();
4077
4078 // Argument types.
4079 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4080 E = Decl->param_end(); PI != E; ++PI) {
4081 ParmVarDecl *PVDecl = *PI;
4082 QualType PType = PVDecl->getOriginalType();
4083 if (const ArrayType *AT =
4084 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4085 // Use array's original type only if it has known number of
4086 // elements.
4087 if (!isa<ConstantArrayType>(AT))
4088 PType = PVDecl->getType();
4089 } else if (PType->isFunctionType())
4090 PType = PVDecl->getType();
4091 getObjCEncodingForType(PType, S);
4092 S += charUnitsToString(ParmOffset);
4093 ParmOffset += getObjCEncodingTypeSize(PType);
4094 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004095
4096 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004097}
4098
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004099/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4100/// method parameter or return type. If Extended, include class names and
4101/// block object types.
4102void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4103 QualType T, std::string& S,
4104 bool Extended) const {
4105 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4106 getObjCEncodingForTypeQualifier(QT, S);
4107 // Encode parameter type.
4108 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4109 true /*OutermostType*/,
4110 false /*EncodingProperty*/,
4111 false /*StructField*/,
4112 Extended /*EncodeBlockParameters*/,
4113 Extended /*EncodeClassNames*/);
4114}
4115
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004116/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004117/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004118bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004119 std::string& S,
4120 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004121 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004122 // Encode return type.
4123 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4124 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004125 // Compute size of all parameters.
4126 // Start with computing size of a pointer in number of bytes.
4127 // FIXME: There might(should) be a better way of doing this computation!
4128 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004129 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004130 // The first two arguments (self and _cmd) are pointers; account for
4131 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004132 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004133 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004134 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004135 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004136 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004137 if (sz.isZero())
4138 return true;
4139
Ken Dyck40775002010-01-11 17:06:35 +00004140 assert (sz.isPositive() &&
4141 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004142 ParmOffset += sz;
4143 }
Ken Dyck40775002010-01-11 17:06:35 +00004144 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004145 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004146 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004147
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004148 // Argument types.
4149 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004150 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004151 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004152 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004153 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004154 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004155 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4156 // Use array's original type only if it has known number of
4157 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004158 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004159 PType = PVDecl->getType();
4160 } else if (PType->isFunctionType())
4161 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004162 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4163 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004164 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004165 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004166 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004167
4168 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004169}
4170
Daniel Dunbar4932b362008-08-28 04:38:10 +00004171/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004172/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004173/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4174/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004175/// Property attributes are stored as a comma-delimited C string. The simple
4176/// attributes readonly and bycopy are encoded as single characters. The
4177/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4178/// encoded as single characters, followed by an identifier. Property types
4179/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004180/// these attributes are defined by the following enumeration:
4181/// @code
4182/// enum PropertyAttributes {
4183/// kPropertyReadOnly = 'R', // property is read-only.
4184/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4185/// kPropertyByref = '&', // property is a reference to the value last assigned
4186/// kPropertyDynamic = 'D', // property is dynamic
4187/// kPropertyGetter = 'G', // followed by getter selector name
4188/// kPropertySetter = 'S', // followed by setter selector name
4189/// kPropertyInstanceVariable = 'V' // followed by instance variable name
4190/// kPropertyType = 't' // followed by old-style type encoding.
4191/// kPropertyWeak = 'W' // 'weak' property
4192/// kPropertyStrong = 'P' // property GC'able
4193/// kPropertyNonAtomic = 'N' // property non-atomic
4194/// };
4195/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004196void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004197 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004198 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004199 // Collect information from the property implementation decl(s).
4200 bool Dynamic = false;
4201 ObjCPropertyImplDecl *SynthesizePID = 0;
4202
4203 // FIXME: Duplicated code due to poor abstraction.
4204 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004205 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004206 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4207 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004208 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004209 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004210 ObjCPropertyImplDecl *PID = *i;
4211 if (PID->getPropertyDecl() == PD) {
4212 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4213 Dynamic = true;
4214 } else {
4215 SynthesizePID = PID;
4216 }
4217 }
4218 }
4219 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004220 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004221 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004222 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004223 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004224 ObjCPropertyImplDecl *PID = *i;
4225 if (PID->getPropertyDecl() == PD) {
4226 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4227 Dynamic = true;
4228 } else {
4229 SynthesizePID = PID;
4230 }
4231 }
Mike Stump11289f42009-09-09 15:08:12 +00004232 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004233 }
4234 }
4235
4236 // FIXME: This is not very efficient.
4237 S = "T";
4238
4239 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004240 // GCC has some special rules regarding encoding of properties which
4241 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004242 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004243 true /* outermost type */,
4244 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004245
4246 if (PD->isReadOnly()) {
4247 S += ",R";
4248 } else {
4249 switch (PD->getSetterKind()) {
4250 case ObjCPropertyDecl::Assign: break;
4251 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004252 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004253 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004254 }
4255 }
4256
4257 // It really isn't clear at all what this means, since properties
4258 // are "dynamic by default".
4259 if (Dynamic)
4260 S += ",D";
4261
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004262 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4263 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004264
Daniel Dunbar4932b362008-08-28 04:38:10 +00004265 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4266 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004267 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004268 }
4269
4270 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4271 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004272 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004273 }
4274
4275 if (SynthesizePID) {
4276 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4277 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004278 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004279 }
4280
4281 // FIXME: OBJCGC: weak & strong
4282}
4283
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004284/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004285/// Another legacy compatibility encoding: 32-bit longs are encoded as
4286/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004287/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4288///
4289void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004290 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004291 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004292 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004293 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004294 else
Jay Foad39c79802011-01-12 09:06:06 +00004295 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004296 PointeeTy = IntTy;
4297 }
4298 }
4299}
4300
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004301void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004302 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004303 // We follow the behavior of gcc, expanding structures which are
4304 // directly pointed to, and expanding embedded structures. Note that
4305 // these rules are sufficient to prevent recursive encoding of the
4306 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004307 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004308 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004309}
4310
David Chisnallb190a2c2010-06-04 01:10:52 +00004311static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4312 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004313 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004314 case BuiltinType::Void: return 'v';
4315 case BuiltinType::Bool: return 'B';
4316 case BuiltinType::Char_U:
4317 case BuiltinType::UChar: return 'C';
4318 case BuiltinType::UShort: return 'S';
4319 case BuiltinType::UInt: return 'I';
4320 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004321 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004322 case BuiltinType::UInt128: return 'T';
4323 case BuiltinType::ULongLong: return 'Q';
4324 case BuiltinType::Char_S:
4325 case BuiltinType::SChar: return 'c';
4326 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004327 case BuiltinType::WChar_S:
4328 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004329 case BuiltinType::Int: return 'i';
4330 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004331 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004332 case BuiltinType::LongLong: return 'q';
4333 case BuiltinType::Int128: return 't';
4334 case BuiltinType::Float: return 'f';
4335 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004336 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004337 }
4338}
4339
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004340static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4341 EnumDecl *Enum = ET->getDecl();
4342
4343 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4344 if (!Enum->isFixed())
4345 return 'i';
4346
4347 // The encoding of a fixed enum type matches its fixed underlying type.
4348 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4349}
4350
Jay Foad39c79802011-01-12 09:06:06 +00004351static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004352 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004353 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004354 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004355 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4356 // The GNU runtime requires more information; bitfields are encoded as b,
4357 // then the offset (in bits) of the first element, then the type of the
4358 // bitfield, then the size in bits. For example, in this structure:
4359 //
4360 // struct
4361 // {
4362 // int integer;
4363 // int flags:2;
4364 // };
4365 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4366 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4367 // information is not especially sensible, but we're stuck with it for
4368 // compatibility with GCC, although providing it breaks anything that
4369 // actually uses runtime introspection and wants to work on both runtimes...
4370 if (!Ctx->getLangOptions().NeXTRuntime) {
4371 const RecordDecl *RD = FD->getParent();
4372 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004373 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004374 if (const EnumType *ET = T->getAs<EnumType>())
4375 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004376 else
Jay Foad39c79802011-01-12 09:06:06 +00004377 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004378 }
Richard Smithcaf33902011-10-10 18:28:20 +00004379 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004380}
4381
Daniel Dunbar07d07852009-10-18 21:17:35 +00004382// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004383void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4384 bool ExpandPointedToStructures,
4385 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004386 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004387 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004388 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004389 bool StructField,
4390 bool EncodeBlockParameters,
4391 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004392 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004393 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004394 return EncodeBitField(this, S, T, FD);
4395 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004396 return;
4397 }
Mike Stump11289f42009-09-09 15:08:12 +00004398
John McCall9dd450b2009-09-21 23:43:11 +00004399 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004400 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004401 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004402 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004403 return;
4404 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004405
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004406 // encoding for pointer or r3eference types.
4407 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004408 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004409 if (PT->isObjCSelType()) {
4410 S += ':';
4411 return;
4412 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004413 PointeeTy = PT->getPointeeType();
4414 }
4415 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4416 PointeeTy = RT->getPointeeType();
4417 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004418 bool isReadOnly = false;
4419 // For historical/compatibility reasons, the read-only qualifier of the
4420 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4421 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004422 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004423 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004424 if (OutermostType && T.isConstQualified()) {
4425 isReadOnly = true;
4426 S += 'r';
4427 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004428 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004429 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004430 while (P->getAs<PointerType>())
4431 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004432 if (P.isConstQualified()) {
4433 isReadOnly = true;
4434 S += 'r';
4435 }
4436 }
4437 if (isReadOnly) {
4438 // Another legacy compatibility encoding. Some ObjC qualifier and type
4439 // combinations need to be rearranged.
4440 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004441 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004442 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004443 }
Mike Stump11289f42009-09-09 15:08:12 +00004444
Anders Carlssond8499822007-10-29 05:01:08 +00004445 if (PointeeTy->isCharType()) {
4446 // char pointer types should be encoded as '*' unless it is a
4447 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004448 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004449 S += '*';
4450 return;
4451 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004452 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004453 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4454 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4455 S += '#';
4456 return;
4457 }
4458 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4459 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4460 S += '@';
4461 return;
4462 }
4463 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004464 }
Anders Carlssond8499822007-10-29 05:01:08 +00004465 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004466 getLegacyIntegralTypeEncoding(PointeeTy);
4467
Mike Stump11289f42009-09-09 15:08:12 +00004468 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004469 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004470 return;
4471 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004472
Chris Lattnere7cabb92009-07-13 00:10:46 +00004473 if (const ArrayType *AT =
4474 // Ignore type qualifiers etc.
4475 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004476 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004477 // Incomplete arrays are encoded as a pointer to the array element.
4478 S += '^';
4479
Mike Stump11289f42009-09-09 15:08:12 +00004480 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004481 false, ExpandStructures, FD);
4482 } else {
4483 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004484
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004485 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4486 if (getTypeSize(CAT->getElementType()) == 0)
4487 S += '0';
4488 else
4489 S += llvm::utostr(CAT->getSize().getZExtValue());
4490 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004491 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004492 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4493 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004494 S += '0';
4495 }
Mike Stump11289f42009-09-09 15:08:12 +00004496
4497 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004498 false, ExpandStructures, FD);
4499 S += ']';
4500 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004501 return;
4502 }
Mike Stump11289f42009-09-09 15:08:12 +00004503
John McCall9dd450b2009-09-21 23:43:11 +00004504 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004505 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004506 return;
4507 }
Mike Stump11289f42009-09-09 15:08:12 +00004508
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004509 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004510 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004511 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004512 // Anonymous structures print as '?'
4513 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4514 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004515 if (ClassTemplateSpecializationDecl *Spec
4516 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4517 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4518 std::string TemplateArgsStr
4519 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004520 TemplateArgs.data(),
4521 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004522 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004523
4524 S += TemplateArgsStr;
4525 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004526 } else {
4527 S += '?';
4528 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004529 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004530 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004531 if (!RDecl->isUnion()) {
4532 getObjCEncodingForStructureImpl(RDecl, S, FD);
4533 } else {
4534 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4535 FieldEnd = RDecl->field_end();
4536 Field != FieldEnd; ++Field) {
4537 if (FD) {
4538 S += '"';
4539 S += Field->getNameAsString();
4540 S += '"';
4541 }
Mike Stump11289f42009-09-09 15:08:12 +00004542
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004543 // Special case bit-fields.
4544 if (Field->isBitField()) {
4545 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4546 (*Field));
4547 } else {
4548 QualType qt = Field->getType();
4549 getLegacyIntegralTypeEncoding(qt);
4550 getObjCEncodingForTypeImpl(qt, S, false, true,
4551 FD, /*OutermostType*/false,
4552 /*EncodingProperty*/false,
4553 /*StructField*/true);
4554 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004555 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004556 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004557 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004558 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004559 return;
4560 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004561
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004562 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004563 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004564 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004565 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004566 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004567 return;
4568 }
Mike Stump11289f42009-09-09 15:08:12 +00004569
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004570 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004571 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004572 if (EncodeBlockParameters) {
4573 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4574
4575 S += '<';
4576 // Block return type
4577 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4578 ExpandPointedToStructures, ExpandStructures,
4579 FD,
4580 false /* OutermostType */,
4581 EncodingProperty,
4582 false /* StructField */,
4583 EncodeBlockParameters,
4584 EncodeClassNames);
4585 // Block self
4586 S += "@?";
4587 // Block parameters
4588 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4589 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4590 E = FPT->arg_type_end(); I && (I != E); ++I) {
4591 getObjCEncodingForTypeImpl(*I, S,
4592 ExpandPointedToStructures,
4593 ExpandStructures,
4594 FD,
4595 false /* OutermostType */,
4596 EncodingProperty,
4597 false /* StructField */,
4598 EncodeBlockParameters,
4599 EncodeClassNames);
4600 }
4601 }
4602 S += '>';
4603 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004604 return;
4605 }
Mike Stump11289f42009-09-09 15:08:12 +00004606
John McCall8b07ec22010-05-15 11:32:37 +00004607 // Ignore protocol qualifiers when mangling at this level.
4608 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4609 T = OT->getBaseType();
4610
John McCall8ccfcb52009-09-24 19:53:00 +00004611 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004612 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004613 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004614 S += '{';
4615 const IdentifierInfo *II = OI->getIdentifier();
4616 S += II->getName();
4617 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004618 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004619 DeepCollectObjCIvars(OI, true, Ivars);
4620 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004621 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004622 if (Field->isBitField())
4623 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004624 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004625 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004626 }
4627 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004628 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004629 }
Mike Stump11289f42009-09-09 15:08:12 +00004630
John McCall9dd450b2009-09-21 23:43:11 +00004631 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004632 if (OPT->isObjCIdType()) {
4633 S += '@';
4634 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004635 }
Mike Stump11289f42009-09-09 15:08:12 +00004636
Steve Narofff0c86112009-10-28 22:03:49 +00004637 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4638 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4639 // Since this is a binary compatibility issue, need to consult with runtime
4640 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004641 S += '#';
4642 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004643 }
Mike Stump11289f42009-09-09 15:08:12 +00004644
Chris Lattnere7cabb92009-07-13 00:10:46 +00004645 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004646 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004647 ExpandPointedToStructures,
4648 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004649 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004650 // Note that we do extended encoding of protocol qualifer list
4651 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004652 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004653 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4654 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004655 S += '<';
4656 S += (*I)->getNameAsString();
4657 S += '>';
4658 }
4659 S += '"';
4660 }
4661 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004662 }
Mike Stump11289f42009-09-09 15:08:12 +00004663
Chris Lattnere7cabb92009-07-13 00:10:46 +00004664 QualType PointeeTy = OPT->getPointeeType();
4665 if (!EncodingProperty &&
4666 isa<TypedefType>(PointeeTy.getTypePtr())) {
4667 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004668 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004669 // {...};
4670 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004671 getObjCEncodingForTypeImpl(PointeeTy, S,
4672 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004673 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004674 return;
4675 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004676
4677 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004678 if (OPT->getInterfaceDecl() &&
4679 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004680 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004681 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004682 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4683 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004684 S += '<';
4685 S += (*I)->getNameAsString();
4686 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004687 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004688 S += '"';
4689 }
4690 return;
4691 }
Mike Stump11289f42009-09-09 15:08:12 +00004692
John McCalla9e6e8d2010-05-17 23:56:34 +00004693 // gcc just blithely ignores member pointers.
4694 // TODO: maybe there should be a mangling for these
4695 if (T->getAs<MemberPointerType>())
4696 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004697
4698 if (T->isVectorType()) {
4699 // This matches gcc's encoding, even though technically it is
4700 // insufficient.
4701 // FIXME. We should do a better job than gcc.
4702 return;
4703 }
4704
David Blaikie83d382b2011-09-23 05:06:16 +00004705 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004706}
4707
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004708void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4709 std::string &S,
4710 const FieldDecl *FD,
4711 bool includeVBases) const {
4712 assert(RDecl && "Expected non-null RecordDecl");
4713 assert(!RDecl->isUnion() && "Should not be called for unions");
4714 if (!RDecl->getDefinition())
4715 return;
4716
4717 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4718 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4719 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4720
4721 if (CXXRec) {
4722 for (CXXRecordDecl::base_class_iterator
4723 BI = CXXRec->bases_begin(),
4724 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4725 if (!BI->isVirtual()) {
4726 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004727 if (base->isEmpty())
4728 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004729 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4730 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4731 std::make_pair(offs, base));
4732 }
4733 }
4734 }
4735
4736 unsigned i = 0;
4737 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4738 FieldEnd = RDecl->field_end();
4739 Field != FieldEnd; ++Field, ++i) {
4740 uint64_t offs = layout.getFieldOffset(i);
4741 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4742 std::make_pair(offs, *Field));
4743 }
4744
4745 if (CXXRec && includeVBases) {
4746 for (CXXRecordDecl::base_class_iterator
4747 BI = CXXRec->vbases_begin(),
4748 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4749 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004750 if (base->isEmpty())
4751 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004752 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00004753 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4754 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4755 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004756 }
4757 }
4758
4759 CharUnits size;
4760 if (CXXRec) {
4761 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4762 } else {
4763 size = layout.getSize();
4764 }
4765
4766 uint64_t CurOffs = 0;
4767 std::multimap<uint64_t, NamedDecl *>::iterator
4768 CurLayObj = FieldOrBaseOffsets.begin();
4769
Argyrios Kyrtzidisc7e50c52011-08-22 16:03:14 +00004770 if ((CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) ||
4771 (CurLayObj == FieldOrBaseOffsets.end() &&
4772 CXXRec && CXXRec->isDynamicClass())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004773 assert(CXXRec && CXXRec->isDynamicClass() &&
4774 "Offset 0 was empty but no VTable ?");
4775 if (FD) {
4776 S += "\"_vptr$";
4777 std::string recname = CXXRec->getNameAsString();
4778 if (recname.empty()) recname = "?";
4779 S += recname;
4780 S += '"';
4781 }
4782 S += "^^?";
4783 CurOffs += getTypeSize(VoidPtrTy);
4784 }
4785
4786 if (!RDecl->hasFlexibleArrayMember()) {
4787 // Mark the end of the structure.
4788 uint64_t offs = toBits(size);
4789 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4790 std::make_pair(offs, (NamedDecl*)0));
4791 }
4792
4793 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4794 assert(CurOffs <= CurLayObj->first);
4795
4796 if (CurOffs < CurLayObj->first) {
4797 uint64_t padding = CurLayObj->first - CurOffs;
4798 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4799 // packing/alignment of members is different that normal, in which case
4800 // the encoding will be out-of-sync with the real layout.
4801 // If the runtime switches to just consider the size of types without
4802 // taking into account alignment, we could make padding explicit in the
4803 // encoding (e.g. using arrays of chars). The encoding strings would be
4804 // longer then though.
4805 CurOffs += padding;
4806 }
4807
4808 NamedDecl *dcl = CurLayObj->second;
4809 if (dcl == 0)
4810 break; // reached end of structure.
4811
4812 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4813 // We expand the bases without their virtual bases since those are going
4814 // in the initial structure. Note that this differs from gcc which
4815 // expands virtual bases each time one is encountered in the hierarchy,
4816 // making the encoding type bigger than it really is.
4817 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004818 assert(!base->isEmpty());
4819 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004820 } else {
4821 FieldDecl *field = cast<FieldDecl>(dcl);
4822 if (FD) {
4823 S += '"';
4824 S += field->getNameAsString();
4825 S += '"';
4826 }
4827
4828 if (field->isBitField()) {
4829 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00004830 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004831 } else {
4832 QualType qt = field->getType();
4833 getLegacyIntegralTypeEncoding(qt);
4834 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4835 /*OutermostType*/false,
4836 /*EncodingProperty*/false,
4837 /*StructField*/true);
4838 CurOffs += getTypeSize(field->getType());
4839 }
4840 }
4841 }
4842}
4843
Mike Stump11289f42009-09-09 15:08:12 +00004844void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004845 std::string& S) const {
4846 if (QT & Decl::OBJC_TQ_In)
4847 S += 'n';
4848 if (QT & Decl::OBJC_TQ_Inout)
4849 S += 'N';
4850 if (QT & Decl::OBJC_TQ_Out)
4851 S += 'o';
4852 if (QT & Decl::OBJC_TQ_Bycopy)
4853 S += 'O';
4854 if (QT & Decl::OBJC_TQ_Byref)
4855 S += 'R';
4856 if (QT & Decl::OBJC_TQ_Oneway)
4857 S += 'V';
4858}
4859
Chris Lattnere7cabb92009-07-13 00:10:46 +00004860void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004861 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004862
Anders Carlsson87c149b2007-10-11 01:00:40 +00004863 BuiltinVaListType = T;
4864}
4865
Douglas Gregor3ea72692011-08-12 05:46:01 +00004866TypedefDecl *ASTContext::getObjCIdDecl() const {
4867 if (!ObjCIdDecl) {
4868 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4869 T = getObjCObjectPointerType(T);
4870 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4871 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4872 getTranslationUnitDecl(),
4873 SourceLocation(), SourceLocation(),
4874 &Idents.get("id"), IdInfo);
4875 }
4876
4877 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00004878}
4879
Douglas Gregor52e02802011-08-12 06:17:30 +00004880TypedefDecl *ASTContext::getObjCSelDecl() const {
4881 if (!ObjCSelDecl) {
4882 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4883 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4884 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4885 getTranslationUnitDecl(),
4886 SourceLocation(), SourceLocation(),
4887 &Idents.get("SEL"), SelInfo);
4888 }
4889 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004890}
4891
Douglas Gregor0a586182011-08-12 05:59:41 +00004892TypedefDecl *ASTContext::getObjCClassDecl() const {
4893 if (!ObjCClassDecl) {
4894 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4895 T = getObjCObjectPointerType(T);
4896 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4897 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4898 getTranslationUnitDecl(),
4899 SourceLocation(), SourceLocation(),
4900 &Idents.get("Class"), ClassInfo);
4901 }
4902
4903 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004904}
4905
Douglas Gregord53ae832012-01-17 18:09:05 +00004906ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
4907 if (!ObjCProtocolClassDecl) {
4908 ObjCProtocolClassDecl
4909 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
4910 SourceLocation(),
4911 &Idents.get("Protocol"),
4912 /*PrevDecl=*/0,
4913 SourceLocation(), true);
4914 }
4915
4916 return ObjCProtocolClassDecl;
4917}
4918
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004919void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004920 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004921 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004922
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004923 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004924}
4925
John McCalld28ae272009-12-02 08:04:21 +00004926/// \brief Retrieve the template name that corresponds to a non-empty
4927/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004928TemplateName
4929ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4930 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004931 unsigned size = End - Begin;
4932 assert(size > 1 && "set is not overloaded!");
4933
4934 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4935 size * sizeof(FunctionTemplateDecl*));
4936 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4937
4938 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004939 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004940 NamedDecl *D = *I;
4941 assert(isa<FunctionTemplateDecl>(D) ||
4942 (isa<UsingShadowDecl>(D) &&
4943 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4944 *Storage++ = D;
4945 }
4946
4947 return TemplateName(OT);
4948}
4949
Douglas Gregordc572a32009-03-30 22:58:21 +00004950/// \brief Retrieve the template name that represents a qualified
4951/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004952TemplateName
4953ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4954 bool TemplateKeyword,
4955 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00004956 assert(NNS && "Missing nested-name-specifier in qualified template name");
4957
Douglas Gregorc42075a2010-02-04 18:10:26 +00004958 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004959 llvm::FoldingSetNodeID ID;
4960 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4961
4962 void *InsertPos = 0;
4963 QualifiedTemplateName *QTN =
4964 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4965 if (!QTN) {
4966 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4967 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4968 }
4969
4970 return TemplateName(QTN);
4971}
4972
4973/// \brief Retrieve the template name that represents a dependent
4974/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004975TemplateName
4976ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4977 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004978 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004979 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004980
4981 llvm::FoldingSetNodeID ID;
4982 DependentTemplateName::Profile(ID, NNS, Name);
4983
4984 void *InsertPos = 0;
4985 DependentTemplateName *QTN =
4986 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4987
4988 if (QTN)
4989 return TemplateName(QTN);
4990
4991 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4992 if (CanonNNS == NNS) {
4993 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4994 } else {
4995 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4996 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004997 DependentTemplateName *CheckQTN =
4998 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4999 assert(!CheckQTN && "Dependent type name canonicalization broken");
5000 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005001 }
5002
5003 DependentTemplateNames.InsertNode(QTN, InsertPos);
5004 return TemplateName(QTN);
5005}
5006
Douglas Gregor71395fa2009-11-04 00:56:37 +00005007/// \brief Retrieve the template name that represents a dependent
5008/// template name such as \c MetaFun::template operator+.
5009TemplateName
5010ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005011 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005012 assert((!NNS || NNS->isDependent()) &&
5013 "Nested name specifier must be dependent");
5014
5015 llvm::FoldingSetNodeID ID;
5016 DependentTemplateName::Profile(ID, NNS, Operator);
5017
5018 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005019 DependentTemplateName *QTN
5020 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005021
5022 if (QTN)
5023 return TemplateName(QTN);
5024
5025 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5026 if (CanonNNS == NNS) {
5027 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5028 } else {
5029 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5030 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005031
5032 DependentTemplateName *CheckQTN
5033 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5034 assert(!CheckQTN && "Dependent template name canonicalization broken");
5035 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005036 }
5037
5038 DependentTemplateNames.InsertNode(QTN, InsertPos);
5039 return TemplateName(QTN);
5040}
5041
Douglas Gregor5590be02011-01-15 06:45:20 +00005042TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005043ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5044 TemplateName replacement) const {
5045 llvm::FoldingSetNodeID ID;
5046 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5047
5048 void *insertPos = 0;
5049 SubstTemplateTemplateParmStorage *subst
5050 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5051
5052 if (!subst) {
5053 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5054 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5055 }
5056
5057 return TemplateName(subst);
5058}
5059
5060TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005061ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5062 const TemplateArgument &ArgPack) const {
5063 ASTContext &Self = const_cast<ASTContext &>(*this);
5064 llvm::FoldingSetNodeID ID;
5065 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5066
5067 void *InsertPos = 0;
5068 SubstTemplateTemplateParmPackStorage *Subst
5069 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5070
5071 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005072 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005073 ArgPack.pack_size(),
5074 ArgPack.pack_begin());
5075 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5076 }
5077
5078 return TemplateName(Subst);
5079}
5080
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005081/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005082/// TargetInfo, produce the corresponding type. The unsigned @p Type
5083/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005084CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005085 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005086 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005087 case TargetInfo::SignedShort: return ShortTy;
5088 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5089 case TargetInfo::SignedInt: return IntTy;
5090 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5091 case TargetInfo::SignedLong: return LongTy;
5092 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5093 case TargetInfo::SignedLongLong: return LongLongTy;
5094 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5095 }
5096
David Blaikie83d382b2011-09-23 05:06:16 +00005097 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005098}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005099
5100//===----------------------------------------------------------------------===//
5101// Type Predicates.
5102//===----------------------------------------------------------------------===//
5103
Fariborz Jahanian96207692009-02-18 21:49:28 +00005104/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5105/// garbage collection attribute.
5106///
John McCall553d45a2011-01-12 00:34:59 +00005107Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
Douglas Gregor79a91412011-09-13 17:21:33 +00005108 if (getLangOptions().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005109 return Qualifiers::GCNone;
5110
5111 assert(getLangOptions().ObjC1);
5112 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5113
5114 // Default behaviour under objective-C's gc is for ObjC pointers
5115 // (or pointers to them) be treated as though they were declared
5116 // as __strong.
5117 if (GCAttrs == Qualifiers::GCNone) {
5118 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5119 return Qualifiers::Strong;
5120 else if (Ty->isPointerType())
5121 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5122 } else {
5123 // It's not valid to set GC attributes on anything that isn't a
5124 // pointer.
5125#ifndef NDEBUG
5126 QualType CT = Ty->getCanonicalTypeInternal();
5127 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5128 CT = AT->getElementType();
5129 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5130#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005131 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005132 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005133}
5134
Chris Lattner49af6a42008-04-07 06:51:04 +00005135//===----------------------------------------------------------------------===//
5136// Type Compatibility Testing
5137//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005138
Mike Stump11289f42009-09-09 15:08:12 +00005139/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005140/// compatible.
5141static bool areCompatVectorTypes(const VectorType *LHS,
5142 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005143 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005144 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005145 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005146}
5147
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005148bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5149 QualType SecondVec) {
5150 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5151 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5152
5153 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5154 return true;
5155
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005156 // Treat Neon vector types and most AltiVec vector types as if they are the
5157 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005158 const VectorType *First = FirstVec->getAs<VectorType>();
5159 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005160 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005161 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005162 First->getVectorKind() != VectorType::AltiVecPixel &&
5163 First->getVectorKind() != VectorType::AltiVecBool &&
5164 Second->getVectorKind() != VectorType::AltiVecPixel &&
5165 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005166 return true;
5167
5168 return false;
5169}
5170
Steve Naroff8e6aee52009-07-23 01:01:38 +00005171//===----------------------------------------------------------------------===//
5172// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5173//===----------------------------------------------------------------------===//
5174
5175/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5176/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005177bool
5178ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5179 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005180 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005181 return true;
5182 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5183 E = rProto->protocol_end(); PI != E; ++PI)
5184 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5185 return true;
5186 return false;
5187}
5188
Steve Naroff8e6aee52009-07-23 01:01:38 +00005189/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5190/// return true if lhs's protocols conform to rhs's protocol; false
5191/// otherwise.
5192bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5193 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5194 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5195 return false;
5196}
5197
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005198/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5199/// Class<p1, ...>.
5200bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5201 QualType rhs) {
5202 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5203 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5204 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5205
5206 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5207 E = lhsQID->qual_end(); I != E; ++I) {
5208 bool match = false;
5209 ObjCProtocolDecl *lhsProto = *I;
5210 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5211 E = rhsOPT->qual_end(); J != E; ++J) {
5212 ObjCProtocolDecl *rhsProto = *J;
5213 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5214 match = true;
5215 break;
5216 }
5217 }
5218 if (!match)
5219 return false;
5220 }
5221 return true;
5222}
5223
Steve Naroff8e6aee52009-07-23 01:01:38 +00005224/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5225/// ObjCQualifiedIDType.
5226bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5227 bool compare) {
5228 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005229 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005230 lhs->isObjCIdType() || lhs->isObjCClassType())
5231 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005232 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005233 rhs->isObjCIdType() || rhs->isObjCClassType())
5234 return true;
5235
5236 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005237 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005238
Steve Naroff8e6aee52009-07-23 01:01:38 +00005239 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005240
Steve Naroff8e6aee52009-07-23 01:01:38 +00005241 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005242 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005243 // make sure we check the class hierarchy.
5244 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5245 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5246 E = lhsQID->qual_end(); I != E; ++I) {
5247 // when comparing an id<P> on lhs with a static type on rhs,
5248 // see if static class implements all of id's protocols, directly or
5249 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005250 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005251 return false;
5252 }
5253 }
5254 // If there are no qualifiers and no interface, we have an 'id'.
5255 return true;
5256 }
Mike Stump11289f42009-09-09 15:08:12 +00005257 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005258 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5259 E = lhsQID->qual_end(); I != E; ++I) {
5260 ObjCProtocolDecl *lhsProto = *I;
5261 bool match = false;
5262
5263 // when comparing an id<P> on lhs with a static type on rhs,
5264 // see if static class implements all of id's protocols, directly or
5265 // through its super class and categories.
5266 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5267 E = rhsOPT->qual_end(); J != E; ++J) {
5268 ObjCProtocolDecl *rhsProto = *J;
5269 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5270 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5271 match = true;
5272 break;
5273 }
5274 }
Mike Stump11289f42009-09-09 15:08:12 +00005275 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005276 // make sure we check the class hierarchy.
5277 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5278 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5279 E = lhsQID->qual_end(); I != E; ++I) {
5280 // when comparing an id<P> on lhs with a static type on rhs,
5281 // see if static class implements all of id's protocols, directly or
5282 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005283 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005284 match = true;
5285 break;
5286 }
5287 }
5288 }
5289 if (!match)
5290 return false;
5291 }
Mike Stump11289f42009-09-09 15:08:12 +00005292
Steve Naroff8e6aee52009-07-23 01:01:38 +00005293 return true;
5294 }
Mike Stump11289f42009-09-09 15:08:12 +00005295
Steve Naroff8e6aee52009-07-23 01:01:38 +00005296 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5297 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5298
Mike Stump11289f42009-09-09 15:08:12 +00005299 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005300 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005301 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005302 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5303 E = lhsOPT->qual_end(); I != E; ++I) {
5304 ObjCProtocolDecl *lhsProto = *I;
5305 bool match = false;
5306
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005307 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005308 // see if static class implements all of id's protocols, directly or
5309 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005310 // First, lhs protocols in the qualifier list must be found, direct
5311 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005312 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5313 E = rhsQID->qual_end(); J != E; ++J) {
5314 ObjCProtocolDecl *rhsProto = *J;
5315 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5316 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5317 match = true;
5318 break;
5319 }
5320 }
5321 if (!match)
5322 return false;
5323 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005324
5325 // Static class's protocols, or its super class or category protocols
5326 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5327 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5328 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5329 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5330 // This is rather dubious but matches gcc's behavior. If lhs has
5331 // no type qualifier and its class has no static protocol(s)
5332 // assume that it is mismatch.
5333 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5334 return false;
5335 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5336 LHSInheritedProtocols.begin(),
5337 E = LHSInheritedProtocols.end(); I != E; ++I) {
5338 bool match = false;
5339 ObjCProtocolDecl *lhsProto = (*I);
5340 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5341 E = rhsQID->qual_end(); J != E; ++J) {
5342 ObjCProtocolDecl *rhsProto = *J;
5343 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5344 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5345 match = true;
5346 break;
5347 }
5348 }
5349 if (!match)
5350 return false;
5351 }
5352 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005353 return true;
5354 }
5355 return false;
5356}
5357
Eli Friedman47f77112008-08-22 00:56:42 +00005358/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005359/// compatible for assignment from RHS to LHS. This handles validation of any
5360/// protocol qualifiers on the LHS or RHS.
5361///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005362bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5363 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005364 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5365 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5366
Steve Naroff1329fa02009-07-15 18:40:39 +00005367 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005368 if (LHS->isObjCUnqualifiedIdOrClass() ||
5369 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005370 return true;
5371
John McCall8b07ec22010-05-15 11:32:37 +00005372 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005373 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5374 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005375 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005376
5377 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5378 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5379 QualType(RHSOPT,0));
5380
John McCall8b07ec22010-05-15 11:32:37 +00005381 // If we have 2 user-defined types, fall into that path.
5382 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005383 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005384
Steve Naroff8e6aee52009-07-23 01:01:38 +00005385 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005386}
5387
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005388/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005389/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005390/// arguments in block literals. When passed as arguments, passing 'A*' where
5391/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5392/// not OK. For the return type, the opposite is not OK.
5393bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5394 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005395 const ObjCObjectPointerType *RHSOPT,
5396 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005397 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005398 return true;
5399
5400 if (LHSOPT->isObjCBuiltinType()) {
5401 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5402 }
5403
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005404 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005405 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5406 QualType(RHSOPT,0),
5407 false);
5408
5409 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5410 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5411 if (LHS && RHS) { // We have 2 user-defined types.
5412 if (LHS != RHS) {
5413 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005414 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005415 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005416 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005417 }
5418 else
5419 return true;
5420 }
5421 return false;
5422}
5423
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005424/// getIntersectionOfProtocols - This routine finds the intersection of set
5425/// of protocols inherited from two distinct objective-c pointer objects.
5426/// It is used to build composite qualifier list of the composite type of
5427/// the conditional expression involving two objective-c pointer objects.
5428static
5429void getIntersectionOfProtocols(ASTContext &Context,
5430 const ObjCObjectPointerType *LHSOPT,
5431 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005432 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005433
John McCall8b07ec22010-05-15 11:32:37 +00005434 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5435 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5436 assert(LHS->getInterface() && "LHS must have an interface base");
5437 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005438
5439 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5440 unsigned LHSNumProtocols = LHS->getNumProtocols();
5441 if (LHSNumProtocols > 0)
5442 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5443 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005444 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005445 Context.CollectInheritedProtocols(LHS->getInterface(),
5446 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005447 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5448 LHSInheritedProtocols.end());
5449 }
5450
5451 unsigned RHSNumProtocols = RHS->getNumProtocols();
5452 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005453 ObjCProtocolDecl **RHSProtocols =
5454 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005455 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5456 if (InheritedProtocolSet.count(RHSProtocols[i]))
5457 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00005458 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005459 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005460 Context.CollectInheritedProtocols(RHS->getInterface(),
5461 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005462 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5463 RHSInheritedProtocols.begin(),
5464 E = RHSInheritedProtocols.end(); I != E; ++I)
5465 if (InheritedProtocolSet.count((*I)))
5466 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005467 }
5468}
5469
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005470/// areCommonBaseCompatible - Returns common base class of the two classes if
5471/// one found. Note that this is O'2 algorithm. But it will be called as the
5472/// last type comparison in a ?-exp of ObjC pointer types before a
5473/// warning is issued. So, its invokation is extremely rare.
5474QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005475 const ObjCObjectPointerType *Lptr,
5476 const ObjCObjectPointerType *Rptr) {
5477 const ObjCObjectType *LHS = Lptr->getObjectType();
5478 const ObjCObjectType *RHS = Rptr->getObjectType();
5479 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5480 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00005481 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005482 return QualType();
5483
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005484 do {
John McCall8b07ec22010-05-15 11:32:37 +00005485 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005486 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005487 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00005488 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5489
5490 QualType Result = QualType(LHS, 0);
5491 if (!Protocols.empty())
5492 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5493 Result = getObjCObjectPointerType(Result);
5494 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005495 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005496 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005497
5498 return QualType();
5499}
5500
John McCall8b07ec22010-05-15 11:32:37 +00005501bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5502 const ObjCObjectType *RHS) {
5503 assert(LHS->getInterface() && "LHS is not an interface type");
5504 assert(RHS->getInterface() && "RHS is not an interface type");
5505
Chris Lattner49af6a42008-04-07 06:51:04 +00005506 // Verify that the base decls are compatible: the RHS must be a subclass of
5507 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005508 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005509 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005510
Chris Lattner49af6a42008-04-07 06:51:04 +00005511 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5512 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005513 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005514 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005515
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005516 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5517 // more detailed analysis is required.
5518 if (RHS->getNumProtocols() == 0) {
5519 // OK, if LHS is a superclass of RHS *and*
5520 // this superclass is assignment compatible with LHS.
5521 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005522 bool IsSuperClass =
5523 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5524 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005525 // OK if conversion of LHS to SuperClass results in narrowing of types
5526 // ; i.e., SuperClass may implement at least one of the protocols
5527 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5528 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5529 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005530 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005531 // If super class has no protocols, it is not a match.
5532 if (SuperClassInheritedProtocols.empty())
5533 return false;
5534
5535 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5536 LHSPE = LHS->qual_end();
5537 LHSPI != LHSPE; LHSPI++) {
5538 bool SuperImplementsProtocol = false;
5539 ObjCProtocolDecl *LHSProto = (*LHSPI);
5540
5541 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5542 SuperClassInheritedProtocols.begin(),
5543 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5544 ObjCProtocolDecl *SuperClassProto = (*I);
5545 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5546 SuperImplementsProtocol = true;
5547 break;
5548 }
5549 }
5550 if (!SuperImplementsProtocol)
5551 return false;
5552 }
5553 return true;
5554 }
5555 return false;
5556 }
Mike Stump11289f42009-09-09 15:08:12 +00005557
John McCall8b07ec22010-05-15 11:32:37 +00005558 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5559 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005560 LHSPI != LHSPE; LHSPI++) {
5561 bool RHSImplementsProtocol = false;
5562
5563 // If the RHS doesn't implement the protocol on the left, the types
5564 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005565 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5566 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005567 RHSPI != RHSPE; RHSPI++) {
5568 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005569 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005570 break;
5571 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005572 }
5573 // FIXME: For better diagnostics, consider passing back the protocol name.
5574 if (!RHSImplementsProtocol)
5575 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005576 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005577 // The RHS implements all protocols listed on the LHS.
5578 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005579}
5580
Steve Naroffb7605152009-02-12 17:52:19 +00005581bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5582 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005583 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5584 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005585
Steve Naroff7cae42b2009-07-10 23:34:53 +00005586 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005587 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005588
5589 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5590 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005591}
5592
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005593bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5594 return canAssignObjCInterfaces(
5595 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5596 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5597}
5598
Mike Stump11289f42009-09-09 15:08:12 +00005599/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005600/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005601/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005602/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005603bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5604 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00005605 if (getLangOptions().CPlusPlus)
5606 return hasSameType(LHS, RHS);
5607
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005608 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005609}
5610
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005611bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00005612 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005613}
5614
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005615bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5616 return !mergeTypes(LHS, RHS, true).isNull();
5617}
5618
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005619/// mergeTransparentUnionType - if T is a transparent union type and a member
5620/// of T is compatible with SubType, return the merged type, else return
5621/// QualType()
5622QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5623 bool OfBlockPointer,
5624 bool Unqualified) {
5625 if (const RecordType *UT = T->getAsUnionType()) {
5626 RecordDecl *UD = UT->getDecl();
5627 if (UD->hasAttr<TransparentUnionAttr>()) {
5628 for (RecordDecl::field_iterator it = UD->field_begin(),
5629 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005630 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005631 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5632 if (!MT.isNull())
5633 return MT;
5634 }
5635 }
5636 }
5637
5638 return QualType();
5639}
5640
5641/// mergeFunctionArgumentTypes - merge two types which appear as function
5642/// argument types
5643QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5644 bool OfBlockPointer,
5645 bool Unqualified) {
5646 // GNU extension: two types are compatible if they appear as a function
5647 // argument, one of the types is a transparent union type and the other
5648 // type is compatible with a union member
5649 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5650 Unqualified);
5651 if (!lmerge.isNull())
5652 return lmerge;
5653
5654 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5655 Unqualified);
5656 if (!rmerge.isNull())
5657 return rmerge;
5658
5659 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5660}
5661
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005662QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005663 bool OfBlockPointer,
5664 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005665 const FunctionType *lbase = lhs->getAs<FunctionType>();
5666 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005667 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5668 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005669 bool allLTypes = true;
5670 bool allRTypes = true;
5671
5672 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005673 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00005674 if (OfBlockPointer) {
5675 QualType RHS = rbase->getResultType();
5676 QualType LHS = lbase->getResultType();
5677 bool UnqualifiedResult = Unqualified;
5678 if (!UnqualifiedResult)
5679 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005680 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00005681 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005682 else
John McCall8c6b56f2010-12-15 01:06:38 +00005683 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5684 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005685 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005686
5687 if (Unqualified)
5688 retType = retType.getUnqualifiedType();
5689
5690 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5691 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5692 if (Unqualified) {
5693 LRetType = LRetType.getUnqualifiedType();
5694 RRetType = RRetType.getUnqualifiedType();
5695 }
5696
5697 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005698 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005699 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005700 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005701
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005702 // FIXME: double check this
5703 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5704 // rbase->getRegParmAttr() != 0 &&
5705 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005706 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5707 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005708
Douglas Gregor8c940862010-01-18 17:14:39 +00005709 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005710 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005711 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005712
John McCall8c6b56f2010-12-15 01:06:38 +00005713 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00005714 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5715 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00005716 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5717 return QualType();
5718
John McCall31168b02011-06-15 23:02:42 +00005719 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5720 return QualType();
5721
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005722 // functypes which return are preferred over those that do not.
5723 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5724 allLTypes = false;
5725 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5726 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005727 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5728 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00005729
John McCall31168b02011-06-15 23:02:42 +00005730 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00005731
Eli Friedman47f77112008-08-22 00:56:42 +00005732 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005733 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5734 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005735 unsigned lproto_nargs = lproto->getNumArgs();
5736 unsigned rproto_nargs = rproto->getNumArgs();
5737
5738 // Compatible functions must have the same number of arguments
5739 if (lproto_nargs != rproto_nargs)
5740 return QualType();
5741
5742 // Variadic and non-variadic functions aren't compatible
5743 if (lproto->isVariadic() != rproto->isVariadic())
5744 return QualType();
5745
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005746 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5747 return QualType();
5748
Fariborz Jahanian97676972011-09-28 21:52:05 +00005749 if (LangOpts.ObjCAutoRefCount &&
5750 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5751 return QualType();
5752
Eli Friedman47f77112008-08-22 00:56:42 +00005753 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005754 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00005755 for (unsigned i = 0; i < lproto_nargs; i++) {
5756 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5757 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005758 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5759 OfBlockPointer,
5760 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005761 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005762
5763 if (Unqualified)
5764 argtype = argtype.getUnqualifiedType();
5765
Eli Friedman47f77112008-08-22 00:56:42 +00005766 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005767 if (Unqualified) {
5768 largtype = largtype.getUnqualifiedType();
5769 rargtype = rargtype.getUnqualifiedType();
5770 }
5771
Chris Lattner465fa322008-10-05 17:34:18 +00005772 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5773 allLTypes = false;
5774 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5775 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005776 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00005777
Eli Friedman47f77112008-08-22 00:56:42 +00005778 if (allLTypes) return lhs;
5779 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005780
5781 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5782 EPI.ExtInfo = einfo;
5783 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005784 }
5785
5786 if (lproto) allRTypes = false;
5787 if (rproto) allLTypes = false;
5788
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005789 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005790 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005791 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005792 if (proto->isVariadic()) return QualType();
5793 // Check that the types are compatible with the types that
5794 // would result from default argument promotions (C99 6.7.5.3p15).
5795 // The only types actually affected are promotable integer
5796 // types and floats, which would be passed as a different
5797 // type depending on whether the prototype is visible.
5798 unsigned proto_nargs = proto->getNumArgs();
5799 for (unsigned i = 0; i < proto_nargs; ++i) {
5800 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005801
5802 // Look at the promotion type of enum types, since that is the type used
5803 // to pass enum values.
5804 if (const EnumType *Enum = argTy->getAs<EnumType>())
5805 argTy = Enum->getDecl()->getPromotionType();
5806
Eli Friedman47f77112008-08-22 00:56:42 +00005807 if (argTy->isPromotableIntegerType() ||
5808 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5809 return QualType();
5810 }
5811
5812 if (allLTypes) return lhs;
5813 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005814
5815 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5816 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005817 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005818 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005819 }
5820
5821 if (allLTypes) return lhs;
5822 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005823 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005824}
5825
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005826QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005827 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005828 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005829 // C++ [expr]: If an expression initially has the type "reference to T", the
5830 // type is adjusted to "T" prior to any further analysis, the expression
5831 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005832 // expression is an lvalue unless the reference is an rvalue reference and
5833 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005834 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5835 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005836
5837 if (Unqualified) {
5838 LHS = LHS.getUnqualifiedType();
5839 RHS = RHS.getUnqualifiedType();
5840 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005841
Eli Friedman47f77112008-08-22 00:56:42 +00005842 QualType LHSCan = getCanonicalType(LHS),
5843 RHSCan = getCanonicalType(RHS);
5844
5845 // If two types are identical, they are compatible.
5846 if (LHSCan == RHSCan)
5847 return LHS;
5848
John McCall8ccfcb52009-09-24 19:53:00 +00005849 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005850 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5851 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005852 if (LQuals != RQuals) {
5853 // If any of these qualifiers are different, we have a type
5854 // mismatch.
5855 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00005856 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5857 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00005858 return QualType();
5859
5860 // Exactly one GC qualifier difference is allowed: __strong is
5861 // okay if the other type has no GC qualifier but is an Objective
5862 // C object pointer (i.e. implicitly strong by default). We fix
5863 // this by pretending that the unqualified type was actually
5864 // qualified __strong.
5865 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5866 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5867 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5868
5869 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5870 return QualType();
5871
5872 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5873 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5874 }
5875 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5876 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5877 }
Eli Friedman47f77112008-08-22 00:56:42 +00005878 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005879 }
5880
5881 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005882
Eli Friedmandcca6332009-06-01 01:22:52 +00005883 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5884 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005885
Chris Lattnerfd652912008-01-14 05:45:46 +00005886 // We want to consider the two function types to be the same for these
5887 // comparisons, just force one to the other.
5888 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5889 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005890
5891 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005892 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5893 LHSClass = Type::ConstantArray;
5894 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5895 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005896
John McCall8b07ec22010-05-15 11:32:37 +00005897 // ObjCInterfaces are just specialized ObjCObjects.
5898 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5899 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5900
Nate Begemance4d7fc2008-04-18 23:10:10 +00005901 // Canonicalize ExtVector -> Vector.
5902 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5903 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005904
Chris Lattner95554662008-04-07 05:43:21 +00005905 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005906 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005907 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005908 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005909 // Compatibility is based on the underlying type, not the promotion
5910 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005911 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00005912 QualType TINT = ETy->getDecl()->getIntegerType();
5913 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00005914 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005915 }
John McCall9dd450b2009-09-21 23:43:11 +00005916 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00005917 QualType TINT = ETy->getDecl()->getIntegerType();
5918 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00005919 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005920 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00005921 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00005922 if (OfBlockPointer && !BlockReturnType) {
5923 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
5924 return LHS;
5925 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
5926 return RHS;
5927 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00005928
Eli Friedman47f77112008-08-22 00:56:42 +00005929 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005930 }
Eli Friedman47f77112008-08-22 00:56:42 +00005931
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005932 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005933 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005934#define TYPE(Class, Base)
5935#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005936#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005937#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5938#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5939#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00005940 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005941
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005942 case Type::LValueReference:
5943 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005944 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00005945 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005946
John McCall8b07ec22010-05-15 11:32:37 +00005947 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005948 case Type::IncompleteArray:
5949 case Type::VariableArray:
5950 case Type::FunctionProto:
5951 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00005952 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005953
Chris Lattnerfd652912008-01-14 05:45:46 +00005954 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005955 {
5956 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005957 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5958 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005959 if (Unqualified) {
5960 LHSPointee = LHSPointee.getUnqualifiedType();
5961 RHSPointee = RHSPointee.getUnqualifiedType();
5962 }
5963 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5964 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005965 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005966 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005967 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005968 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005969 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005970 return getPointerType(ResultType);
5971 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005972 case Type::BlockPointer:
5973 {
5974 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005975 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5976 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005977 if (Unqualified) {
5978 LHSPointee = LHSPointee.getUnqualifiedType();
5979 RHSPointee = RHSPointee.getUnqualifiedType();
5980 }
5981 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5982 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005983 if (ResultType.isNull()) return QualType();
5984 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5985 return LHS;
5986 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5987 return RHS;
5988 return getBlockPointerType(ResultType);
5989 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00005990 case Type::Atomic:
5991 {
5992 // Merge two pointer types, while trying to preserve typedef info
5993 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
5994 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
5995 if (Unqualified) {
5996 LHSValue = LHSValue.getUnqualifiedType();
5997 RHSValue = RHSValue.getUnqualifiedType();
5998 }
5999 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6000 Unqualified);
6001 if (ResultType.isNull()) return QualType();
6002 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6003 return LHS;
6004 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6005 return RHS;
6006 return getAtomicType(ResultType);
6007 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006008 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006009 {
6010 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6011 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6012 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6013 return QualType();
6014
6015 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6016 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006017 if (Unqualified) {
6018 LHSElem = LHSElem.getUnqualifiedType();
6019 RHSElem = RHSElem.getUnqualifiedType();
6020 }
6021
6022 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006023 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006024 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6025 return LHS;
6026 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6027 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006028 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6029 ArrayType::ArraySizeModifier(), 0);
6030 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6031 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006032 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6033 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006034 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6035 return LHS;
6036 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6037 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006038 if (LVAT) {
6039 // FIXME: This isn't correct! But tricky to implement because
6040 // the array's size has to be the size of LHS, but the type
6041 // has to be different.
6042 return LHS;
6043 }
6044 if (RVAT) {
6045 // FIXME: This isn't correct! But tricky to implement because
6046 // the array's size has to be the size of RHS, but the type
6047 // has to be different.
6048 return RHS;
6049 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006050 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6051 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006052 return getIncompleteArrayType(ResultType,
6053 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006054 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006055 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006056 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006057 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006058 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006059 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006060 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006061 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006062 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006063 case Type::Complex:
6064 // Distinct complex types are incompatible.
6065 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006066 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006067 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006068 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6069 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006070 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006071 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006072 case Type::ObjCObject: {
6073 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006074 // FIXME: This should be type compatibility, e.g. whether
6075 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006076 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6077 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6078 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006079 return LHS;
6080
Eli Friedman47f77112008-08-22 00:56:42 +00006081 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006082 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006083 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006084 if (OfBlockPointer) {
6085 if (canAssignObjCInterfacesInBlockPointer(
6086 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006087 RHS->getAs<ObjCObjectPointerType>(),
6088 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006089 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006090 return QualType();
6091 }
John McCall9dd450b2009-09-21 23:43:11 +00006092 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6093 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006094 return LHS;
6095
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006096 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006097 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006098 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006099
David Blaikie8a40f702012-01-17 06:56:22 +00006100 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006101}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006102
Fariborz Jahanian97676972011-09-28 21:52:05 +00006103bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6104 const FunctionProtoType *FromFunctionType,
6105 const FunctionProtoType *ToFunctionType) {
6106 if (FromFunctionType->hasAnyConsumedArgs() !=
6107 ToFunctionType->hasAnyConsumedArgs())
6108 return false;
6109 FunctionProtoType::ExtProtoInfo FromEPI =
6110 FromFunctionType->getExtProtoInfo();
6111 FunctionProtoType::ExtProtoInfo ToEPI =
6112 ToFunctionType->getExtProtoInfo();
6113 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6114 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6115 ArgIdx != NumArgs; ++ArgIdx) {
6116 if (FromEPI.ConsumedArguments[ArgIdx] !=
6117 ToEPI.ConsumedArguments[ArgIdx])
6118 return false;
6119 }
6120 return true;
6121}
6122
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006123/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6124/// 'RHS' attributes and returns the merged version; including for function
6125/// return types.
6126QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6127 QualType LHSCan = getCanonicalType(LHS),
6128 RHSCan = getCanonicalType(RHS);
6129 // If two types are identical, they are compatible.
6130 if (LHSCan == RHSCan)
6131 return LHS;
6132 if (RHSCan->isFunctionType()) {
6133 if (!LHSCan->isFunctionType())
6134 return QualType();
6135 QualType OldReturnType =
6136 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6137 QualType NewReturnType =
6138 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6139 QualType ResReturnType =
6140 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6141 if (ResReturnType.isNull())
6142 return QualType();
6143 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6144 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6145 // In either case, use OldReturnType to build the new function type.
6146 const FunctionType *F = LHS->getAs<FunctionType>();
6147 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006148 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6149 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006150 QualType ResultType
6151 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006152 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006153 return ResultType;
6154 }
6155 }
6156 return QualType();
6157 }
6158
6159 // If the qualifiers are different, the types can still be merged.
6160 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6161 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6162 if (LQuals != RQuals) {
6163 // If any of these qualifiers are different, we have a type mismatch.
6164 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6165 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6166 return QualType();
6167
6168 // Exactly one GC qualifier difference is allowed: __strong is
6169 // okay if the other type has no GC qualifier but is an Objective
6170 // C object pointer (i.e. implicitly strong by default). We fix
6171 // this by pretending that the unqualified type was actually
6172 // qualified __strong.
6173 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6174 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6175 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6176
6177 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6178 return QualType();
6179
6180 if (GC_L == Qualifiers::Strong)
6181 return LHS;
6182 if (GC_R == Qualifiers::Strong)
6183 return RHS;
6184 return QualType();
6185 }
6186
6187 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6188 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6189 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6190 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6191 if (ResQT == LHSBaseQT)
6192 return LHS;
6193 if (ResQT == RHSBaseQT)
6194 return RHS;
6195 }
6196 return QualType();
6197}
6198
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006199//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006200// Integer Predicates
6201//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006202
Jay Foad39c79802011-01-12 09:06:06 +00006203unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006204 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006205 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006206 if (T->isBooleanType())
6207 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006208 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006209 return (unsigned)getTypeSize(T);
6210}
6211
6212QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006213 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006214
6215 // Turn <4 x signed int> -> <4 x unsigned int>
6216 if (const VectorType *VTy = T->getAs<VectorType>())
6217 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006218 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006219
6220 // For enums, we return the unsigned version of the base type.
6221 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006222 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006223
6224 const BuiltinType *BTy = T->getAs<BuiltinType>();
6225 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006226 switch (BTy->getKind()) {
6227 case BuiltinType::Char_S:
6228 case BuiltinType::SChar:
6229 return UnsignedCharTy;
6230 case BuiltinType::Short:
6231 return UnsignedShortTy;
6232 case BuiltinType::Int:
6233 return UnsignedIntTy;
6234 case BuiltinType::Long:
6235 return UnsignedLongTy;
6236 case BuiltinType::LongLong:
6237 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006238 case BuiltinType::Int128:
6239 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006240 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006241 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006242 }
6243}
6244
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006245ASTMutationListener::~ASTMutationListener() { }
6246
Chris Lattnerecd79c62009-06-14 00:45:47 +00006247
6248//===----------------------------------------------------------------------===//
6249// Builtin Type Computation
6250//===----------------------------------------------------------------------===//
6251
6252/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006253/// pointer over the consumed characters. This returns the resultant type. If
6254/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6255/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6256/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006257///
6258/// RequiresICE is filled in on return to indicate whether the value is required
6259/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006260static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006261 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006262 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006263 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006264 // Modifiers.
6265 int HowLong = 0;
6266 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006267 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006268
Chris Lattnerdc226c22010-10-01 22:42:38 +00006269 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006270 bool Done = false;
6271 while (!Done) {
6272 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006273 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006274 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006275 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006276 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006277 case 'S':
6278 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6279 assert(!Signed && "Can't use 'S' modifier multiple times!");
6280 Signed = true;
6281 break;
6282 case 'U':
6283 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6284 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6285 Unsigned = true;
6286 break;
6287 case 'L':
6288 assert(HowLong <= 2 && "Can't have LLLL modifier");
6289 ++HowLong;
6290 break;
6291 }
6292 }
6293
6294 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006295
Chris Lattnerecd79c62009-06-14 00:45:47 +00006296 // Read the base type.
6297 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006298 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006299 case 'v':
6300 assert(HowLong == 0 && !Signed && !Unsigned &&
6301 "Bad modifiers used with 'v'!");
6302 Type = Context.VoidTy;
6303 break;
6304 case 'f':
6305 assert(HowLong == 0 && !Signed && !Unsigned &&
6306 "Bad modifiers used with 'f'!");
6307 Type = Context.FloatTy;
6308 break;
6309 case 'd':
6310 assert(HowLong < 2 && !Signed && !Unsigned &&
6311 "Bad modifiers used with 'd'!");
6312 if (HowLong)
6313 Type = Context.LongDoubleTy;
6314 else
6315 Type = Context.DoubleTy;
6316 break;
6317 case 's':
6318 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6319 if (Unsigned)
6320 Type = Context.UnsignedShortTy;
6321 else
6322 Type = Context.ShortTy;
6323 break;
6324 case 'i':
6325 if (HowLong == 3)
6326 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6327 else if (HowLong == 2)
6328 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6329 else if (HowLong == 1)
6330 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6331 else
6332 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6333 break;
6334 case 'c':
6335 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6336 if (Signed)
6337 Type = Context.SignedCharTy;
6338 else if (Unsigned)
6339 Type = Context.UnsignedCharTy;
6340 else
6341 Type = Context.CharTy;
6342 break;
6343 case 'b': // boolean
6344 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6345 Type = Context.BoolTy;
6346 break;
6347 case 'z': // size_t.
6348 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6349 Type = Context.getSizeType();
6350 break;
6351 case 'F':
6352 Type = Context.getCFConstantStringType();
6353 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006354 case 'G':
6355 Type = Context.getObjCIdType();
6356 break;
6357 case 'H':
6358 Type = Context.getObjCSelType();
6359 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006360 case 'a':
6361 Type = Context.getBuiltinVaListType();
6362 assert(!Type.isNull() && "builtin va list type not initialized!");
6363 break;
6364 case 'A':
6365 // This is a "reference" to a va_list; however, what exactly
6366 // this means depends on how va_list is defined. There are two
6367 // different kinds of va_list: ones passed by value, and ones
6368 // passed by reference. An example of a by-value va_list is
6369 // x86, where va_list is a char*. An example of by-ref va_list
6370 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6371 // we want this argument to be a char*&; for x86-64, we want
6372 // it to be a __va_list_tag*.
6373 Type = Context.getBuiltinVaListType();
6374 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006375 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006376 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006377 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006378 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006379 break;
6380 case 'V': {
6381 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006382 unsigned NumElements = strtoul(Str, &End, 10);
6383 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006384 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006385
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006386 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6387 RequiresICE, false);
6388 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006389
6390 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006391 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006392 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006393 break;
6394 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006395 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006396 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6397 false);
6398 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006399 Type = Context.getComplexType(ElementType);
6400 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00006401 }
6402 case 'Y' : {
6403 Type = Context.getPointerDiffType();
6404 break;
6405 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006406 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006407 Type = Context.getFILEType();
6408 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006409 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006410 return QualType();
6411 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006412 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006413 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006414 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006415 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006416 else
6417 Type = Context.getjmp_bufType();
6418
Mike Stump2adb4da2009-07-28 23:47:15 +00006419 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006420 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006421 return QualType();
6422 }
6423 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00006424 case 'K':
6425 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6426 Type = Context.getucontext_tType();
6427
6428 if (Type.isNull()) {
6429 Error = ASTContext::GE_Missing_ucontext;
6430 return QualType();
6431 }
6432 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006433 }
Mike Stump11289f42009-09-09 15:08:12 +00006434
Chris Lattnerdc226c22010-10-01 22:42:38 +00006435 // If there are modifiers and if we're allowed to parse them, go for it.
6436 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006437 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006438 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006439 default: Done = true; --Str; break;
6440 case '*':
6441 case '&': {
6442 // Both pointers and references can have their pointee types
6443 // qualified with an address space.
6444 char *End;
6445 unsigned AddrSpace = strtoul(Str, &End, 10);
6446 if (End != Str && AddrSpace != 0) {
6447 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6448 Str = End;
6449 }
6450 if (c == '*')
6451 Type = Context.getPointerType(Type);
6452 else
6453 Type = Context.getLValueReferenceType(Type);
6454 break;
6455 }
6456 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6457 case 'C':
6458 Type = Type.withConst();
6459 break;
6460 case 'D':
6461 Type = Context.getVolatileType(Type);
6462 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00006463 case 'R':
6464 Type = Type.withRestrict();
6465 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006466 }
6467 }
Chris Lattner84733392010-10-01 07:13:18 +00006468
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006469 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006470 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006471
Chris Lattnerecd79c62009-06-14 00:45:47 +00006472 return Type;
6473}
6474
6475/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006476QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006477 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006478 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006479 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006480
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006481 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006482
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006483 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006484 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006485 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6486 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006487 if (Error != GE_None)
6488 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006489
6490 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6491
Chris Lattnerecd79c62009-06-14 00:45:47 +00006492 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006493 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006494 if (Error != GE_None)
6495 return QualType();
6496
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006497 // If this argument is required to be an IntegerConstantExpression and the
6498 // caller cares, fill in the bitmask we return.
6499 if (RequiresICE && IntegerConstantArgs)
6500 *IntegerConstantArgs |= 1 << ArgTypes.size();
6501
Chris Lattnerecd79c62009-06-14 00:45:47 +00006502 // Do array -> pointer decay. The builtin should use the decayed type.
6503 if (Ty->isArrayType())
6504 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006505
Chris Lattnerecd79c62009-06-14 00:45:47 +00006506 ArgTypes.push_back(Ty);
6507 }
6508
6509 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6510 "'.' should only occur at end of builtin type list!");
6511
John McCall991eb4b2010-12-21 00:44:39 +00006512 FunctionType::ExtInfo EI;
6513 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6514
6515 bool Variadic = (TypeStr[0] == '.');
6516
6517 // We really shouldn't be making a no-proto type here, especially in C++.
6518 if (ArgTypes.empty() && Variadic)
6519 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006520
John McCalldb40c7f2010-12-14 08:05:40 +00006521 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006522 EPI.ExtInfo = EI;
6523 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006524
6525 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006526}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006527
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006528GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6529 GVALinkage External = GVA_StrongExternal;
6530
6531 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006532 switch (L) {
6533 case NoLinkage:
6534 case InternalLinkage:
6535 case UniqueExternalLinkage:
6536 return GVA_Internal;
6537
6538 case ExternalLinkage:
6539 switch (FD->getTemplateSpecializationKind()) {
6540 case TSK_Undeclared:
6541 case TSK_ExplicitSpecialization:
6542 External = GVA_StrongExternal;
6543 break;
6544
6545 case TSK_ExplicitInstantiationDefinition:
6546 return GVA_ExplicitTemplateInstantiation;
6547
6548 case TSK_ExplicitInstantiationDeclaration:
6549 case TSK_ImplicitInstantiation:
6550 External = GVA_TemplateInstantiation;
6551 break;
6552 }
6553 }
6554
6555 if (!FD->isInlined())
6556 return External;
6557
6558 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6559 // GNU or C99 inline semantics. Determine whether this symbol should be
6560 // externally visible.
6561 if (FD->isInlineDefinitionExternallyVisible())
6562 return External;
6563
6564 // C99 inline semantics, where the symbol is not externally visible.
6565 return GVA_C99Inline;
6566 }
6567
6568 // C++0x [temp.explicit]p9:
6569 // [ Note: The intent is that an inline function that is the subject of
6570 // an explicit instantiation declaration will still be implicitly
6571 // instantiated when used so that the body can be considered for
6572 // inlining, but that no out-of-line copy of the inline function would be
6573 // generated in the translation unit. -- end note ]
6574 if (FD->getTemplateSpecializationKind()
6575 == TSK_ExplicitInstantiationDeclaration)
6576 return GVA_C99Inline;
6577
6578 return GVA_CXXInline;
6579}
6580
6581GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6582 // If this is a static data member, compute the kind of template
6583 // specialization. Otherwise, this variable is not part of a
6584 // template.
6585 TemplateSpecializationKind TSK = TSK_Undeclared;
6586 if (VD->isStaticDataMember())
6587 TSK = VD->getTemplateSpecializationKind();
6588
6589 Linkage L = VD->getLinkage();
6590 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6591 VD->getType()->getLinkage() == UniqueExternalLinkage)
6592 L = UniqueExternalLinkage;
6593
6594 switch (L) {
6595 case NoLinkage:
6596 case InternalLinkage:
6597 case UniqueExternalLinkage:
6598 return GVA_Internal;
6599
6600 case ExternalLinkage:
6601 switch (TSK) {
6602 case TSK_Undeclared:
6603 case TSK_ExplicitSpecialization:
6604 return GVA_StrongExternal;
6605
6606 case TSK_ExplicitInstantiationDeclaration:
6607 llvm_unreachable("Variable should not be instantiated");
6608 // Fall through to treat this like any other instantiation.
6609
6610 case TSK_ExplicitInstantiationDefinition:
6611 return GVA_ExplicitTemplateInstantiation;
6612
6613 case TSK_ImplicitInstantiation:
6614 return GVA_TemplateInstantiation;
6615 }
6616 }
6617
David Blaikie8a40f702012-01-17 06:56:22 +00006618 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006619}
6620
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00006621bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006622 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6623 if (!VD->isFileVarDecl())
6624 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00006625 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006626 return false;
6627
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006628 // Weak references don't produce any output by themselves.
6629 if (D->hasAttr<WeakRefAttr>())
6630 return false;
6631
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006632 // Aliases and used decls are required.
6633 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6634 return true;
6635
6636 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6637 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00006638 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00006639 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006640
6641 // Constructors and destructors are required.
6642 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6643 return true;
6644
6645 // The key function for a class is required.
6646 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6647 const CXXRecordDecl *RD = MD->getParent();
6648 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6649 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6650 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6651 return true;
6652 }
6653 }
6654
6655 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6656
6657 // static, static inline, always_inline, and extern inline functions can
6658 // always be deferred. Normal inline functions can be deferred in C99/C++.
6659 // Implicit template instantiations can also be deferred in C++.
6660 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00006661 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006662 return false;
6663 return true;
6664 }
Douglas Gregor87d81242011-09-10 00:22:34 +00006665
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006666 const VarDecl *VD = cast<VarDecl>(D);
6667 assert(VD->isFileVarDecl() && "Expected file scoped var");
6668
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006669 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6670 return false;
6671
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006672 // Structs that have non-trivial constructors or destructors are required.
6673
6674 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00006675 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006676 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6677 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00006678 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6679 RD->hasTrivialCopyConstructor() &&
6680 RD->hasTrivialMoveConstructor() &&
6681 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006682 return true;
6683 }
6684 }
6685
6686 GVALinkage L = GetGVALinkageForVariable(VD);
6687 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6688 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6689 return false;
6690 }
6691
6692 return true;
6693}
Charles Davis53c59df2010-08-16 03:33:14 +00006694
Charles Davis99202b32010-11-09 18:04:24 +00006695CallingConv ASTContext::getDefaultMethodCallConv() {
6696 // Pass through to the C++ ABI object
6697 return ABI->getDefaultMethodCallConv();
6698}
6699
Jay Foad39c79802011-01-12 09:06:06 +00006700bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00006701 // Pass through to the C++ ABI object
6702 return ABI->isNearlyEmpty(RD);
6703}
6704
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006705MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00006706 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006707 case CXXABI_ARM:
6708 case CXXABI_Itanium:
6709 return createItaniumMangleContext(*this, getDiagnostics());
6710 case CXXABI_Microsoft:
6711 return createMicrosoftMangleContext(*this, getDiagnostics());
6712 }
David Blaikie83d382b2011-09-23 05:06:16 +00006713 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006714}
6715
Charles Davis53c59df2010-08-16 03:33:14 +00006716CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006717
6718size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00006719 return ASTRecordLayouts.getMemorySize()
6720 + llvm::capacity_in_bytes(ObjCLayouts)
6721 + llvm::capacity_in_bytes(KeyFunctions)
6722 + llvm::capacity_in_bytes(ObjCImpls)
6723 + llvm::capacity_in_bytes(BlockVarCopyInits)
6724 + llvm::capacity_in_bytes(DeclAttrs)
6725 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6726 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6727 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6728 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6729 + llvm::capacity_in_bytes(OverriddenMethods)
6730 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006731 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00006732 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006733}
Ted Kremenek540017e2011-10-06 05:00:56 +00006734
Douglas Gregor63798542012-02-20 19:44:39 +00006735unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
6736 CXXRecordDecl *Lambda = CallOperator->getParent();
6737 return LambdaMangleContexts[Lambda->getDeclContext()]
6738 .getManglingNumber(CallOperator);
6739}
6740
6741
Ted Kremenek540017e2011-10-06 05:00:56 +00006742void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6743 ParamIndices[D] = index;
6744}
6745
6746unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6747 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6748 assert(I != ParamIndices.end() &&
6749 "ParmIndices lacks entry set by ParmVarDecl");
6750 return I->second;
6751}