blob: b625655e45f94514aba8b365a388b10c3e7344c8 [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Ted Kremenek7d39c9a2011-07-27 18:41:12 +000033#include "llvm/Support/Capacity.h"
Charles Davis53c59df2010-08-16 03:33:14 +000034#include "CXXABI.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000035#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000036
Chris Lattnerddc135e2006-11-10 06:34:16 +000037using namespace clang;
38
Douglas Gregor9672f922010-07-03 00:47:00 +000039unsigned ASTContext::NumImplicitDefaultConstructors;
40unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000041unsigned ASTContext::NumImplicitCopyConstructors;
42unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000043unsigned ASTContext::NumImplicitMoveConstructors;
44unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000045unsigned ASTContext::NumImplicitCopyAssignmentOperators;
46unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000047unsigned ASTContext::NumImplicitMoveAssignmentOperators;
48unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000049unsigned ASTContext::NumImplicitDestructors;
50unsigned ASTContext::NumImplicitDestructorsDeclared;
51
Steve Naroff0af91202007-04-27 21:51:21 +000052enum FloatingRank {
53 FloatRank, DoubleRank, LongDoubleRank
54};
55
Douglas Gregor7dbfb462010-06-16 21:09:37 +000056void
57ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
58 TemplateTemplateParmDecl *Parm) {
59 ID.AddInteger(Parm->getDepth());
60 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +000061 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000062
63 TemplateParameterList *Params = Parm->getTemplateParameters();
64 ID.AddInteger(Params->size());
65 for (TemplateParameterList::const_iterator P = Params->begin(),
66 PEnd = Params->end();
67 P != PEnd; ++P) {
68 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
69 ID.AddInteger(0);
70 ID.AddBoolean(TTP->isParameterPack());
71 continue;
72 }
73
74 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
75 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +000076 ID.AddBoolean(NTTP->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000077 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +000078 if (NTTP->isExpandedParameterPack()) {
79 ID.AddBoolean(true);
80 ID.AddInteger(NTTP->getNumExpansionTypes());
81 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
82 ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
83 } else
84 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +000085 continue;
86 }
87
88 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
89 ID.AddInteger(2);
90 Profile(ID, TTP);
91 }
92}
93
94TemplateTemplateParmDecl *
95ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +000096 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +000097 // Check if we already have a canonical template template parameter.
98 llvm::FoldingSetNodeID ID;
99 CanonicalTemplateTemplateParm::Profile(ID, TTP);
100 void *InsertPos = 0;
101 CanonicalTemplateTemplateParm *Canonical
102 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
103 if (Canonical)
104 return Canonical->getParam();
105
106 // Build a canonical template parameter list.
107 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000108 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000109 CanonParams.reserve(Params->size());
110 for (TemplateParameterList::const_iterator P = Params->begin(),
111 PEnd = Params->end();
112 P != PEnd; ++P) {
113 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
114 CanonParams.push_back(
115 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000116 SourceLocation(),
117 SourceLocation(),
118 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000119 TTP->getIndex(), 0, false,
120 TTP->isParameterPack()));
121 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000122 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
123 QualType T = getCanonicalType(NTTP->getType());
124 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
125 NonTypeTemplateParmDecl *Param;
126 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000127 SmallVector<QualType, 2> ExpandedTypes;
128 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000129 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
130 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
131 ExpandedTInfos.push_back(
132 getTrivialTypeSourceInfo(ExpandedTypes.back()));
133 }
134
135 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000136 SourceLocation(),
137 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000138 NTTP->getDepth(),
139 NTTP->getPosition(), 0,
140 T,
141 TInfo,
142 ExpandedTypes.data(),
143 ExpandedTypes.size(),
144 ExpandedTInfos.data());
145 } else {
146 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000147 SourceLocation(),
148 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000149 NTTP->getDepth(),
150 NTTP->getPosition(), 0,
151 T,
152 NTTP->isParameterPack(),
153 TInfo);
154 }
155 CanonParams.push_back(Param);
156
157 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000158 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
159 cast<TemplateTemplateParmDecl>(*P)));
160 }
161
162 TemplateTemplateParmDecl *CanonTTP
163 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
164 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000165 TTP->getPosition(),
166 TTP->isParameterPack(),
167 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000168 TemplateParameterList::Create(*this, SourceLocation(),
169 SourceLocation(),
170 CanonParams.data(),
171 CanonParams.size(),
172 SourceLocation()));
173
174 // Get the new insert position for the node we care about.
175 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
176 assert(Canonical == 0 && "Shouldn't be in the map!");
177 (void)Canonical;
178
179 // Create the canonical template template parameter entry.
180 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
181 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
182 return CanonTTP;
183}
184
Charles Davis53c59df2010-08-16 03:33:14 +0000185CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000186 if (!LangOpts.CPlusPlus) return 0;
187
Charles Davis6bcb07a2010-08-19 02:18:14 +0000188 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000189 case CXXABI_ARM:
190 return CreateARMCXXABI(*this);
191 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000192 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000193 case CXXABI_Microsoft:
194 return CreateMicrosoftCXXABI(*this);
195 }
John McCall86353412010-08-21 22:46:04 +0000196 return 0;
Charles Davis53c59df2010-08-16 03:33:14 +0000197}
198
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),
227 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000228 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000229 FILEDecl(0),
230 jmp_bufDecl(0), sigjmp_bufDecl(0), BlockDescriptorType(0),
231 BlockDescriptorExtendedType(0), cudaConfigureCallDecl(0),
232 NullTypeSourceInfo(QualType()),
233 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000234 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000235 Idents(idents), Selectors(sels),
236 BuiltinInfo(builtins),
237 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000238 ExternalSource(0), Listener(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000239 LastSDM(0, 0),
240 UniqueBlockByRefTypeID(0)
241{
Mike Stump11289f42009-09-09 15:08:12 +0000242 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000243 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000244
245 if (!DelayInitialization) {
246 assert(t && "No target supplied for ASTContext initialization");
247 InitBuiltinTypes(*t);
248 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000249}
250
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000251ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000252 // Release the DenseMaps associated with DeclContext objects.
253 // FIXME: Is this the ideal solution?
254 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000255
Douglas Gregor5b11d492010-07-25 17:53:33 +0000256 // Call all of the deallocation functions.
257 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
258 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000259
Douglas Gregor832940b2010-03-02 23:58:15 +0000260 // Release all of the memory associated with overridden C++ methods.
261 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
262 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
263 OM != OMEnd; ++OM)
264 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000265
Ted Kremenek076baeb2010-06-08 23:00:58 +0000266 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000267 // because they can contain DenseMaps.
268 for (llvm::DenseMap<const ObjCContainerDecl*,
269 const ASTRecordLayout*>::iterator
270 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
271 // Increment in loop to prevent using deallocated memory.
272 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
273 R->Destroy(*this);
274
Ted Kremenek076baeb2010-06-08 23:00:58 +0000275 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
276 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
277 // Increment in loop to prevent using deallocated memory.
278 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
279 R->Destroy(*this);
280 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000281
282 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
283 AEnd = DeclAttrs.end();
284 A != AEnd; ++A)
285 A->second->~AttrVec();
286}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000287
Douglas Gregor1a809332010-05-23 18:26:36 +0000288void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
289 Deallocations.push_back(std::make_pair(Callback, Data));
290}
291
Mike Stump11289f42009-09-09 15:08:12 +0000292void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000293ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
294 ExternalSource.reset(Source.take());
295}
296
Chris Lattner4eb445d2007-01-26 01:27:23 +0000297void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000298 llvm::errs() << "\n*** AST Context Stats:\n";
299 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000300
Douglas Gregora30d0462009-05-26 14:40:08 +0000301 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000302#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000303#define ABSTRACT_TYPE(Name, Parent)
304#include "clang/AST/TypeNodes.def"
305 0 // Extra
306 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000307
Chris Lattner4eb445d2007-01-26 01:27:23 +0000308 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
309 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000310 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000311 }
312
Douglas Gregora30d0462009-05-26 14:40:08 +0000313 unsigned Idx = 0;
314 unsigned TotalBytes = 0;
315#define TYPE(Name, Parent) \
316 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000317 llvm::errs() << " " << counts[Idx] << " " << #Name \
318 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000319 TotalBytes += counts[Idx] * sizeof(Name##Type); \
320 ++Idx;
321#define ABSTRACT_TYPE(Name, Parent)
322#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000323
Chandler Carruth3c147a72011-07-04 05:32:14 +0000324 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
325
Douglas Gregor7454c562010-07-02 20:37:36 +0000326 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000327 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
328 << NumImplicitDefaultConstructors
329 << " implicit default constructors created\n";
330 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
331 << NumImplicitCopyConstructors
332 << " implicit copy constructors created\n";
Alexis Huntfcaeae42011-05-25 20:50:04 +0000333 if (getLangOptions().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000334 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
335 << NumImplicitMoveConstructors
336 << " implicit move constructors created\n";
337 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
338 << NumImplicitCopyAssignmentOperators
339 << " implicit copy assignment operators created\n";
Alexis Huntfcaeae42011-05-25 20:50:04 +0000340 if (getLangOptions().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000341 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
342 << NumImplicitMoveAssignmentOperators
343 << " implicit move assignment operators created\n";
344 llvm::errs() << NumImplicitDestructorsDeclared << "/"
345 << NumImplicitDestructors
346 << " implicit destructors created\n";
347
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000348 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000349 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000350 ExternalSource->PrintStats();
351 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000352
Douglas Gregor5b11d492010-07-25 17:53:33 +0000353 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000354}
355
Douglas Gregor801c99d2011-08-12 06:49:56 +0000356TypedefDecl *ASTContext::getInt128Decl() const {
357 if (!Int128Decl) {
358 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
359 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
360 getTranslationUnitDecl(),
361 SourceLocation(),
362 SourceLocation(),
363 &Idents.get("__int128_t"),
364 TInfo);
365 }
366
367 return Int128Decl;
368}
369
370TypedefDecl *ASTContext::getUInt128Decl() const {
371 if (!UInt128Decl) {
372 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
373 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
374 getTranslationUnitDecl(),
375 SourceLocation(),
376 SourceLocation(),
377 &Idents.get("__uint128_t"),
378 TInfo);
379 }
380
381 return UInt128Decl;
382}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000383
John McCall48f2d582009-10-23 23:03:21 +0000384void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000385 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000386 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000387 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000388}
389
Douglas Gregore8bbc122011-09-02 00:18:52 +0000390void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
391 assert((!this->Target || this->Target == &Target) &&
392 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000393 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000394
Douglas Gregore8bbc122011-09-02 00:18:52 +0000395 this->Target = &Target;
396
397 ABI.reset(createCXXABI(Target));
398 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
399
Chris Lattner970e54e2006-11-12 00:37:36 +0000400 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000401 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000402
Chris Lattner970e54e2006-11-12 00:37:36 +0000403 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000404 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000405 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000406 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000407 InitBuiltinType(CharTy, BuiltinType::Char_S);
408 else
409 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000410 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000411 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
412 InitBuiltinType(ShortTy, BuiltinType::Short);
413 InitBuiltinType(IntTy, BuiltinType::Int);
414 InitBuiltinType(LongTy, BuiltinType::Long);
415 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000416
Chris Lattner970e54e2006-11-12 00:37:36 +0000417 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000418 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
419 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
420 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
421 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
422 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000423
Chris Lattner970e54e2006-11-12 00:37:36 +0000424 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000425 InitBuiltinType(FloatTy, BuiltinType::Float);
426 InitBuiltinType(DoubleTy, BuiltinType::Double);
427 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000428
Chris Lattnerf122cef2009-04-30 02:43:43 +0000429 // GNU extension, 128-bit integers.
430 InitBuiltinType(Int128Ty, BuiltinType::Int128);
431 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
432
Chris Lattnerad3467e2010-12-25 23:25:43 +0000433 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000434 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000435 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
436 else // -fshort-wchar makes wchar_t be unsigned.
437 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
438 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000439 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000440
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000441 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
442 InitBuiltinType(Char16Ty, BuiltinType::Char16);
443 else // C99
444 Char16Ty = getFromTargetType(Target.getChar16Type());
445
446 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
447 InitBuiltinType(Char32Ty, BuiltinType::Char32);
448 else // C99
449 Char32Ty = getFromTargetType(Target.getChar32Type());
450
Douglas Gregor4619e432008-12-05 23:32:09 +0000451 // Placeholder type for type-dependent expressions whose type is
452 // completely unknown. No code should ever check a type against
453 // DependentTy and users should never see it; however, it is here to
454 // help diagnose failures to properly check for type-dependent
455 // expressions.
456 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000457
John McCall36e7fe32010-10-12 00:20:44 +0000458 // Placeholder type for functions.
459 InitBuiltinType(OverloadTy, BuiltinType::Overload);
460
John McCall0009fcc2011-04-26 20:42:42 +0000461 // Placeholder type for bound members.
462 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
463
John McCall31996342011-04-07 08:22:57 +0000464 // "any" type; useful for debugger-like clients.
465 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
466
Chris Lattner970e54e2006-11-12 00:37:36 +0000467 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000468 FloatComplexTy = getComplexType(FloatTy);
469 DoubleComplexTy = getComplexType(DoubleTy);
470 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000471
Steve Naroff66e9f332007-10-15 14:41:52 +0000472 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000473
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000474 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000475 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
476 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000477 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000478
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000479 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000480
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000481 // void * type
482 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000483
484 // nullptr type (C++0x 2.14.7)
485 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000486}
487
David Blaikie9c902b52011-09-25 23:23:43 +0000488DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000489 return SourceMgr.getDiagnostics();
490}
491
Douglas Gregor561eceb2010-08-30 16:49:28 +0000492AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
493 AttrVec *&Result = DeclAttrs[D];
494 if (!Result) {
495 void *Mem = Allocate(sizeof(AttrVec));
496 Result = new (Mem) AttrVec;
497 }
498
499 return *Result;
500}
501
502/// \brief Erase the attributes corresponding to the given declaration.
503void ASTContext::eraseDeclAttrs(const Decl *D) {
504 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
505 if (Pos != DeclAttrs.end()) {
506 Pos->second->~AttrVec();
507 DeclAttrs.erase(Pos);
508 }
509}
510
Douglas Gregor86d142a2009-10-08 07:24:58 +0000511MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000512ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000513 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000514 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000515 = InstantiatedFromStaticDataMember.find(Var);
516 if (Pos == InstantiatedFromStaticDataMember.end())
517 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000518
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000519 return Pos->second;
520}
521
Mike Stump11289f42009-09-09 15:08:12 +0000522void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000523ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000524 TemplateSpecializationKind TSK,
525 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000526 assert(Inst->isStaticDataMember() && "Not a static data member");
527 assert(Tmpl->isStaticDataMember() && "Not a static data member");
528 assert(!InstantiatedFromStaticDataMember[Inst] &&
529 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000530 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000531 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000532}
533
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000534FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
535 const FunctionDecl *FD){
536 assert(FD && "Specialization is 0");
537 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000538 = ClassScopeSpecializationPattern.find(FD);
539 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000540 return 0;
541
542 return Pos->second;
543}
544
545void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
546 FunctionDecl *Pattern) {
547 assert(FD && "Specialization is 0");
548 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000549 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000550}
551
John McCalle61f2ba2009-11-18 02:36:19 +0000552NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000553ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000554 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000555 = InstantiatedFromUsingDecl.find(UUD);
556 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000557 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000558
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000559 return Pos->second;
560}
561
562void
John McCallb96ec562009-12-04 22:46:56 +0000563ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
564 assert((isa<UsingDecl>(Pattern) ||
565 isa<UnresolvedUsingValueDecl>(Pattern) ||
566 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
567 "pattern decl is not a using decl");
568 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
569 InstantiatedFromUsingDecl[Inst] = Pattern;
570}
571
572UsingShadowDecl *
573ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
574 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
575 = InstantiatedFromUsingShadowDecl.find(Inst);
576 if (Pos == InstantiatedFromUsingShadowDecl.end())
577 return 0;
578
579 return Pos->second;
580}
581
582void
583ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
584 UsingShadowDecl *Pattern) {
585 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
586 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000587}
588
Anders Carlsson5da84842009-09-01 04:26:58 +0000589FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
590 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
591 = InstantiatedFromUnnamedFieldDecl.find(Field);
592 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
593 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000594
Anders Carlsson5da84842009-09-01 04:26:58 +0000595 return Pos->second;
596}
597
598void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
599 FieldDecl *Tmpl) {
600 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
601 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
602 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
603 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000604
Anders Carlsson5da84842009-09-01 04:26:58 +0000605 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
606}
607
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000608bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
609 const FieldDecl *LastFD) const {
610 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000611 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000612}
613
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000614bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
615 const FieldDecl *LastFD) const {
616 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000617 FD->getBitWidthValue(*this) == 0 &&
618 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000619}
620
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000621bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
622 const FieldDecl *LastFD) const {
623 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000624 FD->getBitWidthValue(*this) &&
625 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000626}
627
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000628bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000629 const FieldDecl *LastFD) const {
630 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000631 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000632}
633
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000634bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000635 const FieldDecl *LastFD) const {
636 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000637 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000638}
639
Douglas Gregor832940b2010-03-02 23:58:15 +0000640ASTContext::overridden_cxx_method_iterator
641ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
642 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
643 = OverriddenMethods.find(Method);
644 if (Pos == OverriddenMethods.end())
645 return 0;
646
647 return Pos->second.begin();
648}
649
650ASTContext::overridden_cxx_method_iterator
651ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
652 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
653 = OverriddenMethods.find(Method);
654 if (Pos == OverriddenMethods.end())
655 return 0;
656
657 return Pos->second.end();
658}
659
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000660unsigned
661ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
662 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
663 = OverriddenMethods.find(Method);
664 if (Pos == OverriddenMethods.end())
665 return 0;
666
667 return Pos->second.size();
668}
669
Douglas Gregor832940b2010-03-02 23:58:15 +0000670void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
671 const CXXMethodDecl *Overridden) {
672 OverriddenMethods[Method].push_back(Overridden);
673}
674
Chris Lattner53cfe802007-07-18 17:52:12 +0000675//===----------------------------------------------------------------------===//
676// Type Sizing and Analysis
677//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000678
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000679/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
680/// scalar floating point type.
681const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000682 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000683 assert(BT && "Not a floating point type!");
684 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000685 default: llvm_unreachable("Not a floating point type!");
Douglas Gregore8bbc122011-09-02 00:18:52 +0000686 case BuiltinType::Float: return Target->getFloatFormat();
687 case BuiltinType::Double: return Target->getDoubleFormat();
688 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000689 }
690}
691
Ken Dyck160146e2010-01-27 17:10:57 +0000692/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000693/// specified decl. Note that bitfields do not have a valid alignment, so
694/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000695/// If @p RefAsPointee, references are treated like their underlying type
696/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000697CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000698 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +0000699
John McCall94268702010-10-08 18:24:19 +0000700 bool UseAlignAttrOnly = false;
701 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
702 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000703
John McCall94268702010-10-08 18:24:19 +0000704 // __attribute__((aligned)) can increase or decrease alignment
705 // *except* on a struct or struct member, where it only increases
706 // alignment unless 'packed' is also specified.
707 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +0000708 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +0000709 // ignore that possibility; Sema should diagnose it.
710 if (isa<FieldDecl>(D)) {
711 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
712 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
713 } else {
714 UseAlignAttrOnly = true;
715 }
716 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000717 else if (isa<FieldDecl>(D))
718 UseAlignAttrOnly =
719 D->hasAttr<PackedAttr>() ||
720 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000721
John McCall4e819612011-01-20 07:57:12 +0000722 // If we're using the align attribute only, just ignore everything
723 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000724 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000725 // do nothing
726
John McCall94268702010-10-08 18:24:19 +0000727 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000728 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000729 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000730 if (RefAsPointee)
731 T = RT->getPointeeType();
732 else
733 T = getPointerType(RT->getPointeeType());
734 }
735 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000736 // Adjust alignments of declarations with array type by the
737 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +0000738 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000739 const ArrayType *arrayType;
740 if (MinWidth && (arrayType = getAsArrayType(T))) {
741 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000742 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +0000743 else if (isa<ConstantArrayType>(arrayType) &&
744 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000745 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000746
John McCall33ddac02011-01-19 10:06:00 +0000747 // Walk through any array types while we're at it.
748 T = getBaseElementType(arrayType);
749 }
Chad Rosier99ee7822011-07-26 07:03:04 +0000750 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +0000751 }
John McCall4e819612011-01-20 07:57:12 +0000752
753 // Fields can be subject to extra alignment constraints, like if
754 // the field is packed, the struct is packed, or the struct has a
755 // a max-field-alignment constraint (#pragma pack). So calculate
756 // the actual alignment of the field within the struct, and then
757 // (as we're expected to) constrain that by the alignment of the type.
758 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
759 // So calculate the alignment of the field.
760 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
761
762 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000763 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000764
765 // Use the GCD of that and the offset within the record.
766 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
767 if (offset > 0) {
768 // Alignment is always a power of 2, so the GCD will be a power of 2,
769 // which means we get to do this crazy thing instead of Euclid's.
770 uint64_t lowBitOfOffset = offset & (~offset + 1);
771 if (lowBitOfOffset < fieldAlign)
772 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
773 }
774
775 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000776 }
Chris Lattner68061312009-01-24 21:53:27 +0000777 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000778
Ken Dyckcc56c542011-01-15 18:38:59 +0000779 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000780}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000781
John McCall87fe5d52010-05-20 01:18:31 +0000782std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000783ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000784 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000785 return std::make_pair(toCharUnitsFromBits(Info.first),
786 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000787}
788
789std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000790ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000791 return getTypeInfoInChars(T.getTypePtr());
792}
793
Chris Lattner983a8bb2007-07-13 22:13:22 +0000794/// getTypeSize - Return the size of the specified type, in bits. This method
795/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000796///
797/// FIXME: Pointers into different addr spaces could have different sizes and
798/// alignment requirements: getPointerInfo should take an AddrSpace, this
799/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000800std::pair<uint64_t, unsigned>
Jay Foad39c79802011-01-12 09:06:06 +0000801ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000802 uint64_t Width=0;
803 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000804 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000805#define TYPE(Class, Base)
806#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000807#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000808#define DEPENDENT_TYPE(Class, Base) case Type::Class:
809#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +0000810 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000811 break;
812
Chris Lattner355332d2007-07-13 22:27:08 +0000813 case Type::FunctionNoProto:
814 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000815 // GCC extension: alignof(function) = 32 bits
816 Width = 0;
817 Align = 32;
818 break;
819
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000820 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000821 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000822 Width = 0;
823 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
824 break;
825
Steve Naroff5c131802007-08-30 01:06:46 +0000826 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000827 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000828
Chris Lattner37e05872008-03-05 18:54:05 +0000829 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000830 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000831 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +0000832 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000833 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000834 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000835 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000836 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000837 const VectorType *VT = cast<VectorType>(T);
838 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
839 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000840 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000841 // If the alignment is not a power of 2, round up to the next power of 2.
842 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000843 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000844 Align = llvm::NextPowerOf2(Align);
845 Width = llvm::RoundUpToAlignment(Width, Align);
846 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000847 break;
848 }
Chris Lattner647fb222007-07-18 18:26:58 +0000849
Chris Lattner7570e9c2008-03-08 08:52:55 +0000850 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000851 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000852 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000853 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000854 // GCC extension: alignof(void) = 8 bits.
855 Width = 0;
856 Align = 8;
857 break;
858
Chris Lattner6a4f7452007-12-19 19:23:28 +0000859 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000860 Width = Target->getBoolWidth();
861 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000862 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000863 case BuiltinType::Char_S:
864 case BuiltinType::Char_U:
865 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000866 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000867 Width = Target->getCharWidth();
868 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000869 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000870 case BuiltinType::WChar_S:
871 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000872 Width = Target->getWCharWidth();
873 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000874 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000875 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000876 Width = Target->getChar16Width();
877 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000878 break;
879 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000880 Width = Target->getChar32Width();
881 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000882 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000883 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000884 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000885 Width = Target->getShortWidth();
886 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000887 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000888 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000889 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000890 Width = Target->getIntWidth();
891 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000892 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000893 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000894 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000895 Width = Target->getLongWidth();
896 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000897 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000898 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000899 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000900 Width = Target->getLongLongWidth();
901 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000902 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000903 case BuiltinType::Int128:
904 case BuiltinType::UInt128:
905 Width = 128;
906 Align = 128; // int128_t is 128-bit aligned on all targets.
907 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000908 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000909 Width = Target->getFloatWidth();
910 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000911 break;
912 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000913 Width = Target->getDoubleWidth();
914 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000915 break;
916 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000917 Width = Target->getLongDoubleWidth();
918 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000919 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000920 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000921 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
922 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000923 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000924 case BuiltinType::ObjCId:
925 case BuiltinType::ObjCClass:
926 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000927 Width = Target->getPointerWidth(0);
928 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000929 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000930 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000931 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000932 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000933 Width = Target->getPointerWidth(0);
934 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000935 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000936 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000937 unsigned AS = getTargetAddressSpace(
938 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000939 Width = Target->getPointerWidth(AS);
940 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +0000941 break;
942 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000943 case Type::LValueReference:
944 case Type::RValueReference: {
945 // alignof and sizeof should never enter this code path here, so we go
946 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000947 unsigned AS = getTargetAddressSpace(
948 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000949 Width = Target->getPointerWidth(AS);
950 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000951 break;
952 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000953 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000954 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000955 Width = Target->getPointerWidth(AS);
956 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000957 break;
958 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000959 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000960 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000961 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000962 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000963 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000964 Align = PtrDiffInfo.second;
965 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000966 }
Chris Lattner647fb222007-07-18 18:26:58 +0000967 case Type::Complex: {
968 // Complex types have the same alignment as their elements, but twice the
969 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000970 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000971 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000972 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000973 Align = EltInfo.second;
974 break;
975 }
John McCall8b07ec22010-05-15 11:32:37 +0000976 case Type::ObjCObject:
977 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000978 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000979 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000980 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000981 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000982 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +0000983 break;
984 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000985 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000986 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000987 const TagType *TT = cast<TagType>(T);
988
989 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +0000990 Width = 8;
991 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +0000992 break;
993 }
Mike Stump11289f42009-09-09 15:08:12 +0000994
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000995 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000996 return getTypeInfo(ET->getDecl()->getIntegerType());
997
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000998 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000999 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001000 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001001 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001002 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001003 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001004
Chris Lattner63d2b362009-10-22 05:17:15 +00001005 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001006 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1007 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001008
Richard Smith30482bc2011-02-20 03:19:35 +00001009 case Type::Auto: {
1010 const AutoType *A = cast<AutoType>(T);
1011 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001012 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001013 }
1014
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001015 case Type::Paren:
1016 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1017
Douglas Gregoref462e62009-04-30 17:32:17 +00001018 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001019 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001020 std::pair<uint64_t, unsigned> Info
1021 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001022 // If the typedef has an aligned attribute on it, it overrides any computed
1023 // alignment we have. This violates the GCC documentation (which says that
1024 // attribute(aligned) can only round up) but matches its implementation.
1025 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1026 Align = AttrAlign;
1027 else
1028 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001029 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001030 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001031 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001032
1033 case Type::TypeOfExpr:
1034 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1035 .getTypePtr());
1036
1037 case Type::TypeOf:
1038 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1039
Anders Carlsson81df7b82009-06-24 19:06:50 +00001040 case Type::Decltype:
1041 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1042 .getTypePtr());
1043
Alexis Hunte852b102011-05-24 22:41:36 +00001044 case Type::UnaryTransform:
1045 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1046
Abramo Bagnara6150c882010-05-11 21:36:43 +00001047 case Type::Elaborated:
1048 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001049
John McCall81904512011-01-06 01:58:22 +00001050 case Type::Attributed:
1051 return getTypeInfo(
1052 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1053
Richard Smith3f1b5d02011-05-05 21:57:07 +00001054 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001055 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001056 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001057 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1058 // A type alias template specialization may refer to a typedef with the
1059 // aligned attribute on it.
1060 if (TST->isTypeAlias())
1061 return getTypeInfo(TST->getAliasedType().getTypePtr());
1062 else
1063 return getTypeInfo(getCanonicalType(T));
1064 }
1065
Eli Friedman0dfb8892011-10-06 23:00:33 +00001066 case Type::Atomic: {
1067 // FIXME: The alignment needs to be "fixed".
1068 return getTypeInfo(cast<AtomicType>(T)->getValueType());
1069 }
1070
Douglas Gregoref462e62009-04-30 17:32:17 +00001071 }
Mike Stump11289f42009-09-09 15:08:12 +00001072
Chris Lattner53cfe802007-07-18 17:52:12 +00001073 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001074 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001075}
1076
Ken Dyckcc56c542011-01-15 18:38:59 +00001077/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1078CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1079 return CharUnits::fromQuantity(BitSize / getCharWidth());
1080}
1081
Ken Dyckb0fcc592011-02-11 01:54:29 +00001082/// toBits - Convert a size in characters to a size in characters.
1083int64_t ASTContext::toBits(CharUnits CharSize) const {
1084 return CharSize.getQuantity() * getCharWidth();
1085}
1086
Ken Dyck8c89d592009-12-22 14:23:30 +00001087/// getTypeSizeInChars - Return the size of the specified type, in characters.
1088/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001089CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001090 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001091}
Jay Foad39c79802011-01-12 09:06:06 +00001092CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001093 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001094}
1095
Ken Dycka6046ab2010-01-26 17:25:18 +00001096/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001097/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001098CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001099 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001100}
Jay Foad39c79802011-01-12 09:06:06 +00001101CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001102 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001103}
1104
Chris Lattnera3402cd2009-01-27 18:08:34 +00001105/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1106/// type for the current target in bits. This can be different than the ABI
1107/// alignment in cases where it is beneficial for performance to overalign
1108/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001109unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001110 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001111
1112 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001113 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001114 T = CT->getElementType().getTypePtr();
1115 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1116 T->isSpecificBuiltinType(BuiltinType::LongLong))
1117 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1118
Chris Lattnera3402cd2009-01-27 18:08:34 +00001119 return ABIAlign;
1120}
1121
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001122/// DeepCollectObjCIvars -
1123/// This routine first collects all declared, but not synthesized, ivars in
1124/// super class and then collects all ivars, including those synthesized for
1125/// current class. This routine is used for implementation of current class
1126/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001127///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001128void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1129 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001130 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001131 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1132 DeepCollectObjCIvars(SuperClass, false, Ivars);
1133 if (!leafClass) {
1134 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1135 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +00001136 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001137 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001138 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001139 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001140 Iv= Iv->getNextIvar())
1141 Ivars.push_back(Iv);
1142 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001143}
1144
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001145/// CollectInheritedProtocols - Collect all protocols in current class and
1146/// those inherited by it.
1147void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001148 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001149 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001150 // We can use protocol_iterator here instead of
1151 // all_referenced_protocol_iterator since we are walking all categories.
1152 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1153 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001154 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001155 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001156 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001157 PE = Proto->protocol_end(); P != PE; ++P) {
1158 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001159 CollectInheritedProtocols(*P, Protocols);
1160 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001161 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001162
1163 // Categories of this Interface.
1164 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1165 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1166 CollectInheritedProtocols(CDeclChain, Protocols);
1167 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1168 while (SD) {
1169 CollectInheritedProtocols(SD, Protocols);
1170 SD = SD->getSuperClass();
1171 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001172 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001173 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001174 PE = OC->protocol_end(); P != PE; ++P) {
1175 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001176 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001177 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1178 PE = Proto->protocol_end(); P != PE; ++P)
1179 CollectInheritedProtocols(*P, Protocols);
1180 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001181 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001182 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1183 PE = OP->protocol_end(); P != PE; ++P) {
1184 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001185 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001186 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1187 PE = Proto->protocol_end(); P != PE; ++P)
1188 CollectInheritedProtocols(*P, Protocols);
1189 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001190 }
1191}
1192
Jay Foad39c79802011-01-12 09:06:06 +00001193unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001194 unsigned count = 0;
1195 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001196 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1197 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001198 count += CDecl->ivar_size();
1199
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001200 // Count ivar defined in this class's implementation. This
1201 // includes synthesized ivars.
1202 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001203 count += ImplDecl->ivar_size();
1204
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001205 return count;
1206}
1207
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001208/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1209ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1210 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1211 I = ObjCImpls.find(D);
1212 if (I != ObjCImpls.end())
1213 return cast<ObjCImplementationDecl>(I->second);
1214 return 0;
1215}
1216/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1217ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1218 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1219 I = ObjCImpls.find(D);
1220 if (I != ObjCImpls.end())
1221 return cast<ObjCCategoryImplDecl>(I->second);
1222 return 0;
1223}
1224
1225/// \brief Set the implementation of ObjCInterfaceDecl.
1226void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1227 ObjCImplementationDecl *ImplD) {
1228 assert(IFaceD && ImplD && "Passed null params");
1229 ObjCImpls[IFaceD] = ImplD;
1230}
1231/// \brief Set the implementation of ObjCCategoryDecl.
1232void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1233 ObjCCategoryImplDecl *ImplD) {
1234 assert(CatD && ImplD && "Passed null params");
1235 ObjCImpls[CatD] = ImplD;
1236}
1237
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001238/// \brief Get the copy initialization expression of VarDecl,or NULL if
1239/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001240Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001241 assert(VD && "Passed null params");
1242 assert(VD->hasAttr<BlocksAttr>() &&
1243 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001244 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001245 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001246 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1247}
1248
1249/// \brief Set the copy inialization expression of a block var decl.
1250void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1251 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001252 assert(VD->hasAttr<BlocksAttr>() &&
1253 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001254 BlockVarCopyInits[VD] = Init;
1255}
1256
John McCallbcd03502009-12-07 02:54:59 +00001257/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001258///
John McCallbcd03502009-12-07 02:54:59 +00001259/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001260/// the TypeLoc wrappers.
1261///
1262/// \param T the type that will be the basis for type source info. This type
1263/// should refer to how the declarator was written in source code, not to
1264/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001265TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001266 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001267 if (!DataSize)
1268 DataSize = TypeLoc::getFullDataSizeForType(T);
1269 else
1270 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001271 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001272
John McCallbcd03502009-12-07 02:54:59 +00001273 TypeSourceInfo *TInfo =
1274 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1275 new (TInfo) TypeSourceInfo(T);
1276 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001277}
1278
John McCallbcd03502009-12-07 02:54:59 +00001279TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001280 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001281 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001282 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001283 return DI;
1284}
1285
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001286const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001287ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001288 return getObjCLayout(D, 0);
1289}
1290
1291const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001292ASTContext::getASTObjCImplementationLayout(
1293 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001294 return getObjCLayout(D->getClassInterface(), D);
1295}
1296
Chris Lattner983a8bb2007-07-13 22:13:22 +00001297//===----------------------------------------------------------------------===//
1298// Type creation/memoization methods
1299//===----------------------------------------------------------------------===//
1300
Jay Foad39c79802011-01-12 09:06:06 +00001301QualType
John McCall33ddac02011-01-19 10:06:00 +00001302ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1303 unsigned fastQuals = quals.getFastQualifiers();
1304 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001305
1306 // Check if we've already instantiated this type.
1307 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001308 ExtQuals::Profile(ID, baseType, quals);
1309 void *insertPos = 0;
1310 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1311 assert(eq->getQualifiers() == quals);
1312 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001313 }
1314
John McCall33ddac02011-01-19 10:06:00 +00001315 // If the base type is not canonical, make the appropriate canonical type.
1316 QualType canon;
1317 if (!baseType->isCanonicalUnqualified()) {
1318 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1319 canonSplit.second.addConsistentQualifiers(quals);
1320 canon = getExtQualType(canonSplit.first, canonSplit.second);
1321
1322 // Re-find the insert position.
1323 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1324 }
1325
1326 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1327 ExtQualNodes.InsertNode(eq, insertPos);
1328 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001329}
1330
Jay Foad39c79802011-01-12 09:06:06 +00001331QualType
1332ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001333 QualType CanT = getCanonicalType(T);
1334 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001335 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001336
John McCall8ccfcb52009-09-24 19:53:00 +00001337 // If we are composing extended qualifiers together, merge together
1338 // into one ExtQuals node.
1339 QualifierCollector Quals;
1340 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001341
John McCall8ccfcb52009-09-24 19:53:00 +00001342 // If this type already has an address space specified, it cannot get
1343 // another one.
1344 assert(!Quals.hasAddressSpace() &&
1345 "Type cannot be in multiple addr spaces!");
1346 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001347
John McCall8ccfcb52009-09-24 19:53:00 +00001348 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001349}
1350
Chris Lattnerd60183d2009-02-18 22:53:11 +00001351QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001352 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001353 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001354 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001355 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001356
John McCall53fa7142010-12-24 02:08:15 +00001357 if (const PointerType *ptr = T->getAs<PointerType>()) {
1358 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001359 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001360 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1361 return getPointerType(ResultType);
1362 }
1363 }
Mike Stump11289f42009-09-09 15:08:12 +00001364
John McCall8ccfcb52009-09-24 19:53:00 +00001365 // If we are composing extended qualifiers together, merge together
1366 // into one ExtQuals node.
1367 QualifierCollector Quals;
1368 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001369
John McCall8ccfcb52009-09-24 19:53:00 +00001370 // If this type already has an ObjCGC specified, it cannot get
1371 // another one.
1372 assert(!Quals.hasObjCGCAttr() &&
1373 "Type cannot have multiple ObjCGCs!");
1374 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001375
John McCall8ccfcb52009-09-24 19:53:00 +00001376 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001377}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001378
John McCall4f5019e2010-12-19 02:44:49 +00001379const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1380 FunctionType::ExtInfo Info) {
1381 if (T->getExtInfo() == Info)
1382 return T;
1383
1384 QualType Result;
1385 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1386 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1387 } else {
1388 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1389 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1390 EPI.ExtInfo = Info;
1391 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1392 FPT->getNumArgs(), EPI);
1393 }
1394
1395 return cast<FunctionType>(Result.getTypePtr());
1396}
1397
Chris Lattnerc6395932007-06-22 20:56:16 +00001398/// getComplexType - Return the uniqued reference to the type for a complex
1399/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001400QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001401 // Unique pointers, to guarantee there is only one pointer of a particular
1402 // structure.
1403 llvm::FoldingSetNodeID ID;
1404 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001405
Chris Lattnerc6395932007-06-22 20:56:16 +00001406 void *InsertPos = 0;
1407 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1408 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001409
Chris Lattnerc6395932007-06-22 20:56:16 +00001410 // If the pointee type isn't canonical, this won't be a canonical type either,
1411 // so fill in the canonical type field.
1412 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001413 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001414 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001415
Chris Lattnerc6395932007-06-22 20:56:16 +00001416 // Get the new insert position for the node we care about.
1417 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001418 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001419 }
John McCall90d1c2d2009-09-24 23:30:46 +00001420 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001421 Types.push_back(New);
1422 ComplexTypes.InsertNode(New, InsertPos);
1423 return QualType(New, 0);
1424}
1425
Chris Lattner970e54e2006-11-12 00:37:36 +00001426/// getPointerType - Return the uniqued reference to the type for a pointer to
1427/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001428QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001429 // Unique pointers, to guarantee there is only one pointer of a particular
1430 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001431 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001432 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001433
Chris Lattner67521df2007-01-27 01:29:36 +00001434 void *InsertPos = 0;
1435 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001436 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001437
Chris Lattner7ccecb92006-11-12 08:50:50 +00001438 // If the pointee type isn't canonical, this won't be a canonical type either,
1439 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001440 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001441 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001442 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001443
Chris Lattner67521df2007-01-27 01:29:36 +00001444 // Get the new insert position for the node we care about.
1445 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001446 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001447 }
John McCall90d1c2d2009-09-24 23:30:46 +00001448 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001449 Types.push_back(New);
1450 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001451 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001452}
1453
Mike Stump11289f42009-09-09 15:08:12 +00001454/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001455/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001456QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001457 assert(T->isFunctionType() && "block of function types only");
1458 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001459 // structure.
1460 llvm::FoldingSetNodeID ID;
1461 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001462
Steve Naroffec33ed92008-08-27 16:04:49 +00001463 void *InsertPos = 0;
1464 if (BlockPointerType *PT =
1465 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1466 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001467
1468 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001469 // type either so fill in the canonical type field.
1470 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001471 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001472 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001473
Steve Naroffec33ed92008-08-27 16:04:49 +00001474 // Get the new insert position for the node we care about.
1475 BlockPointerType *NewIP =
1476 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001477 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001478 }
John McCall90d1c2d2009-09-24 23:30:46 +00001479 BlockPointerType *New
1480 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001481 Types.push_back(New);
1482 BlockPointerTypes.InsertNode(New, InsertPos);
1483 return QualType(New, 0);
1484}
1485
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001486/// getLValueReferenceType - Return the uniqued reference to the type for an
1487/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001488QualType
1489ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001490 assert(getCanonicalType(T) != OverloadTy &&
1491 "Unresolved overloaded function type");
1492
Bill Wendling3708c182007-05-27 10:15:43 +00001493 // Unique pointers, to guarantee there is only one pointer of a particular
1494 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001495 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001496 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001497
1498 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001499 if (LValueReferenceType *RT =
1500 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001501 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001502
John McCallfc93cf92009-10-22 22:37:11 +00001503 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1504
Bill Wendling3708c182007-05-27 10:15:43 +00001505 // If the referencee type isn't canonical, this won't be a canonical type
1506 // either, so fill in the canonical type field.
1507 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001508 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1509 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1510 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001511
Bill Wendling3708c182007-05-27 10:15:43 +00001512 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001513 LValueReferenceType *NewIP =
1514 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001515 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001516 }
1517
John McCall90d1c2d2009-09-24 23:30:46 +00001518 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001519 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1520 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001521 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001522 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001523
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001524 return QualType(New, 0);
1525}
1526
1527/// getRValueReferenceType - Return the uniqued reference to the type for an
1528/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001529QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001530 // Unique pointers, to guarantee there is only one pointer of a particular
1531 // structure.
1532 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001533 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001534
1535 void *InsertPos = 0;
1536 if (RValueReferenceType *RT =
1537 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1538 return QualType(RT, 0);
1539
John McCallfc93cf92009-10-22 22:37:11 +00001540 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1541
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001542 // If the referencee type isn't canonical, this won't be a canonical type
1543 // either, so fill in the canonical type field.
1544 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001545 if (InnerRef || !T.isCanonical()) {
1546 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1547 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001548
1549 // Get the new insert position for the node we care about.
1550 RValueReferenceType *NewIP =
1551 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001552 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001553 }
1554
John McCall90d1c2d2009-09-24 23:30:46 +00001555 RValueReferenceType *New
1556 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001557 Types.push_back(New);
1558 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001559 return QualType(New, 0);
1560}
1561
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001562/// getMemberPointerType - Return the uniqued reference to the type for a
1563/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001564QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001565 // Unique pointers, to guarantee there is only one pointer of a particular
1566 // structure.
1567 llvm::FoldingSetNodeID ID;
1568 MemberPointerType::Profile(ID, T, Cls);
1569
1570 void *InsertPos = 0;
1571 if (MemberPointerType *PT =
1572 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1573 return QualType(PT, 0);
1574
1575 // If the pointee or class type isn't canonical, this won't be a canonical
1576 // type either, so fill in the canonical type field.
1577 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001578 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001579 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1580
1581 // Get the new insert position for the node we care about.
1582 MemberPointerType *NewIP =
1583 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001584 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001585 }
John McCall90d1c2d2009-09-24 23:30:46 +00001586 MemberPointerType *New
1587 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001588 Types.push_back(New);
1589 MemberPointerTypes.InsertNode(New, InsertPos);
1590 return QualType(New, 0);
1591}
1592
Mike Stump11289f42009-09-09 15:08:12 +00001593/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001594/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001595QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001596 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001597 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001598 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001599 assert((EltTy->isDependentType() ||
1600 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001601 "Constant array of VLAs is illegal!");
1602
Chris Lattnere2df3f92009-05-13 04:12:56 +00001603 // Convert the array size into a canonical width matching the pointer size for
1604 // the target.
1605 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001606 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001607 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001608
Chris Lattner23b7eb62007-06-15 23:05:46 +00001609 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001610 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001611
Chris Lattner36f8e652007-01-27 08:31:04 +00001612 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001613 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001614 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001615 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001616
John McCall33ddac02011-01-19 10:06:00 +00001617 // If the element type isn't canonical or has qualifiers, this won't
1618 // be a canonical type either, so fill in the canonical type field.
1619 QualType Canon;
1620 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1621 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1622 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001623 ASM, IndexTypeQuals);
John McCall33ddac02011-01-19 10:06:00 +00001624 Canon = getQualifiedType(Canon, canonSplit.second);
1625
Chris Lattner36f8e652007-01-27 08:31:04 +00001626 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001627 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001628 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001629 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001630 }
Mike Stump11289f42009-09-09 15:08:12 +00001631
John McCall90d1c2d2009-09-24 23:30:46 +00001632 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001633 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001634 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001635 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001636 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001637}
1638
John McCall06549462011-01-18 08:40:38 +00001639/// getVariableArrayDecayedType - Turns the given type, which may be
1640/// variably-modified, into the corresponding type with all the known
1641/// sizes replaced with [*].
1642QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1643 // Vastly most common case.
1644 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001645
John McCall06549462011-01-18 08:40:38 +00001646 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001647
John McCall06549462011-01-18 08:40:38 +00001648 SplitQualType split = type.getSplitDesugaredType();
1649 const Type *ty = split.first;
1650 switch (ty->getTypeClass()) {
1651#define TYPE(Class, Base)
1652#define ABSTRACT_TYPE(Class, Base)
1653#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1654#include "clang/AST/TypeNodes.def"
1655 llvm_unreachable("didn't desugar past all non-canonical types?");
1656
1657 // These types should never be variably-modified.
1658 case Type::Builtin:
1659 case Type::Complex:
1660 case Type::Vector:
1661 case Type::ExtVector:
1662 case Type::DependentSizedExtVector:
1663 case Type::ObjCObject:
1664 case Type::ObjCInterface:
1665 case Type::ObjCObjectPointer:
1666 case Type::Record:
1667 case Type::Enum:
1668 case Type::UnresolvedUsing:
1669 case Type::TypeOfExpr:
1670 case Type::TypeOf:
1671 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001672 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001673 case Type::DependentName:
1674 case Type::InjectedClassName:
1675 case Type::TemplateSpecialization:
1676 case Type::DependentTemplateSpecialization:
1677 case Type::TemplateTypeParm:
1678 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001679 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001680 case Type::PackExpansion:
1681 llvm_unreachable("type should never be variably-modified");
1682
1683 // These types can be variably-modified but should never need to
1684 // further decay.
1685 case Type::FunctionNoProto:
1686 case Type::FunctionProto:
1687 case Type::BlockPointer:
1688 case Type::MemberPointer:
1689 return type;
1690
1691 // These types can be variably-modified. All these modifications
1692 // preserve structure except as noted by comments.
1693 // TODO: if we ever care about optimizing VLAs, there are no-op
1694 // optimizations available here.
1695 case Type::Pointer:
1696 result = getPointerType(getVariableArrayDecayedType(
1697 cast<PointerType>(ty)->getPointeeType()));
1698 break;
1699
1700 case Type::LValueReference: {
1701 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1702 result = getLValueReferenceType(
1703 getVariableArrayDecayedType(lv->getPointeeType()),
1704 lv->isSpelledAsLValue());
1705 break;
1706 }
1707
1708 case Type::RValueReference: {
1709 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1710 result = getRValueReferenceType(
1711 getVariableArrayDecayedType(lv->getPointeeType()));
1712 break;
1713 }
1714
Eli Friedman0dfb8892011-10-06 23:00:33 +00001715 case Type::Atomic: {
1716 const AtomicType *at = cast<AtomicType>(ty);
1717 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1718 break;
1719 }
1720
John McCall06549462011-01-18 08:40:38 +00001721 case Type::ConstantArray: {
1722 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1723 result = getConstantArrayType(
1724 getVariableArrayDecayedType(cat->getElementType()),
1725 cat->getSize(),
1726 cat->getSizeModifier(),
1727 cat->getIndexTypeCVRQualifiers());
1728 break;
1729 }
1730
1731 case Type::DependentSizedArray: {
1732 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1733 result = getDependentSizedArrayType(
1734 getVariableArrayDecayedType(dat->getElementType()),
1735 dat->getSizeExpr(),
1736 dat->getSizeModifier(),
1737 dat->getIndexTypeCVRQualifiers(),
1738 dat->getBracketsRange());
1739 break;
1740 }
1741
1742 // Turn incomplete types into [*] types.
1743 case Type::IncompleteArray: {
1744 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1745 result = getVariableArrayType(
1746 getVariableArrayDecayedType(iat->getElementType()),
1747 /*size*/ 0,
1748 ArrayType::Normal,
1749 iat->getIndexTypeCVRQualifiers(),
1750 SourceRange());
1751 break;
1752 }
1753
1754 // Turn VLA types into [*] types.
1755 case Type::VariableArray: {
1756 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1757 result = getVariableArrayType(
1758 getVariableArrayDecayedType(vat->getElementType()),
1759 /*size*/ 0,
1760 ArrayType::Star,
1761 vat->getIndexTypeCVRQualifiers(),
1762 vat->getBracketsRange());
1763 break;
1764 }
1765 }
1766
1767 // Apply the top-level qualifiers from the original.
1768 return getQualifiedType(result, split.second);
1769}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001770
Steve Naroffcadebd02007-08-30 18:14:25 +00001771/// getVariableArrayType - Returns a non-unique reference to the type for a
1772/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001773QualType ASTContext::getVariableArrayType(QualType EltTy,
1774 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001775 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001776 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001777 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001778 // Since we don't unique expressions, it isn't possible to unique VLA's
1779 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001780 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001781
John McCall33ddac02011-01-19 10:06:00 +00001782 // Be sure to pull qualifiers off the element type.
1783 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1784 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1785 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001786 IndexTypeQuals, Brackets);
John McCall33ddac02011-01-19 10:06:00 +00001787 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001788 }
1789
John McCall90d1c2d2009-09-24 23:30:46 +00001790 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001791 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001792
1793 VariableArrayTypes.push_back(New);
1794 Types.push_back(New);
1795 return QualType(New, 0);
1796}
1797
Douglas Gregor4619e432008-12-05 23:32:09 +00001798/// getDependentSizedArrayType - Returns a non-unique reference to
1799/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001800/// type.
John McCall33ddac02011-01-19 10:06:00 +00001801QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1802 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001803 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001804 unsigned elementTypeQuals,
1805 SourceRange brackets) const {
1806 assert((!numElements || numElements->isTypeDependent() ||
1807 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001808 "Size must be type- or value-dependent!");
1809
John McCall33ddac02011-01-19 10:06:00 +00001810 // Dependently-sized array types that do not have a specified number
1811 // of elements will have their sizes deduced from a dependent
1812 // initializer. We do no canonicalization here at all, which is okay
1813 // because they can't be used in most locations.
1814 if (!numElements) {
1815 DependentSizedArrayType *newType
1816 = new (*this, TypeAlignment)
1817 DependentSizedArrayType(*this, elementType, QualType(),
1818 numElements, ASM, elementTypeQuals,
1819 brackets);
1820 Types.push_back(newType);
1821 return QualType(newType, 0);
1822 }
1823
1824 // Otherwise, we actually build a new type every time, but we
1825 // also build a canonical type.
1826
1827 SplitQualType canonElementType = getCanonicalType(elementType).split();
1828
1829 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001830 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001831 DependentSizedArrayType::Profile(ID, *this,
1832 QualType(canonElementType.first, 0),
1833 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001834
John McCall33ddac02011-01-19 10:06:00 +00001835 // Look for an existing type with these properties.
1836 DependentSizedArrayType *canonTy =
1837 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001838
John McCall33ddac02011-01-19 10:06:00 +00001839 // If we don't have one, build one.
1840 if (!canonTy) {
1841 canonTy = new (*this, TypeAlignment)
1842 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1843 QualType(), numElements, ASM, elementTypeQuals,
1844 brackets);
1845 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1846 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001847 }
1848
John McCall33ddac02011-01-19 10:06:00 +00001849 // Apply qualifiers from the element type to the array.
1850 QualType canon = getQualifiedType(QualType(canonTy,0),
1851 canonElementType.second);
Mike Stump11289f42009-09-09 15:08:12 +00001852
John McCall33ddac02011-01-19 10:06:00 +00001853 // If we didn't need extra canonicalization for the element type,
1854 // then just use that as our result.
1855 if (QualType(canonElementType.first, 0) == elementType)
1856 return canon;
1857
1858 // Otherwise, we need to build a type which follows the spelling
1859 // of the element type.
1860 DependentSizedArrayType *sugaredType
1861 = new (*this, TypeAlignment)
1862 DependentSizedArrayType(*this, elementType, canon, numElements,
1863 ASM, elementTypeQuals, brackets);
1864 Types.push_back(sugaredType);
1865 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00001866}
1867
John McCall33ddac02011-01-19 10:06:00 +00001868QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00001869 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001870 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001871 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001872 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001873
John McCall33ddac02011-01-19 10:06:00 +00001874 void *insertPos = 0;
1875 if (IncompleteArrayType *iat =
1876 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1877 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00001878
1879 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00001880 // either, so fill in the canonical type field. We also have to pull
1881 // qualifiers off the element type.
1882 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00001883
John McCall33ddac02011-01-19 10:06:00 +00001884 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1885 SplitQualType canonSplit = getCanonicalType(elementType).split();
1886 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1887 ASM, elementTypeQuals);
1888 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanbd258282008-02-15 18:16:39 +00001889
1890 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00001891 IncompleteArrayType *existing =
1892 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1893 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001894 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001895
John McCall33ddac02011-01-19 10:06:00 +00001896 IncompleteArrayType *newType = new (*this, TypeAlignment)
1897 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001898
John McCall33ddac02011-01-19 10:06:00 +00001899 IncompleteArrayTypes.InsertNode(newType, insertPos);
1900 Types.push_back(newType);
1901 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001902}
1903
Steve Naroff91fcddb2007-07-18 18:00:27 +00001904/// getVectorType - Return the unique reference to a vector type of
1905/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001906QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001907 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00001908 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001909
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001910 // Check if we've already instantiated a vector of this type.
1911 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001912 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001913
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001914 void *InsertPos = 0;
1915 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1916 return QualType(VTP, 0);
1917
1918 // If the element type isn't canonical, this won't be a canonical type either,
1919 // so fill in the canonical type field.
1920 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001921 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001922 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001923
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001924 // Get the new insert position for the node we care about.
1925 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001926 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001927 }
John McCall90d1c2d2009-09-24 23:30:46 +00001928 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001929 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001930 VectorTypes.InsertNode(New, InsertPos);
1931 Types.push_back(New);
1932 return QualType(New, 0);
1933}
1934
Nate Begemance4d7fc2008-04-18 23:10:10 +00001935/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001936/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00001937QualType
1938ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00001939 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00001940
Steve Naroff91fcddb2007-07-18 18:00:27 +00001941 // Check if we've already instantiated a vector of this type.
1942 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001943 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001944 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001945 void *InsertPos = 0;
1946 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1947 return QualType(VTP, 0);
1948
1949 // If the element type isn't canonical, this won't be a canonical type either,
1950 // so fill in the canonical type field.
1951 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001952 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001953 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001954
Steve Naroff91fcddb2007-07-18 18:00:27 +00001955 // Get the new insert position for the node we care about.
1956 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001957 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001958 }
John McCall90d1c2d2009-09-24 23:30:46 +00001959 ExtVectorType *New = new (*this, TypeAlignment)
1960 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001961 VectorTypes.InsertNode(New, InsertPos);
1962 Types.push_back(New);
1963 return QualType(New, 0);
1964}
1965
Jay Foad39c79802011-01-12 09:06:06 +00001966QualType
1967ASTContext::getDependentSizedExtVectorType(QualType vecType,
1968 Expr *SizeExpr,
1969 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00001970 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001971 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001972 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001973
Douglas Gregor352169a2009-07-31 03:54:25 +00001974 void *InsertPos = 0;
1975 DependentSizedExtVectorType *Canon
1976 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1977 DependentSizedExtVectorType *New;
1978 if (Canon) {
1979 // We already have a canonical version of this array type; use it as
1980 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001981 New = new (*this, TypeAlignment)
1982 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1983 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001984 } else {
1985 QualType CanonVecTy = getCanonicalType(vecType);
1986 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001987 New = new (*this, TypeAlignment)
1988 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1989 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001990
1991 DependentSizedExtVectorType *CanonCheck
1992 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1993 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1994 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001995 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1996 } else {
1997 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1998 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001999 New = new (*this, TypeAlignment)
2000 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002001 }
2002 }
Mike Stump11289f42009-09-09 15:08:12 +00002003
Douglas Gregor758a8692009-06-17 21:51:59 +00002004 Types.push_back(New);
2005 return QualType(New, 0);
2006}
2007
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002008/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002009///
Jay Foad39c79802011-01-12 09:06:06 +00002010QualType
2011ASTContext::getFunctionNoProtoType(QualType ResultTy,
2012 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002013 const CallingConv DefaultCC = Info.getCC();
2014 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2015 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002016 // Unique functions, to guarantee there is only one function of a particular
2017 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002018 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002019 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002020
Chris Lattner47955de2007-01-27 08:37:20 +00002021 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002022 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002023 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002024 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002025
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002026 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002027 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002028 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002029 Canonical =
2030 getFunctionNoProtoType(getCanonicalType(ResultTy),
2031 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002032
Chris Lattner47955de2007-01-27 08:37:20 +00002033 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002034 FunctionNoProtoType *NewIP =
2035 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002036 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002037 }
Mike Stump11289f42009-09-09 15:08:12 +00002038
Roman Divacky65b88cd2011-03-01 17:40:53 +00002039 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002040 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002041 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002042 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002043 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002044 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002045}
2046
2047/// getFunctionType - Return a normal function type with a typed argument
2048/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002049QualType
2050ASTContext::getFunctionType(QualType ResultTy,
2051 const QualType *ArgArray, unsigned NumArgs,
2052 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002053 // Unique functions, to guarantee there is only one function of a particular
2054 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002055 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002056 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002057
2058 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002059 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002060 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002061 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002062
2063 // Determine whether the type being created is already canonical or not.
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002064 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002065 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002066 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002067 isCanonical = false;
2068
Roman Divacky65b88cd2011-03-01 17:40:53 +00002069 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2070 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2071 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002072
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002073 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002074 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002075 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002076 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002077 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002078 CanonicalArgs.reserve(NumArgs);
2079 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002080 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002081
John McCalldb40c7f2010-12-14 08:05:40 +00002082 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002083 CanonicalEPI.ExceptionSpecType = EST_None;
2084 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002085 CanonicalEPI.ExtInfo
2086 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2087
Chris Lattner76a00cf2008-04-06 22:59:24 +00002088 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002089 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002090 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002091
Chris Lattnerfd4de792007-01-27 01:15:32 +00002092 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002093 FunctionProtoType *NewIP =
2094 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002095 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002096 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002097
John McCall31168b02011-06-15 23:02:42 +00002098 // FunctionProtoType objects are allocated with extra bytes after
2099 // them for three variable size arrays at the end:
2100 // - parameter types
2101 // - exception types
2102 // - consumed-arguments flags
2103 // Instead of the exception types, there could be a noexcept
2104 // expression.
John McCalldb40c7f2010-12-14 08:05:40 +00002105 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002106 NumArgs * sizeof(QualType);
2107 if (EPI.ExceptionSpecType == EST_Dynamic)
2108 Size += EPI.NumExceptions * sizeof(QualType);
2109 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002110 Size += sizeof(Expr*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002111 }
John McCall31168b02011-06-15 23:02:42 +00002112 if (EPI.ConsumedArguments)
2113 Size += NumArgs * sizeof(bool);
2114
John McCalldb40c7f2010-12-14 08:05:40 +00002115 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002116 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2117 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002118 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002119 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002120 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002121 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002122}
Chris Lattneref51c202006-11-10 07:17:23 +00002123
John McCalle78aac42010-03-10 03:28:59 +00002124#ifndef NDEBUG
2125static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2126 if (!isa<CXXRecordDecl>(D)) return false;
2127 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2128 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2129 return true;
2130 if (RD->getDescribedClassTemplate() &&
2131 !isa<ClassTemplateSpecializationDecl>(RD))
2132 return true;
2133 return false;
2134}
2135#endif
2136
2137/// getInjectedClassNameType - Return the unique reference to the
2138/// injected class name type for the specified templated declaration.
2139QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002140 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002141 assert(NeedsInjectedClassNameType(Decl));
2142 if (Decl->TypeForDecl) {
2143 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00002144 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00002145 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2146 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2147 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2148 } else {
John McCall424cec92011-01-19 06:33:43 +00002149 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002150 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002151 Decl->TypeForDecl = newType;
2152 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002153 }
2154 return QualType(Decl->TypeForDecl, 0);
2155}
2156
Douglas Gregor83a586e2008-04-13 21:07:44 +00002157/// getTypeDeclType - Return the unique reference to the type for the
2158/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002159QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002160 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002161 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002162
Richard Smithdda56e42011-04-15 14:24:37 +00002163 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002164 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002165
John McCall96f0b5f2010-03-10 06:48:02 +00002166 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2167 "Template type parameter types are always available.");
2168
John McCall81e38502010-02-16 03:57:14 +00002169 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002170 assert(!Record->getPreviousDeclaration() &&
2171 "struct/union has previous declaration");
2172 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002173 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002174 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002175 assert(!Enum->getPreviousDeclaration() &&
2176 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002177 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002178 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002179 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002180 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2181 Decl->TypeForDecl = newType;
2182 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002183 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002184 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002185
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002186 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002187}
2188
Chris Lattner32d920b2007-01-26 02:01:53 +00002189/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002190/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002191QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002192ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2193 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002194 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002195
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002196 if (Canonical.isNull())
2197 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002198 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002199 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002200 Decl->TypeForDecl = newType;
2201 Types.push_back(newType);
2202 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002203}
2204
Jay Foad39c79802011-01-12 09:06:06 +00002205QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002206 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2207
2208 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2209 if (PrevDecl->TypeForDecl)
2210 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2211
John McCall424cec92011-01-19 06:33:43 +00002212 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2213 Decl->TypeForDecl = newType;
2214 Types.push_back(newType);
2215 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002216}
2217
Jay Foad39c79802011-01-12 09:06:06 +00002218QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002219 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2220
2221 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2222 if (PrevDecl->TypeForDecl)
2223 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2224
John McCall424cec92011-01-19 06:33:43 +00002225 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2226 Decl->TypeForDecl = newType;
2227 Types.push_back(newType);
2228 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002229}
2230
John McCall81904512011-01-06 01:58:22 +00002231QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2232 QualType modifiedType,
2233 QualType equivalentType) {
2234 llvm::FoldingSetNodeID id;
2235 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2236
2237 void *insertPos = 0;
2238 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2239 if (type) return QualType(type, 0);
2240
2241 QualType canon = getCanonicalType(equivalentType);
2242 type = new (*this, TypeAlignment)
2243 AttributedType(canon, attrKind, modifiedType, equivalentType);
2244
2245 Types.push_back(type);
2246 AttributedTypes.InsertNode(type, insertPos);
2247
2248 return QualType(type, 0);
2249}
2250
2251
John McCallcebee162009-10-18 09:09:24 +00002252/// \brief Retrieve a substitution-result type.
2253QualType
2254ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002255 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002256 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002257 && "replacement types must always be canonical");
2258
2259 llvm::FoldingSetNodeID ID;
2260 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2261 void *InsertPos = 0;
2262 SubstTemplateTypeParmType *SubstParm
2263 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2264
2265 if (!SubstParm) {
2266 SubstParm = new (*this, TypeAlignment)
2267 SubstTemplateTypeParmType(Parm, Replacement);
2268 Types.push_back(SubstParm);
2269 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2270 }
2271
2272 return QualType(SubstParm, 0);
2273}
2274
Douglas Gregorada4b792011-01-14 02:55:32 +00002275/// \brief Retrieve a
2276QualType ASTContext::getSubstTemplateTypeParmPackType(
2277 const TemplateTypeParmType *Parm,
2278 const TemplateArgument &ArgPack) {
2279#ifndef NDEBUG
2280 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2281 PEnd = ArgPack.pack_end();
2282 P != PEnd; ++P) {
2283 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2284 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2285 }
2286#endif
2287
2288 llvm::FoldingSetNodeID ID;
2289 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2290 void *InsertPos = 0;
2291 if (SubstTemplateTypeParmPackType *SubstParm
2292 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2293 return QualType(SubstParm, 0);
2294
2295 QualType Canon;
2296 if (!Parm->isCanonicalUnqualified()) {
2297 Canon = getCanonicalType(QualType(Parm, 0));
2298 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2299 ArgPack);
2300 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2301 }
2302
2303 SubstTemplateTypeParmPackType *SubstParm
2304 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2305 ArgPack);
2306 Types.push_back(SubstParm);
2307 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2308 return QualType(SubstParm, 0);
2309}
2310
Douglas Gregoreff93e02009-02-05 23:33:38 +00002311/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002312/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002313/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002314QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002315 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002316 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002317 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002318 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002319 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002320 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002321 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2322
2323 if (TypeParm)
2324 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002325
Chandler Carruth08836322011-05-01 00:51:33 +00002326 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002327 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002328 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002329
2330 TemplateTypeParmType *TypeCheck
2331 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2332 assert(!TypeCheck && "Template type parameter canonical type broken");
2333 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002334 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002335 TypeParm = new (*this, TypeAlignment)
2336 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002337
2338 Types.push_back(TypeParm);
2339 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2340
2341 return QualType(TypeParm, 0);
2342}
2343
John McCalle78aac42010-03-10 03:28:59 +00002344TypeSourceInfo *
2345ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2346 SourceLocation NameLoc,
2347 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002348 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002349 assert(!Name.getAsDependentTemplateName() &&
2350 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002351 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002352
2353 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2354 TemplateSpecializationTypeLoc TL
2355 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2356 TL.setTemplateNameLoc(NameLoc);
2357 TL.setLAngleLoc(Args.getLAngleLoc());
2358 TL.setRAngleLoc(Args.getRAngleLoc());
2359 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2360 TL.setArgLocInfo(i, Args[i].getLocInfo());
2361 return DI;
2362}
2363
Mike Stump11289f42009-09-09 15:08:12 +00002364QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002365ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002366 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002367 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002368 assert(!Template.getAsDependentTemplateName() &&
2369 "No dependent template names here!");
2370
John McCall6b51f282009-11-23 01:53:49 +00002371 unsigned NumArgs = Args.size();
2372
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002373 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002374 ArgVec.reserve(NumArgs);
2375 for (unsigned i = 0; i != NumArgs; ++i)
2376 ArgVec.push_back(Args[i].getArgument());
2377
John McCall2408e322010-04-27 00:57:59 +00002378 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002379 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002380}
2381
2382QualType
2383ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002384 const TemplateArgument *Args,
2385 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002386 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002387 assert(!Template.getAsDependentTemplateName() &&
2388 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002389 // Look through qualified template names.
2390 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2391 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002392
Richard Smith3f1b5d02011-05-05 21:57:07 +00002393 bool isTypeAlias =
2394 Template.getAsTemplateDecl() &&
2395 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2396
2397 QualType CanonType;
2398 if (!Underlying.isNull())
2399 CanonType = getCanonicalType(Underlying);
2400 else {
2401 assert(!isTypeAlias &&
2402 "Underlying type for template alias must be computed by caller");
2403 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2404 NumArgs);
2405 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002406
Douglas Gregora8e02e72009-07-28 23:00:59 +00002407 // Allocate the (non-canonical) template specialization type, but don't
2408 // try to unique it: these types typically have location information that
2409 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002410 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2411 sizeof(TemplateArgument) * NumArgs +
2412 (isTypeAlias ? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002413 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002414 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00002415 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00002416 Args, NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002417 CanonType,
2418 isTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002419
Douglas Gregor8bf42052009-02-09 18:46:07 +00002420 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002421 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002422}
2423
Mike Stump11289f42009-09-09 15:08:12 +00002424QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002425ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2426 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002427 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002428 assert(!Template.getAsDependentTemplateName() &&
2429 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002430 assert((!Template.getAsTemplateDecl() ||
2431 !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2432 "Underlying type for template alias must be computed by caller");
2433
Douglas Gregore29139c2011-03-03 17:04:51 +00002434 // Look through qualified template names.
2435 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2436 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002437
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002438 // Build the canonical template specialization type.
2439 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002440 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002441 CanonArgs.reserve(NumArgs);
2442 for (unsigned I = 0; I != NumArgs; ++I)
2443 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2444
2445 // Determine whether this canonical template specialization type already
2446 // exists.
2447 llvm::FoldingSetNodeID ID;
2448 TemplateSpecializationType::Profile(ID, CanonTemplate,
2449 CanonArgs.data(), NumArgs, *this);
2450
2451 void *InsertPos = 0;
2452 TemplateSpecializationType *Spec
2453 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2454
2455 if (!Spec) {
2456 // Allocate a new canonical template specialization type.
2457 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2458 sizeof(TemplateArgument) * NumArgs),
2459 TypeAlignment);
2460 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2461 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002462 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002463 Types.push_back(Spec);
2464 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2465 }
2466
2467 assert(Spec->isDependentType() &&
2468 "Non-dependent template-id type must have a canonical type");
2469 return QualType(Spec, 0);
2470}
2471
2472QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002473ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2474 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002475 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002476 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002477 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002478
2479 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002480 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002481 if (T)
2482 return QualType(T, 0);
2483
Douglas Gregorc42075a2010-02-04 18:10:26 +00002484 QualType Canon = NamedType;
2485 if (!Canon.isCanonical()) {
2486 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002487 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2488 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002489 (void)CheckT;
2490 }
2491
Abramo Bagnara6150c882010-05-11 21:36:43 +00002492 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002493 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002494 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002495 return QualType(T, 0);
2496}
2497
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002498QualType
Jay Foad39c79802011-01-12 09:06:06 +00002499ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002500 llvm::FoldingSetNodeID ID;
2501 ParenType::Profile(ID, InnerType);
2502
2503 void *InsertPos = 0;
2504 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2505 if (T)
2506 return QualType(T, 0);
2507
2508 QualType Canon = InnerType;
2509 if (!Canon.isCanonical()) {
2510 Canon = getCanonicalType(InnerType);
2511 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2512 assert(!CheckT && "Paren canonical type broken");
2513 (void)CheckT;
2514 }
2515
2516 T = new (*this) ParenType(InnerType, Canon);
2517 Types.push_back(T);
2518 ParenTypes.InsertNode(T, InsertPos);
2519 return QualType(T, 0);
2520}
2521
Douglas Gregor02085352010-03-31 20:19:30 +00002522QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2523 NestedNameSpecifier *NNS,
2524 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002525 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002526 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2527
2528 if (Canon.isNull()) {
2529 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002530 ElaboratedTypeKeyword CanonKeyword = Keyword;
2531 if (Keyword == ETK_None)
2532 CanonKeyword = ETK_Typename;
2533
2534 if (CanonNNS != NNS || CanonKeyword != Keyword)
2535 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002536 }
2537
2538 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002539 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002540
2541 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002542 DependentNameType *T
2543 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002544 if (T)
2545 return QualType(T, 0);
2546
Douglas Gregor02085352010-03-31 20:19:30 +00002547 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002548 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002549 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002550 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002551}
2552
Mike Stump11289f42009-09-09 15:08:12 +00002553QualType
John McCallc392f372010-06-11 00:33:02 +00002554ASTContext::getDependentTemplateSpecializationType(
2555 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002556 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002557 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002558 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002559 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002560 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002561 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2562 ArgCopy.push_back(Args[I].getArgument());
2563 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2564 ArgCopy.size(),
2565 ArgCopy.data());
2566}
2567
2568QualType
2569ASTContext::getDependentTemplateSpecializationType(
2570 ElaboratedTypeKeyword Keyword,
2571 NestedNameSpecifier *NNS,
2572 const IdentifierInfo *Name,
2573 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002574 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002575 assert((!NNS || NNS->isDependent()) &&
2576 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002577
Douglas Gregorc42075a2010-02-04 18:10:26 +00002578 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002579 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2580 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002581
2582 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002583 DependentTemplateSpecializationType *T
2584 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002585 if (T)
2586 return QualType(T, 0);
2587
John McCallc392f372010-06-11 00:33:02 +00002588 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002589
John McCallc392f372010-06-11 00:33:02 +00002590 ElaboratedTypeKeyword CanonKeyword = Keyword;
2591 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2592
2593 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002594 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002595 for (unsigned I = 0; I != NumArgs; ++I) {
2596 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2597 if (!CanonArgs[I].structurallyEquals(Args[I]))
2598 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002599 }
2600
John McCallc392f372010-06-11 00:33:02 +00002601 QualType Canon;
2602 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2603 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2604 Name, NumArgs,
2605 CanonArgs.data());
2606
2607 // Find the insert position again.
2608 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2609 }
2610
2611 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2612 sizeof(TemplateArgument) * NumArgs),
2613 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002614 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002615 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002616 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002617 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002618 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002619}
2620
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002621QualType ASTContext::getPackExpansionType(QualType Pattern,
2622 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002623 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002624 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002625
2626 assert(Pattern->containsUnexpandedParameterPack() &&
2627 "Pack expansions must expand one or more parameter packs");
2628 void *InsertPos = 0;
2629 PackExpansionType *T
2630 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2631 if (T)
2632 return QualType(T, 0);
2633
2634 QualType Canon;
2635 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002636 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002637
2638 // Find the insert position again.
2639 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2640 }
2641
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002642 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002643 Types.push_back(T);
2644 PackExpansionTypes.InsertNode(T, InsertPos);
2645 return QualType(T, 0);
2646}
2647
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002648/// CmpProtocolNames - Comparison predicate for sorting protocols
2649/// alphabetically.
2650static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2651 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002652 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002653}
2654
John McCall8b07ec22010-05-15 11:32:37 +00002655static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002656 unsigned NumProtocols) {
2657 if (NumProtocols == 0) return true;
2658
2659 for (unsigned i = 1; i != NumProtocols; ++i)
2660 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2661 return false;
2662 return true;
2663}
2664
2665static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002666 unsigned &NumProtocols) {
2667 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002668
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002669 // Sort protocols, keyed by name.
2670 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2671
2672 // Remove duplicates.
2673 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2674 NumProtocols = ProtocolsEnd-Protocols;
2675}
2676
John McCall8b07ec22010-05-15 11:32:37 +00002677QualType ASTContext::getObjCObjectType(QualType BaseType,
2678 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002679 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002680 // If the base type is an interface and there aren't any protocols
2681 // to add, then the interface type will do just fine.
2682 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2683 return BaseType;
2684
2685 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002686 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002687 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002688 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002689 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2690 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002691
John McCall8b07ec22010-05-15 11:32:37 +00002692 // Build the canonical type, which has the canonical base type and
2693 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002694 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002695 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2696 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2697 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002698 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002699 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002700 unsigned UniqueCount = NumProtocols;
2701
John McCallfc93cf92009-10-22 22:37:11 +00002702 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002703 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2704 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002705 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002706 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2707 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002708 }
2709
2710 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002711 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2712 }
2713
2714 unsigned Size = sizeof(ObjCObjectTypeImpl);
2715 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2716 void *Mem = Allocate(Size, TypeAlignment);
2717 ObjCObjectTypeImpl *T =
2718 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2719
2720 Types.push_back(T);
2721 ObjCObjectTypes.InsertNode(T, InsertPos);
2722 return QualType(T, 0);
2723}
2724
2725/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2726/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002727QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002728 llvm::FoldingSetNodeID ID;
2729 ObjCObjectPointerType::Profile(ID, ObjectT);
2730
2731 void *InsertPos = 0;
2732 if (ObjCObjectPointerType *QT =
2733 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2734 return QualType(QT, 0);
2735
2736 // Find the canonical object type.
2737 QualType Canonical;
2738 if (!ObjectT.isCanonical()) {
2739 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2740
2741 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002742 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2743 }
2744
Douglas Gregorf85bee62010-02-08 22:59:26 +00002745 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002746 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2747 ObjCObjectPointerType *QType =
2748 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002749
Steve Narofffb4330f2009-06-17 22:40:22 +00002750 Types.push_back(QType);
2751 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002752 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002753}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002754
Douglas Gregor1c283312010-08-11 12:19:30 +00002755/// getObjCInterfaceType - Return the unique reference to the type for the
2756/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad39c79802011-01-12 09:06:06 +00002757QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002758 if (Decl->TypeForDecl)
2759 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002760
Douglas Gregor1c283312010-08-11 12:19:30 +00002761 // FIXME: redeclarations?
2762 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2763 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2764 Decl->TypeForDecl = T;
2765 Types.push_back(T);
2766 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002767}
2768
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002769/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2770/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002771/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002772/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002773/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002774QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002775 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002776 if (tofExpr->isTypeDependent()) {
2777 llvm::FoldingSetNodeID ID;
2778 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002779
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002780 void *InsertPos = 0;
2781 DependentTypeOfExprType *Canon
2782 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2783 if (Canon) {
2784 // We already have a "canonical" version of an identical, dependent
2785 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002786 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002787 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002788 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002789 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002790 Canon
2791 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002792 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2793 toe = Canon;
2794 }
2795 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002796 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002797 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002798 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002799 Types.push_back(toe);
2800 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002801}
2802
Steve Naroffa773cd52007-08-01 18:02:17 +00002803/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2804/// TypeOfType AST's. The only motivation to unique these nodes would be
2805/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002806/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002807/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002808QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002809 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002810 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002811 Types.push_back(tot);
2812 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002813}
2814
Anders Carlssonad6bd352009-06-24 21:24:56 +00002815/// getDecltypeForExpr - Given an expr, will return the decltype for that
2816/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad39c79802011-01-12 09:06:06 +00002817static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002818 if (e->isTypeDependent())
2819 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002820
Anders Carlssonad6bd352009-06-24 21:24:56 +00002821 // If e is an id expression or a class member access, decltype(e) is defined
2822 // as the type of the entity named by e.
2823 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2824 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2825 return VD->getType();
2826 }
2827 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2828 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2829 return FD->getType();
2830 }
2831 // If e is a function call or an invocation of an overloaded operator,
2832 // (parentheses around e are ignored), decltype(e) is defined as the
2833 // return type of that function.
2834 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2835 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002836
Anders Carlssonad6bd352009-06-24 21:24:56 +00002837 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002838
2839 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002840 // defined as T&, otherwise decltype(e) is defined as T.
John McCall086a4642010-11-24 05:12:34 +00002841 if (e->isLValue())
Anders Carlssonad6bd352009-06-24 21:24:56 +00002842 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002843
Anders Carlssonad6bd352009-06-24 21:24:56 +00002844 return T;
2845}
2846
Anders Carlsson81df7b82009-06-24 19:06:50 +00002847/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2848/// DecltypeType AST's. The only motivation to unique these nodes would be
2849/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002850/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002851/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002852QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002853 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00002854
2855 // C++0x [temp.type]p2:
2856 // If an expression e involves a template parameter, decltype(e) denotes a
2857 // unique dependent type. Two such decltype-specifiers refer to the same
2858 // type only if their expressions are equivalent (14.5.6.1).
2859 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002860 llvm::FoldingSetNodeID ID;
2861 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002862
Douglas Gregora21f6c32009-07-30 23:36:40 +00002863 void *InsertPos = 0;
2864 DependentDecltypeType *Canon
2865 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2866 if (Canon) {
2867 // We already have a "canonical" version of an equivalent, dependent
2868 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002869 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002870 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002871 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002872 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002873 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002874 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2875 dt = Canon;
2876 }
2877 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002878 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002879 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002880 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002881 Types.push_back(dt);
2882 return QualType(dt, 0);
2883}
2884
Alexis Hunte852b102011-05-24 22:41:36 +00002885/// getUnaryTransformationType - We don't unique these, since the memory
2886/// savings are minimal and these are rare.
2887QualType ASTContext::getUnaryTransformType(QualType BaseType,
2888 QualType UnderlyingType,
2889 UnaryTransformType::UTTKind Kind)
2890 const {
2891 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00002892 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2893 Kind,
2894 UnderlyingType->isDependentType() ?
2895 QualType() : UnderlyingType);
Alexis Hunte852b102011-05-24 22:41:36 +00002896 Types.push_back(Ty);
2897 return QualType(Ty, 0);
2898}
2899
Richard Smithb2bc2e62011-02-21 20:05:19 +00002900/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00002901QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00002902 void *InsertPos = 0;
2903 if (!DeducedType.isNull()) {
2904 // Look in the folding set for an existing type.
2905 llvm::FoldingSetNodeID ID;
2906 AutoType::Profile(ID, DeducedType);
2907 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2908 return QualType(AT, 0);
2909 }
2910
2911 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2912 Types.push_back(AT);
2913 if (InsertPos)
2914 AutoTypes.InsertNode(AT, InsertPos);
2915 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00002916}
2917
Eli Friedman0dfb8892011-10-06 23:00:33 +00002918/// getAtomicType - Return the uniqued reference to the atomic type for
2919/// the given value type.
2920QualType ASTContext::getAtomicType(QualType T) const {
2921 // Unique pointers, to guarantee there is only one pointer of a particular
2922 // structure.
2923 llvm::FoldingSetNodeID ID;
2924 AtomicType::Profile(ID, T);
2925
2926 void *InsertPos = 0;
2927 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
2928 return QualType(AT, 0);
2929
2930 // If the atomic value type isn't canonical, this won't be a canonical type
2931 // either, so fill in the canonical type field.
2932 QualType Canonical;
2933 if (!T.isCanonical()) {
2934 Canonical = getAtomicType(getCanonicalType(T));
2935
2936 // Get the new insert position for the node we care about.
2937 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
2938 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2939 }
2940 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
2941 Types.push_back(New);
2942 AtomicTypes.InsertNode(New, InsertPos);
2943 return QualType(New, 0);
2944}
2945
Richard Smith02e85f32011-04-14 22:09:26 +00002946/// getAutoDeductType - Get type pattern for deducing against 'auto'.
2947QualType ASTContext::getAutoDeductType() const {
2948 if (AutoDeductTy.isNull())
2949 AutoDeductTy = getAutoType(QualType());
2950 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
2951 return AutoDeductTy;
2952}
2953
2954/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
2955QualType ASTContext::getAutoRRefDeductType() const {
2956 if (AutoRRefDeductTy.isNull())
2957 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
2958 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
2959 return AutoRRefDeductTy;
2960}
2961
Chris Lattnerfb072462007-01-23 05:45:31 +00002962/// getTagDeclType - Return the unique reference to the type for the
2963/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00002964QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002965 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002966 // FIXME: What is the design on getTagDeclType when it requires casting
2967 // away const? mutable?
2968 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002969}
2970
Mike Stump11289f42009-09-09 15:08:12 +00002971/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2972/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2973/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002974CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002975 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002976}
Chris Lattnerfb072462007-01-23 05:45:31 +00002977
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002978/// getSignedWCharType - Return the type of "signed wchar_t".
2979/// Used when in C++, as a GCC extension.
2980QualType ASTContext::getSignedWCharType() const {
2981 // FIXME: derive from "Target" ?
2982 return WCharTy;
2983}
2984
2985/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2986/// Used when in C++, as a GCC extension.
2987QualType ASTContext::getUnsignedWCharType() const {
2988 // FIXME: derive from "Target" ?
2989 return UnsignedIntTy;
2990}
2991
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002992/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2993/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2994QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002995 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002996}
2997
Chris Lattnera21ad802008-04-02 05:18:44 +00002998//===----------------------------------------------------------------------===//
2999// Type Operators
3000//===----------------------------------------------------------------------===//
3001
Jay Foad39c79802011-01-12 09:06:06 +00003002CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003003 // Push qualifiers into arrays, and then discard any remaining
3004 // qualifiers.
3005 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003006 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003007 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003008 QualType Result;
3009 if (isa<ArrayType>(Ty)) {
3010 Result = getArrayDecayedType(QualType(Ty,0));
3011 } else if (isa<FunctionType>(Ty)) {
3012 Result = getPointerType(QualType(Ty, 0));
3013 } else {
3014 Result = QualType(Ty, 0);
3015 }
3016
3017 return CanQualType::CreateUnsafe(Result);
3018}
3019
John McCall6c9dd522011-01-18 07:41:22 +00003020QualType ASTContext::getUnqualifiedArrayType(QualType type,
3021 Qualifiers &quals) {
3022 SplitQualType splitType = type.getSplitUnqualifiedType();
3023
3024 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3025 // the unqualified desugared type and then drops it on the floor.
3026 // We then have to strip that sugar back off with
3027 // getUnqualifiedDesugaredType(), which is silly.
3028 const ArrayType *AT =
3029 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
3030
3031 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003032 if (!AT) {
John McCall6c9dd522011-01-18 07:41:22 +00003033 quals = splitType.second;
3034 return QualType(splitType.first, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003035 }
3036
John McCall6c9dd522011-01-18 07:41:22 +00003037 // Otherwise, recurse on the array's element type.
3038 QualType elementType = AT->getElementType();
3039 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3040
3041 // If that didn't change the element type, AT has no qualifiers, so we
3042 // can just use the results in splitType.
3043 if (elementType == unqualElementType) {
3044 assert(quals.empty()); // from the recursive call
3045 quals = splitType.second;
3046 return QualType(splitType.first, 0);
3047 }
3048
3049 // Otherwise, add in the qualifiers from the outermost type, then
3050 // build the type back up.
3051 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003052
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003053 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003054 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003055 CAT->getSizeModifier(), 0);
3056 }
3057
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003058 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003059 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003060 }
3061
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003062 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003063 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003064 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003065 VAT->getSizeModifier(),
3066 VAT->getIndexTypeCVRQualifiers(),
3067 VAT->getBracketsRange());
3068 }
3069
3070 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003071 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003072 DSAT->getSizeModifier(), 0,
3073 SourceRange());
3074}
3075
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003076/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3077/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3078/// they point to and return true. If T1 and T2 aren't pointer types
3079/// or pointer-to-member types, or if they are not similar at this
3080/// level, returns false and leaves T1 and T2 unchanged. Top-level
3081/// qualifiers on T1 and T2 are ignored. This function will typically
3082/// be called in a loop that successively "unwraps" pointer and
3083/// pointer-to-member types to compare them at each level.
3084bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3085 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3086 *T2PtrType = T2->getAs<PointerType>();
3087 if (T1PtrType && T2PtrType) {
3088 T1 = T1PtrType->getPointeeType();
3089 T2 = T2PtrType->getPointeeType();
3090 return true;
3091 }
3092
3093 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3094 *T2MPType = T2->getAs<MemberPointerType>();
3095 if (T1MPType && T2MPType &&
3096 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3097 QualType(T2MPType->getClass(), 0))) {
3098 T1 = T1MPType->getPointeeType();
3099 T2 = T2MPType->getPointeeType();
3100 return true;
3101 }
3102
3103 if (getLangOptions().ObjC1) {
3104 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3105 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3106 if (T1OPType && T2OPType) {
3107 T1 = T1OPType->getPointeeType();
3108 T2 = T2OPType->getPointeeType();
3109 return true;
3110 }
3111 }
3112
3113 // FIXME: Block pointers, too?
3114
3115 return false;
3116}
3117
Jay Foad39c79802011-01-12 09:06:06 +00003118DeclarationNameInfo
3119ASTContext::getNameForTemplate(TemplateName Name,
3120 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003121 switch (Name.getKind()) {
3122 case TemplateName::QualifiedTemplate:
3123 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003124 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003125 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3126 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003127
John McCalld9dfe3a2011-06-30 08:33:18 +00003128 case TemplateName::OverloadedTemplate: {
3129 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3130 // DNInfo work in progress: CHECKME: what about DNLoc?
3131 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3132 }
3133
3134 case TemplateName::DependentTemplate: {
3135 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003136 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003137 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003138 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3139 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003140 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003141 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3142 // DNInfo work in progress: FIXME: source locations?
3143 DeclarationNameLoc DNLoc;
3144 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3145 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3146 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003147 }
3148 }
3149
John McCalld9dfe3a2011-06-30 08:33:18 +00003150 case TemplateName::SubstTemplateTemplateParm: {
3151 SubstTemplateTemplateParmStorage *subst
3152 = Name.getAsSubstTemplateTemplateParm();
3153 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3154 NameLoc);
3155 }
3156
3157 case TemplateName::SubstTemplateTemplateParmPack: {
3158 SubstTemplateTemplateParmPackStorage *subst
3159 = Name.getAsSubstTemplateTemplateParmPack();
3160 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3161 NameLoc);
3162 }
3163 }
3164
3165 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003166}
3167
Jay Foad39c79802011-01-12 09:06:06 +00003168TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003169 switch (Name.getKind()) {
3170 case TemplateName::QualifiedTemplate:
3171 case TemplateName::Template: {
3172 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003173 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003174 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003175 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3176
3177 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003178 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003179 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003180
John McCalld9dfe3a2011-06-30 08:33:18 +00003181 case TemplateName::OverloadedTemplate:
3182 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003183
John McCalld9dfe3a2011-06-30 08:33:18 +00003184 case TemplateName::DependentTemplate: {
3185 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3186 assert(DTN && "Non-dependent template names must refer to template decls.");
3187 return DTN->CanonicalTemplateName;
3188 }
3189
3190 case TemplateName::SubstTemplateTemplateParm: {
3191 SubstTemplateTemplateParmStorage *subst
3192 = Name.getAsSubstTemplateTemplateParm();
3193 return getCanonicalTemplateName(subst->getReplacement());
3194 }
3195
3196 case TemplateName::SubstTemplateTemplateParmPack: {
3197 SubstTemplateTemplateParmPackStorage *subst
3198 = Name.getAsSubstTemplateTemplateParmPack();
3199 TemplateTemplateParmDecl *canonParameter
3200 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3201 TemplateArgument canonArgPack
3202 = getCanonicalTemplateArgument(subst->getArgumentPack());
3203 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3204 }
3205 }
3206
3207 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003208}
3209
Douglas Gregoradee3e32009-11-11 23:06:43 +00003210bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3211 X = getCanonicalTemplateName(X);
3212 Y = getCanonicalTemplateName(Y);
3213 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3214}
3215
Mike Stump11289f42009-09-09 15:08:12 +00003216TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003217ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003218 switch (Arg.getKind()) {
3219 case TemplateArgument::Null:
3220 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003221
Douglas Gregora8e02e72009-07-28 23:00:59 +00003222 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003223 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003224
Douglas Gregora8e02e72009-07-28 23:00:59 +00003225 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00003226 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003227
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003228 case TemplateArgument::Template:
3229 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003230
3231 case TemplateArgument::TemplateExpansion:
3232 return TemplateArgument(getCanonicalTemplateName(
3233 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003234 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003235
Douglas Gregora8e02e72009-07-28 23:00:59 +00003236 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00003237 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003238 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003239
Douglas Gregora8e02e72009-07-28 23:00:59 +00003240 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003241 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003242
Douglas Gregora8e02e72009-07-28 23:00:59 +00003243 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003244 if (Arg.pack_size() == 0)
3245 return Arg;
3246
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003247 TemplateArgument *CanonArgs
3248 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003249 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003250 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003251 AEnd = Arg.pack_end();
3252 A != AEnd; (void)++A, ++Idx)
3253 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003254
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003255 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003256 }
3257 }
3258
3259 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003260 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003261}
3262
Douglas Gregor333489b2009-03-27 23:10:48 +00003263NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003264ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003265 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003266 return 0;
3267
3268 switch (NNS->getKind()) {
3269 case NestedNameSpecifier::Identifier:
3270 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003271 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003272 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3273 NNS->getAsIdentifier());
3274
3275 case NestedNameSpecifier::Namespace:
3276 // A namespace is canonical; build a nested-name-specifier with
3277 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003278 return NestedNameSpecifier::Create(*this, 0,
3279 NNS->getAsNamespace()->getOriginalNamespace());
3280
3281 case NestedNameSpecifier::NamespaceAlias:
3282 // A namespace is canonical; build a nested-name-specifier with
3283 // this namespace and no prefix.
3284 return NestedNameSpecifier::Create(*this, 0,
3285 NNS->getAsNamespaceAlias()->getNamespace()
3286 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003287
3288 case NestedNameSpecifier::TypeSpec:
3289 case NestedNameSpecifier::TypeSpecWithTemplate: {
3290 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003291
3292 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3293 // break it apart into its prefix and identifier, then reconsititute those
3294 // as the canonical nested-name-specifier. This is required to canonicalize
3295 // a dependent nested-name-specifier involving typedefs of dependent-name
3296 // types, e.g.,
3297 // typedef typename T::type T1;
3298 // typedef typename T1::type T2;
3299 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3300 NestedNameSpecifier *Prefix
3301 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3302 return NestedNameSpecifier::Create(*this, Prefix,
3303 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3304 }
3305
Douglas Gregorcc10cbf2010-11-04 00:14:23 +00003306 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor3ade5702010-11-04 00:09:33 +00003307 if (const DependentTemplateSpecializationType *DTST
3308 = T->getAs<DependentTemplateSpecializationType>()) {
3309 NestedNameSpecifier *Prefix
3310 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregor6e068012011-02-28 00:04:36 +00003311
3312 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3313 Prefix, DTST->getIdentifier(),
3314 DTST->getNumArgs(),
3315 DTST->getArgs());
Douglas Gregor3ade5702010-11-04 00:09:33 +00003316 T = getCanonicalType(T);
3317 }
3318
John McCall33ddac02011-01-19 10:06:00 +00003319 return NestedNameSpecifier::Create(*this, 0, false,
3320 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003321 }
3322
3323 case NestedNameSpecifier::Global:
3324 // The global specifier is canonical and unique.
3325 return NNS;
3326 }
3327
3328 // Required to silence a GCC warning
3329 return 0;
3330}
3331
Chris Lattner7adf0762008-08-04 07:31:14 +00003332
Jay Foad39c79802011-01-12 09:06:06 +00003333const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003334 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003335 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003336 // Handle the common positive case fast.
3337 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3338 return AT;
3339 }
Mike Stump11289f42009-09-09 15:08:12 +00003340
John McCall8ccfcb52009-09-24 19:53:00 +00003341 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003342 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003343 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003344
John McCall8ccfcb52009-09-24 19:53:00 +00003345 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003346 // implements C99 6.7.3p8: "If the specification of an array type includes
3347 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003348
Chris Lattner7adf0762008-08-04 07:31:14 +00003349 // If we get here, we either have type qualifiers on the type, or we have
3350 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003351 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003352
John McCall33ddac02011-01-19 10:06:00 +00003353 SplitQualType split = T.getSplitDesugaredType();
3354 Qualifiers qs = split.second;
Mike Stump11289f42009-09-09 15:08:12 +00003355
Chris Lattner7adf0762008-08-04 07:31:14 +00003356 // If we have a simple case, just return now.
John McCall33ddac02011-01-19 10:06:00 +00003357 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3358 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003359 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003360
Chris Lattner7adf0762008-08-04 07:31:14 +00003361 // Otherwise, we have an array and we have qualifiers on it. Push the
3362 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003363 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003364
Chris Lattner7adf0762008-08-04 07:31:14 +00003365 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3366 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3367 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003368 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003369 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3370 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3371 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003372 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003373
Mike Stump11289f42009-09-09 15:08:12 +00003374 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003375 = dyn_cast<DependentSizedArrayType>(ATy))
3376 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003377 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003378 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003379 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003380 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003381 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003382
Chris Lattner7adf0762008-08-04 07:31:14 +00003383 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003384 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003385 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003386 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003387 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003388 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003389}
3390
Douglas Gregor84280642011-07-12 04:42:08 +00003391QualType ASTContext::getAdjustedParameterType(QualType T) {
3392 // C99 6.7.5.3p7:
3393 // A declaration of a parameter as "array of type" shall be
3394 // adjusted to "qualified pointer to type", where the type
3395 // qualifiers (if any) are those specified within the [ and ] of
3396 // the array type derivation.
3397 if (T->isArrayType())
3398 return getArrayDecayedType(T);
3399
3400 // C99 6.7.5.3p8:
3401 // A declaration of a parameter as "function returning type"
3402 // shall be adjusted to "pointer to function returning type", as
3403 // in 6.3.2.1.
3404 if (T->isFunctionType())
3405 return getPointerType(T);
3406
3407 return T;
3408}
3409
3410QualType ASTContext::getSignatureParameterType(QualType T) {
3411 T = getVariableArrayDecayedType(T);
3412 T = getAdjustedParameterType(T);
3413 return T.getUnqualifiedType();
3414}
3415
Chris Lattnera21ad802008-04-02 05:18:44 +00003416/// getArrayDecayedType - Return the properly qualified result of decaying the
3417/// specified array type to a pointer. This operation is non-trivial when
3418/// handling typedefs etc. The canonical type of "T" must be an array type,
3419/// this returns a pointer to a properly qualified element of the array.
3420///
3421/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003422QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003423 // Get the element type with 'getAsArrayType' so that we don't lose any
3424 // typedefs in the element type of the array. This also handles propagation
3425 // of type qualifiers from the array type into the element type if present
3426 // (C99 6.7.3p8).
3427 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3428 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003429
Chris Lattner7adf0762008-08-04 07:31:14 +00003430 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003431
3432 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003433 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003434}
3435
John McCall33ddac02011-01-19 10:06:00 +00003436QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3437 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003438}
3439
John McCall33ddac02011-01-19 10:06:00 +00003440QualType ASTContext::getBaseElementType(QualType type) const {
3441 Qualifiers qs;
3442 while (true) {
3443 SplitQualType split = type.getSplitDesugaredType();
3444 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3445 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003446
John McCall33ddac02011-01-19 10:06:00 +00003447 type = array->getElementType();
3448 qs.addConsistentQualifiers(split.second);
3449 }
Mike Stump11289f42009-09-09 15:08:12 +00003450
John McCall33ddac02011-01-19 10:06:00 +00003451 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003452}
3453
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003454/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003455uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003456ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3457 uint64_t ElementCount = 1;
3458 do {
3459 ElementCount *= CA->getSize().getZExtValue();
3460 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3461 } while (CA);
3462 return ElementCount;
3463}
3464
Steve Naroff0af91202007-04-27 21:51:21 +00003465/// getFloatingRank - Return a relative rank for floating point types.
3466/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003467static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003468 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003469 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003470
John McCall9dd450b2009-09-21 23:43:11 +00003471 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3472 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003473 default: llvm_unreachable("getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00003474 case BuiltinType::Float: return FloatRank;
3475 case BuiltinType::Double: return DoubleRank;
3476 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003477 }
3478}
3479
Mike Stump11289f42009-09-09 15:08:12 +00003480/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3481/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003482/// 'typeDomain' is a real floating point or complex type.
3483/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003484QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3485 QualType Domain) const {
3486 FloatingRank EltRank = getFloatingRank(Size);
3487 if (Domain->isComplexType()) {
3488 switch (EltRank) {
David Blaikie83d382b2011-09-23 05:06:16 +00003489 default: llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00003490 case FloatRank: return FloatComplexTy;
3491 case DoubleRank: return DoubleComplexTy;
3492 case LongDoubleRank: return LongDoubleComplexTy;
3493 }
Steve Naroff0af91202007-04-27 21:51:21 +00003494 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003495
3496 assert(Domain->isRealFloatingType() && "Unknown domain!");
3497 switch (EltRank) {
David Blaikie83d382b2011-09-23 05:06:16 +00003498 default: llvm_unreachable("getFloatingRank(): illegal value for rank");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003499 case FloatRank: return FloatTy;
3500 case DoubleRank: return DoubleTy;
3501 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003502 }
Steve Naroffe4718892007-04-27 18:30:00 +00003503}
3504
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003505/// getFloatingTypeOrder - Compare the rank of the two specified floating
3506/// point types, ignoring the domain of the type (i.e. 'double' ==
3507/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003508/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003509int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003510 FloatingRank LHSR = getFloatingRank(LHS);
3511 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003512
Chris Lattnerb90739d2008-04-06 23:38:49 +00003513 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003514 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003515 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003516 return 1;
3517 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003518}
3519
Chris Lattner76a00cf2008-04-06 22:59:24 +00003520/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3521/// routine will assert if passed a built-in type that isn't an integer or enum,
3522/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003523unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003524 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCall424cec92011-01-19 06:33:43 +00003525 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00003526 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00003527
Chris Lattnerad3467e2010-12-25 23:25:43 +00003528 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3529 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Douglas Gregore8bbc122011-09-02 00:18:52 +00003530 T = getFromTargetType(Target->getWCharType()).getTypePtr();
Eli Friedmanc131d3b2009-07-05 23:44:27 +00003531
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003532 if (T->isSpecificBuiltinType(BuiltinType::Char16))
Douglas Gregore8bbc122011-09-02 00:18:52 +00003533 T = getFromTargetType(Target->getChar16Type()).getTypePtr();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003534
3535 if (T->isSpecificBuiltinType(BuiltinType::Char32))
Douglas Gregore8bbc122011-09-02 00:18:52 +00003536 T = getFromTargetType(Target->getChar32Type()).getTypePtr();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003537
Chris Lattner76a00cf2008-04-06 22:59:24 +00003538 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003539 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003540 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003541 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003542 case BuiltinType::Char_S:
3543 case BuiltinType::Char_U:
3544 case BuiltinType::SChar:
3545 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003546 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003547 case BuiltinType::Short:
3548 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003549 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003550 case BuiltinType::Int:
3551 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003552 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003553 case BuiltinType::Long:
3554 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003555 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003556 case BuiltinType::LongLong:
3557 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003558 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003559 case BuiltinType::Int128:
3560 case BuiltinType::UInt128:
3561 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003562 }
3563}
3564
Eli Friedman629ffb92009-08-20 04:21:42 +00003565/// \brief Whether this is a promotable bitfield reference according
3566/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3567///
3568/// \returns the type this bit-field will promote to, or NULL if no
3569/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003570QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003571 if (E->isTypeDependent() || E->isValueDependent())
3572 return QualType();
3573
Eli Friedman629ffb92009-08-20 04:21:42 +00003574 FieldDecl *Field = E->getBitField();
3575 if (!Field)
3576 return QualType();
3577
3578 QualType FT = Field->getType();
3579
Richard Smithcaf33902011-10-10 18:28:20 +00003580 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00003581 uint64_t IntSize = getTypeSize(IntTy);
3582 // GCC extension compatibility: if the bit-field size is less than or equal
3583 // to the size of int, it gets promoted no matter what its type is.
3584 // For instance, unsigned long bf : 4 gets promoted to signed int.
3585 if (BitWidth < IntSize)
3586 return IntTy;
3587
3588 if (BitWidth == IntSize)
3589 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3590
3591 // Types bigger than int are not subject to promotions, and therefore act
3592 // like the base type.
3593 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3594 // is ridiculous.
3595 return QualType();
3596}
3597
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003598/// getPromotedIntegerType - Returns the type that Promotable will
3599/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3600/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003601QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003602 assert(!Promotable.isNull());
3603 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003604 if (const EnumType *ET = Promotable->getAs<EnumType>())
3605 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003606 if (Promotable->isSignedIntegerType())
3607 return IntTy;
3608 uint64_t PromotableSize = getTypeSize(Promotable);
3609 uint64_t IntSize = getTypeSize(IntTy);
3610 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3611 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3612}
3613
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003614/// \brief Recurses in pointer/array types until it finds an objc retainable
3615/// type and returns its ownership.
3616Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3617 while (!T.isNull()) {
3618 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3619 return T.getObjCLifetime();
3620 if (T->isArrayType())
3621 T = getBaseElementType(T);
3622 else if (const PointerType *PT = T->getAs<PointerType>())
3623 T = PT->getPointeeType();
3624 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003625 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003626 else
3627 break;
3628 }
3629
3630 return Qualifiers::OCL_None;
3631}
3632
Mike Stump11289f42009-09-09 15:08:12 +00003633/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003634/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003635/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003636int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003637 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3638 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003639 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003640
Chris Lattner76a00cf2008-04-06 22:59:24 +00003641 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3642 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003643
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003644 unsigned LHSRank = getIntegerRank(LHSC);
3645 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003646
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003647 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3648 if (LHSRank == RHSRank) return 0;
3649 return LHSRank > RHSRank ? 1 : -1;
3650 }
Mike Stump11289f42009-09-09 15:08:12 +00003651
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003652 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3653 if (LHSUnsigned) {
3654 // If the unsigned [LHS] type is larger, return it.
3655 if (LHSRank >= RHSRank)
3656 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003657
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003658 // If the signed type can represent all values of the unsigned type, it
3659 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003660 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003661 return -1;
3662 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003663
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003664 // If the unsigned [RHS] type is larger, return it.
3665 if (RHSRank >= LHSRank)
3666 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003667
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003668 // If the signed type can represent all values of the unsigned type, it
3669 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003670 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003671 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003672}
Anders Carlsson98f07902007-08-17 05:31:46 +00003673
Anders Carlsson6d417272009-11-14 21:45:58 +00003674static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003675CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3676 DeclContext *DC, IdentifierInfo *Id) {
3677 SourceLocation Loc;
Anders Carlsson6d417272009-11-14 21:45:58 +00003678 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003679 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003680 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003681 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003682}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003683
Mike Stump11289f42009-09-09 15:08:12 +00003684// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003685QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003686 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003687 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003688 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003689 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003690 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003691
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003692 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003693
Anders Carlsson98f07902007-08-17 05:31:46 +00003694 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003695 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003696 // int flags;
3697 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003698 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003699 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003700 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003701 FieldTypes[3] = LongTy;
3702
Anders Carlsson98f07902007-08-17 05:31:46 +00003703 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003704 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003705 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003706 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003707 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003708 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003709 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003710 /*Mutable=*/false,
3711 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003712 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003713 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003714 }
3715
Douglas Gregord5058122010-02-11 01:19:42 +00003716 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003717 }
Mike Stump11289f42009-09-09 15:08:12 +00003718
Anders Carlsson98f07902007-08-17 05:31:46 +00003719 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003720}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003721
Douglas Gregor512b0772009-04-23 22:29:11 +00003722void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003723 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003724 assert(Rec && "Invalid CFConstantStringType");
3725 CFConstantStringTypeDecl = Rec->getDecl();
3726}
3727
Jay Foad39c79802011-01-12 09:06:06 +00003728QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003729 if (BlockDescriptorType)
3730 return getTagDeclType(BlockDescriptorType);
3731
3732 RecordDecl *T;
3733 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003734 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003735 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003736 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003737
3738 QualType FieldTypes[] = {
3739 UnsignedLongTy,
3740 UnsignedLongTy,
3741 };
3742
3743 const char *FieldNames[] = {
3744 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003745 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003746 };
3747
3748 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003749 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003750 SourceLocation(),
3751 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003752 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003753 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003754 /*Mutable=*/false,
3755 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003756 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003757 T->addDecl(Field);
3758 }
3759
Douglas Gregord5058122010-02-11 01:19:42 +00003760 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003761
3762 BlockDescriptorType = T;
3763
3764 return getTagDeclType(BlockDescriptorType);
3765}
3766
Jay Foad39c79802011-01-12 09:06:06 +00003767QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003768 if (BlockDescriptorExtendedType)
3769 return getTagDeclType(BlockDescriptorExtendedType);
3770
3771 RecordDecl *T;
3772 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003773 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003774 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003775 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003776
3777 QualType FieldTypes[] = {
3778 UnsignedLongTy,
3779 UnsignedLongTy,
3780 getPointerType(VoidPtrTy),
3781 getPointerType(VoidPtrTy)
3782 };
3783
3784 const char *FieldNames[] = {
3785 "reserved",
3786 "Size",
3787 "CopyFuncPtr",
3788 "DestroyFuncPtr"
3789 };
3790
3791 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003792 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003793 SourceLocation(),
3794 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003795 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003796 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003797 /*Mutable=*/false,
3798 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003799 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003800 T->addDecl(Field);
3801 }
3802
Douglas Gregord5058122010-02-11 01:19:42 +00003803 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003804
3805 BlockDescriptorExtendedType = T;
3806
3807 return getTagDeclType(BlockDescriptorExtendedType);
3808}
3809
Jay Foad39c79802011-01-12 09:06:06 +00003810bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00003811 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00003812 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003813 if (getLangOptions().CPlusPlus) {
3814 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3815 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00003816 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003817
3818 }
3819 }
Mike Stump94967902009-10-21 18:16:27 +00003820 return false;
3821}
3822
Jay Foad39c79802011-01-12 09:06:06 +00003823QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003824ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003825 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003826 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003827 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003828 // unsigned int __flags;
3829 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003830 // void *__copy_helper; // as needed
3831 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003832 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003833 // } *
3834
Mike Stump94967902009-10-21 18:16:27 +00003835 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3836
3837 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003838 llvm::SmallString<36> Name;
3839 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3840 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003841 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003842 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003843 T->startDefinition();
3844 QualType Int32Ty = IntTy;
3845 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3846 QualType FieldTypes[] = {
3847 getPointerType(VoidPtrTy),
3848 getPointerType(getTagDeclType(T)),
3849 Int32Ty,
3850 Int32Ty,
3851 getPointerType(VoidPtrTy),
3852 getPointerType(VoidPtrTy),
3853 Ty
3854 };
3855
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003856 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003857 "__isa",
3858 "__forwarding",
3859 "__flags",
3860 "__size",
3861 "__copy_helper",
3862 "__destroy_helper",
3863 DeclName,
3864 };
3865
3866 for (size_t i = 0; i < 7; ++i) {
3867 if (!HasCopyAndDispose && i >=4 && i <= 5)
3868 continue;
3869 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003870 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00003871 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003872 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003873 /*BitWidth=*/0, /*Mutable=*/false,
3874 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003875 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003876 T->addDecl(Field);
3877 }
3878
Douglas Gregord5058122010-02-11 01:19:42 +00003879 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003880
3881 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003882}
3883
Douglas Gregorbab8a962011-09-08 01:46:34 +00003884TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
3885 if (!ObjCInstanceTypeDecl)
3886 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
3887 getTranslationUnitDecl(),
3888 SourceLocation(),
3889 SourceLocation(),
3890 &Idents.get("instancetype"),
3891 getTrivialTypeSourceInfo(getObjCIdType()));
3892 return ObjCInstanceTypeDecl;
3893}
3894
Anders Carlsson18acd442007-10-29 06:33:42 +00003895// This returns true if a type has been typedefed to BOOL:
3896// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003897static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003898 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003899 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3900 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003901
Anders Carlssond8499822007-10-29 05:01:08 +00003902 return false;
3903}
3904
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003905/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003906/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00003907CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00003908 if (!type->isIncompleteArrayType() && type->isIncompleteType())
3909 return CharUnits::Zero();
3910
Ken Dyck40775002010-01-11 17:06:35 +00003911 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003912
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003913 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003914 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003915 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003916 // Treat arrays as pointers, since that's how they're passed in.
3917 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003918 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003919 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003920}
3921
3922static inline
3923std::string charUnitsToString(const CharUnits &CU) {
3924 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003925}
3926
John McCall351762c2011-02-07 10:33:21 +00003927/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003928/// declaration.
John McCall351762c2011-02-07 10:33:21 +00003929std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3930 std::string S;
3931
David Chisnall950a9512009-11-17 19:33:30 +00003932 const BlockDecl *Decl = Expr->getBlockDecl();
3933 QualType BlockTy =
3934 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3935 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003936 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003937 // Compute size of all parameters.
3938 // Start with computing size of a pointer in number of bytes.
3939 // FIXME: There might(should) be a better way of doing this computation!
3940 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003941 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3942 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003943 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003944 E = Decl->param_end(); PI != E; ++PI) {
3945 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003946 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003947 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003948 ParmOffset += sz;
3949 }
3950 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003951 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003952 // Block pointer and offset.
3953 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00003954
3955 // Argument types.
3956 ParmOffset = PtrSize;
3957 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3958 Decl->param_end(); PI != E; ++PI) {
3959 ParmVarDecl *PVDecl = *PI;
3960 QualType PType = PVDecl->getOriginalType();
3961 if (const ArrayType *AT =
3962 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3963 // Use array's original type only if it has known number of
3964 // elements.
3965 if (!isa<ConstantArrayType>(AT))
3966 PType = PVDecl->getType();
3967 } else if (PType->isFunctionType())
3968 PType = PVDecl->getType();
3969 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003970 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003971 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003972 }
John McCall351762c2011-02-07 10:33:21 +00003973
3974 return S;
David Chisnall950a9512009-11-17 19:33:30 +00003975}
3976
Douglas Gregora9d84932011-05-27 01:19:52 +00003977bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00003978 std::string& S) {
3979 // Encode result type.
3980 getObjCEncodingForType(Decl->getResultType(), S);
3981 CharUnits ParmOffset;
3982 // Compute size of all parameters.
3983 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3984 E = Decl->param_end(); PI != E; ++PI) {
3985 QualType PType = (*PI)->getType();
3986 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00003987 if (sz.isZero())
3988 return true;
3989
David Chisnall50e4eba2010-12-30 14:05:53 +00003990 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00003991 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00003992 ParmOffset += sz;
3993 }
3994 S += charUnitsToString(ParmOffset);
3995 ParmOffset = CharUnits::Zero();
3996
3997 // Argument types.
3998 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3999 E = Decl->param_end(); PI != E; ++PI) {
4000 ParmVarDecl *PVDecl = *PI;
4001 QualType PType = PVDecl->getOriginalType();
4002 if (const ArrayType *AT =
4003 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4004 // Use array's original type only if it has known number of
4005 // elements.
4006 if (!isa<ConstantArrayType>(AT))
4007 PType = PVDecl->getType();
4008 } else if (PType->isFunctionType())
4009 PType = PVDecl->getType();
4010 getObjCEncodingForType(PType, S);
4011 S += charUnitsToString(ParmOffset);
4012 ParmOffset += getObjCEncodingTypeSize(PType);
4013 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004014
4015 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004016}
4017
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004018/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004019/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004020bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00004021 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004022 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004023 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004024 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004025 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004026 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004027 // Compute size of all parameters.
4028 // Start with computing size of a pointer in number of bytes.
4029 // FIXME: There might(should) be a better way of doing this computation!
4030 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004031 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004032 // The first two arguments (self and _cmd) are pointers; account for
4033 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004034 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004035 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004036 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004037 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004038 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004039 if (sz.isZero())
4040 return true;
4041
Ken Dyck40775002010-01-11 17:06:35 +00004042 assert (sz.isPositive() &&
4043 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004044 ParmOffset += sz;
4045 }
Ken Dyck40775002010-01-11 17:06:35 +00004046 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004047 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004048 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004049
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004050 // Argument types.
4051 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004052 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004053 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004054 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004055 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004056 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004057 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4058 // Use array's original type only if it has known number of
4059 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004060 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004061 PType = PVDecl->getType();
4062 } else if (PType->isFunctionType())
4063 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004064 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004065 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004066 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004067 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004068 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004069 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004070 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004071
4072 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004073}
4074
Daniel Dunbar4932b362008-08-28 04:38:10 +00004075/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004076/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004077/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4078/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004079/// Property attributes are stored as a comma-delimited C string. The simple
4080/// attributes readonly and bycopy are encoded as single characters. The
4081/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4082/// encoded as single characters, followed by an identifier. Property types
4083/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004084/// these attributes are defined by the following enumeration:
4085/// @code
4086/// enum PropertyAttributes {
4087/// kPropertyReadOnly = 'R', // property is read-only.
4088/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4089/// kPropertyByref = '&', // property is a reference to the value last assigned
4090/// kPropertyDynamic = 'D', // property is dynamic
4091/// kPropertyGetter = 'G', // followed by getter selector name
4092/// kPropertySetter = 'S', // followed by setter selector name
4093/// kPropertyInstanceVariable = 'V' // followed by instance variable name
4094/// kPropertyType = 't' // followed by old-style type encoding.
4095/// kPropertyWeak = 'W' // 'weak' property
4096/// kPropertyStrong = 'P' // property GC'able
4097/// kPropertyNonAtomic = 'N' // property non-atomic
4098/// };
4099/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004100void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004101 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004102 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004103 // Collect information from the property implementation decl(s).
4104 bool Dynamic = false;
4105 ObjCPropertyImplDecl *SynthesizePID = 0;
4106
4107 // FIXME: Duplicated code due to poor abstraction.
4108 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004109 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004110 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4111 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004112 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004113 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004114 ObjCPropertyImplDecl *PID = *i;
4115 if (PID->getPropertyDecl() == PD) {
4116 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4117 Dynamic = true;
4118 } else {
4119 SynthesizePID = PID;
4120 }
4121 }
4122 }
4123 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004124 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004125 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004126 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004127 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004128 ObjCPropertyImplDecl *PID = *i;
4129 if (PID->getPropertyDecl() == PD) {
4130 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4131 Dynamic = true;
4132 } else {
4133 SynthesizePID = PID;
4134 }
4135 }
Mike Stump11289f42009-09-09 15:08:12 +00004136 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004137 }
4138 }
4139
4140 // FIXME: This is not very efficient.
4141 S = "T";
4142
4143 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004144 // GCC has some special rules regarding encoding of properties which
4145 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004146 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004147 true /* outermost type */,
4148 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004149
4150 if (PD->isReadOnly()) {
4151 S += ",R";
4152 } else {
4153 switch (PD->getSetterKind()) {
4154 case ObjCPropertyDecl::Assign: break;
4155 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004156 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004157 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004158 }
4159 }
4160
4161 // It really isn't clear at all what this means, since properties
4162 // are "dynamic by default".
4163 if (Dynamic)
4164 S += ",D";
4165
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004166 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4167 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004168
Daniel Dunbar4932b362008-08-28 04:38:10 +00004169 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4170 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004171 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004172 }
4173
4174 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4175 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004176 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004177 }
4178
4179 if (SynthesizePID) {
4180 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4181 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004182 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004183 }
4184
4185 // FIXME: OBJCGC: weak & strong
4186}
4187
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004188/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004189/// Another legacy compatibility encoding: 32-bit longs are encoded as
4190/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004191/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4192///
4193void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004194 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004195 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004196 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004197 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004198 else
Jay Foad39c79802011-01-12 09:06:06 +00004199 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004200 PointeeTy = IntTy;
4201 }
4202 }
4203}
4204
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004205void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004206 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004207 // We follow the behavior of gcc, expanding structures which are
4208 // directly pointed to, and expanding embedded structures. Note that
4209 // these rules are sufficient to prevent recursive encoding of the
4210 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004211 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004212 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004213}
4214
David Chisnallb190a2c2010-06-04 01:10:52 +00004215static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4216 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004217 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004218 case BuiltinType::Void: return 'v';
4219 case BuiltinType::Bool: return 'B';
4220 case BuiltinType::Char_U:
4221 case BuiltinType::UChar: return 'C';
4222 case BuiltinType::UShort: return 'S';
4223 case BuiltinType::UInt: return 'I';
4224 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004225 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004226 case BuiltinType::UInt128: return 'T';
4227 case BuiltinType::ULongLong: return 'Q';
4228 case BuiltinType::Char_S:
4229 case BuiltinType::SChar: return 'c';
4230 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004231 case BuiltinType::WChar_S:
4232 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004233 case BuiltinType::Int: return 'i';
4234 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004235 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004236 case BuiltinType::LongLong: return 'q';
4237 case BuiltinType::Int128: return 't';
4238 case BuiltinType::Float: return 'f';
4239 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004240 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004241 }
4242}
4243
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004244static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4245 EnumDecl *Enum = ET->getDecl();
4246
4247 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4248 if (!Enum->isFixed())
4249 return 'i';
4250
4251 // The encoding of a fixed enum type matches its fixed underlying type.
4252 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4253}
4254
Jay Foad39c79802011-01-12 09:06:06 +00004255static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004256 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004257 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004258 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004259 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4260 // The GNU runtime requires more information; bitfields are encoded as b,
4261 // then the offset (in bits) of the first element, then the type of the
4262 // bitfield, then the size in bits. For example, in this structure:
4263 //
4264 // struct
4265 // {
4266 // int integer;
4267 // int flags:2;
4268 // };
4269 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4270 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4271 // information is not especially sensible, but we're stuck with it for
4272 // compatibility with GCC, although providing it breaks anything that
4273 // actually uses runtime introspection and wants to work on both runtimes...
4274 if (!Ctx->getLangOptions().NeXTRuntime) {
4275 const RecordDecl *RD = FD->getParent();
4276 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004277 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004278 if (const EnumType *ET = T->getAs<EnumType>())
4279 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004280 else
Jay Foad39c79802011-01-12 09:06:06 +00004281 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004282 }
Richard Smithcaf33902011-10-10 18:28:20 +00004283 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004284}
4285
Daniel Dunbar07d07852009-10-18 21:17:35 +00004286// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004287void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4288 bool ExpandPointedToStructures,
4289 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004290 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004291 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004292 bool EncodingProperty,
4293 bool StructField) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004294 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004295 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004296 return EncodeBitField(this, S, T, FD);
4297 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004298 return;
4299 }
Mike Stump11289f42009-09-09 15:08:12 +00004300
John McCall9dd450b2009-09-21 23:43:11 +00004301 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004302 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004303 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004304 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004305 return;
4306 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004307
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004308 // encoding for pointer or r3eference types.
4309 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004310 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004311 if (PT->isObjCSelType()) {
4312 S += ':';
4313 return;
4314 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004315 PointeeTy = PT->getPointeeType();
4316 }
4317 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4318 PointeeTy = RT->getPointeeType();
4319 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004320 bool isReadOnly = false;
4321 // For historical/compatibility reasons, the read-only qualifier of the
4322 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4323 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004324 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004325 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004326 if (OutermostType && T.isConstQualified()) {
4327 isReadOnly = true;
4328 S += 'r';
4329 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004330 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004331 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004332 while (P->getAs<PointerType>())
4333 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004334 if (P.isConstQualified()) {
4335 isReadOnly = true;
4336 S += 'r';
4337 }
4338 }
4339 if (isReadOnly) {
4340 // Another legacy compatibility encoding. Some ObjC qualifier and type
4341 // combinations need to be rearranged.
4342 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004343 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004344 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004345 }
Mike Stump11289f42009-09-09 15:08:12 +00004346
Anders Carlssond8499822007-10-29 05:01:08 +00004347 if (PointeeTy->isCharType()) {
4348 // char pointer types should be encoded as '*' unless it is a
4349 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004350 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004351 S += '*';
4352 return;
4353 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004354 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004355 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4356 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4357 S += '#';
4358 return;
4359 }
4360 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4361 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4362 S += '@';
4363 return;
4364 }
4365 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004366 }
Anders Carlssond8499822007-10-29 05:01:08 +00004367 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004368 getLegacyIntegralTypeEncoding(PointeeTy);
4369
Mike Stump11289f42009-09-09 15:08:12 +00004370 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004371 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004372 return;
4373 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004374
Chris Lattnere7cabb92009-07-13 00:10:46 +00004375 if (const ArrayType *AT =
4376 // Ignore type qualifiers etc.
4377 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004378 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004379 // Incomplete arrays are encoded as a pointer to the array element.
4380 S += '^';
4381
Mike Stump11289f42009-09-09 15:08:12 +00004382 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004383 false, ExpandStructures, FD);
4384 } else {
4385 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004386
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004387 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4388 if (getTypeSize(CAT->getElementType()) == 0)
4389 S += '0';
4390 else
4391 S += llvm::utostr(CAT->getSize().getZExtValue());
4392 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004393 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004394 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4395 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004396 S += '0';
4397 }
Mike Stump11289f42009-09-09 15:08:12 +00004398
4399 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004400 false, ExpandStructures, FD);
4401 S += ']';
4402 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004403 return;
4404 }
Mike Stump11289f42009-09-09 15:08:12 +00004405
John McCall9dd450b2009-09-21 23:43:11 +00004406 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004407 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004408 return;
4409 }
Mike Stump11289f42009-09-09 15:08:12 +00004410
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004411 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004412 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004413 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004414 // Anonymous structures print as '?'
4415 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4416 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004417 if (ClassTemplateSpecializationDecl *Spec
4418 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4419 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4420 std::string TemplateArgsStr
4421 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004422 TemplateArgs.data(),
4423 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004424 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004425
4426 S += TemplateArgsStr;
4427 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004428 } else {
4429 S += '?';
4430 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004431 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004432 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004433 if (!RDecl->isUnion()) {
4434 getObjCEncodingForStructureImpl(RDecl, S, FD);
4435 } else {
4436 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4437 FieldEnd = RDecl->field_end();
4438 Field != FieldEnd; ++Field) {
4439 if (FD) {
4440 S += '"';
4441 S += Field->getNameAsString();
4442 S += '"';
4443 }
Mike Stump11289f42009-09-09 15:08:12 +00004444
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004445 // Special case bit-fields.
4446 if (Field->isBitField()) {
4447 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4448 (*Field));
4449 } else {
4450 QualType qt = Field->getType();
4451 getLegacyIntegralTypeEncoding(qt);
4452 getObjCEncodingForTypeImpl(qt, S, false, true,
4453 FD, /*OutermostType*/false,
4454 /*EncodingProperty*/false,
4455 /*StructField*/true);
4456 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004457 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004458 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004459 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004460 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004461 return;
4462 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004463
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004464 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004465 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004466 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004467 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004468 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004469 return;
4470 }
Mike Stump11289f42009-09-09 15:08:12 +00004471
Chris Lattnere7cabb92009-07-13 00:10:46 +00004472 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004473 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00004474 return;
4475 }
Mike Stump11289f42009-09-09 15:08:12 +00004476
John McCall8b07ec22010-05-15 11:32:37 +00004477 // Ignore protocol qualifiers when mangling at this level.
4478 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4479 T = OT->getBaseType();
4480
John McCall8ccfcb52009-09-24 19:53:00 +00004481 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004482 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004483 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004484 S += '{';
4485 const IdentifierInfo *II = OI->getIdentifier();
4486 S += II->getName();
4487 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004488 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004489 DeepCollectObjCIvars(OI, true, Ivars);
4490 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004491 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004492 if (Field->isBitField())
4493 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004494 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004495 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004496 }
4497 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004498 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004499 }
Mike Stump11289f42009-09-09 15:08:12 +00004500
John McCall9dd450b2009-09-21 23:43:11 +00004501 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004502 if (OPT->isObjCIdType()) {
4503 S += '@';
4504 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004505 }
Mike Stump11289f42009-09-09 15:08:12 +00004506
Steve Narofff0c86112009-10-28 22:03:49 +00004507 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4508 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4509 // Since this is a binary compatibility issue, need to consult with runtime
4510 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004511 S += '#';
4512 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004513 }
Mike Stump11289f42009-09-09 15:08:12 +00004514
Chris Lattnere7cabb92009-07-13 00:10:46 +00004515 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004516 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004517 ExpandPointedToStructures,
4518 ExpandStructures, FD);
4519 if (FD || EncodingProperty) {
4520 // Note that we do extended encoding of protocol qualifer list
4521 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004522 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004523 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4524 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004525 S += '<';
4526 S += (*I)->getNameAsString();
4527 S += '>';
4528 }
4529 S += '"';
4530 }
4531 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004532 }
Mike Stump11289f42009-09-09 15:08:12 +00004533
Chris Lattnere7cabb92009-07-13 00:10:46 +00004534 QualType PointeeTy = OPT->getPointeeType();
4535 if (!EncodingProperty &&
4536 isa<TypedefType>(PointeeTy.getTypePtr())) {
4537 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004538 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004539 // {...};
4540 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004541 getObjCEncodingForTypeImpl(PointeeTy, S,
4542 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004543 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004544 return;
4545 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004546
4547 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00004548 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004549 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004550 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004551 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4552 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004553 S += '<';
4554 S += (*I)->getNameAsString();
4555 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004556 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004557 S += '"';
4558 }
4559 return;
4560 }
Mike Stump11289f42009-09-09 15:08:12 +00004561
John McCalla9e6e8d2010-05-17 23:56:34 +00004562 // gcc just blithely ignores member pointers.
4563 // TODO: maybe there should be a mangling for these
4564 if (T->getAs<MemberPointerType>())
4565 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004566
4567 if (T->isVectorType()) {
4568 // This matches gcc's encoding, even though technically it is
4569 // insufficient.
4570 // FIXME. We should do a better job than gcc.
4571 return;
4572 }
4573
David Blaikie83d382b2011-09-23 05:06:16 +00004574 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004575}
4576
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004577void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4578 std::string &S,
4579 const FieldDecl *FD,
4580 bool includeVBases) const {
4581 assert(RDecl && "Expected non-null RecordDecl");
4582 assert(!RDecl->isUnion() && "Should not be called for unions");
4583 if (!RDecl->getDefinition())
4584 return;
4585
4586 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4587 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4588 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4589
4590 if (CXXRec) {
4591 for (CXXRecordDecl::base_class_iterator
4592 BI = CXXRec->bases_begin(),
4593 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4594 if (!BI->isVirtual()) {
4595 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004596 if (base->isEmpty())
4597 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004598 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4599 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4600 std::make_pair(offs, base));
4601 }
4602 }
4603 }
4604
4605 unsigned i = 0;
4606 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4607 FieldEnd = RDecl->field_end();
4608 Field != FieldEnd; ++Field, ++i) {
4609 uint64_t offs = layout.getFieldOffset(i);
4610 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4611 std::make_pair(offs, *Field));
4612 }
4613
4614 if (CXXRec && includeVBases) {
4615 for (CXXRecordDecl::base_class_iterator
4616 BI = CXXRec->vbases_begin(),
4617 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4618 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004619 if (base->isEmpty())
4620 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004621 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00004622 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4623 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4624 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004625 }
4626 }
4627
4628 CharUnits size;
4629 if (CXXRec) {
4630 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4631 } else {
4632 size = layout.getSize();
4633 }
4634
4635 uint64_t CurOffs = 0;
4636 std::multimap<uint64_t, NamedDecl *>::iterator
4637 CurLayObj = FieldOrBaseOffsets.begin();
4638
Argyrios Kyrtzidisc7e50c52011-08-22 16:03:14 +00004639 if ((CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) ||
4640 (CurLayObj == FieldOrBaseOffsets.end() &&
4641 CXXRec && CXXRec->isDynamicClass())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004642 assert(CXXRec && CXXRec->isDynamicClass() &&
4643 "Offset 0 was empty but no VTable ?");
4644 if (FD) {
4645 S += "\"_vptr$";
4646 std::string recname = CXXRec->getNameAsString();
4647 if (recname.empty()) recname = "?";
4648 S += recname;
4649 S += '"';
4650 }
4651 S += "^^?";
4652 CurOffs += getTypeSize(VoidPtrTy);
4653 }
4654
4655 if (!RDecl->hasFlexibleArrayMember()) {
4656 // Mark the end of the structure.
4657 uint64_t offs = toBits(size);
4658 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4659 std::make_pair(offs, (NamedDecl*)0));
4660 }
4661
4662 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4663 assert(CurOffs <= CurLayObj->first);
4664
4665 if (CurOffs < CurLayObj->first) {
4666 uint64_t padding = CurLayObj->first - CurOffs;
4667 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4668 // packing/alignment of members is different that normal, in which case
4669 // the encoding will be out-of-sync with the real layout.
4670 // If the runtime switches to just consider the size of types without
4671 // taking into account alignment, we could make padding explicit in the
4672 // encoding (e.g. using arrays of chars). The encoding strings would be
4673 // longer then though.
4674 CurOffs += padding;
4675 }
4676
4677 NamedDecl *dcl = CurLayObj->second;
4678 if (dcl == 0)
4679 break; // reached end of structure.
4680
4681 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4682 // We expand the bases without their virtual bases since those are going
4683 // in the initial structure. Note that this differs from gcc which
4684 // expands virtual bases each time one is encountered in the hierarchy,
4685 // making the encoding type bigger than it really is.
4686 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004687 assert(!base->isEmpty());
4688 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004689 } else {
4690 FieldDecl *field = cast<FieldDecl>(dcl);
4691 if (FD) {
4692 S += '"';
4693 S += field->getNameAsString();
4694 S += '"';
4695 }
4696
4697 if (field->isBitField()) {
4698 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00004699 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004700 } else {
4701 QualType qt = field->getType();
4702 getLegacyIntegralTypeEncoding(qt);
4703 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4704 /*OutermostType*/false,
4705 /*EncodingProperty*/false,
4706 /*StructField*/true);
4707 CurOffs += getTypeSize(field->getType());
4708 }
4709 }
4710 }
4711}
4712
Mike Stump11289f42009-09-09 15:08:12 +00004713void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004714 std::string& S) const {
4715 if (QT & Decl::OBJC_TQ_In)
4716 S += 'n';
4717 if (QT & Decl::OBJC_TQ_Inout)
4718 S += 'N';
4719 if (QT & Decl::OBJC_TQ_Out)
4720 S += 'o';
4721 if (QT & Decl::OBJC_TQ_Bycopy)
4722 S += 'O';
4723 if (QT & Decl::OBJC_TQ_Byref)
4724 S += 'R';
4725 if (QT & Decl::OBJC_TQ_Oneway)
4726 S += 'V';
4727}
4728
Chris Lattnere7cabb92009-07-13 00:10:46 +00004729void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004730 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004731
Anders Carlsson87c149b2007-10-11 01:00:40 +00004732 BuiltinVaListType = T;
4733}
4734
Douglas Gregor3ea72692011-08-12 05:46:01 +00004735TypedefDecl *ASTContext::getObjCIdDecl() const {
4736 if (!ObjCIdDecl) {
4737 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4738 T = getObjCObjectPointerType(T);
4739 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4740 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4741 getTranslationUnitDecl(),
4742 SourceLocation(), SourceLocation(),
4743 &Idents.get("id"), IdInfo);
4744 }
4745
4746 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00004747}
4748
Douglas Gregor52e02802011-08-12 06:17:30 +00004749TypedefDecl *ASTContext::getObjCSelDecl() const {
4750 if (!ObjCSelDecl) {
4751 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4752 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4753 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4754 getTranslationUnitDecl(),
4755 SourceLocation(), SourceLocation(),
4756 &Idents.get("SEL"), SelInfo);
4757 }
4758 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004759}
4760
Chris Lattnere7cabb92009-07-13 00:10:46 +00004761void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004762 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004763}
4764
Douglas Gregor0a586182011-08-12 05:59:41 +00004765TypedefDecl *ASTContext::getObjCClassDecl() const {
4766 if (!ObjCClassDecl) {
4767 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4768 T = getObjCObjectPointerType(T);
4769 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4770 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4771 getTranslationUnitDecl(),
4772 SourceLocation(), SourceLocation(),
4773 &Idents.get("Class"), ClassInfo);
4774 }
4775
4776 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004777}
4778
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004779void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004780 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004781 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004782
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004783 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004784}
4785
John McCalld28ae272009-12-02 08:04:21 +00004786/// \brief Retrieve the template name that corresponds to a non-empty
4787/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004788TemplateName
4789ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4790 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004791 unsigned size = End - Begin;
4792 assert(size > 1 && "set is not overloaded!");
4793
4794 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4795 size * sizeof(FunctionTemplateDecl*));
4796 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4797
4798 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004799 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004800 NamedDecl *D = *I;
4801 assert(isa<FunctionTemplateDecl>(D) ||
4802 (isa<UsingShadowDecl>(D) &&
4803 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4804 *Storage++ = D;
4805 }
4806
4807 return TemplateName(OT);
4808}
4809
Douglas Gregordc572a32009-03-30 22:58:21 +00004810/// \brief Retrieve the template name that represents a qualified
4811/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004812TemplateName
4813ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4814 bool TemplateKeyword,
4815 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00004816 assert(NNS && "Missing nested-name-specifier in qualified template name");
4817
Douglas Gregorc42075a2010-02-04 18:10:26 +00004818 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004819 llvm::FoldingSetNodeID ID;
4820 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4821
4822 void *InsertPos = 0;
4823 QualifiedTemplateName *QTN =
4824 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4825 if (!QTN) {
4826 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4827 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4828 }
4829
4830 return TemplateName(QTN);
4831}
4832
4833/// \brief Retrieve the template name that represents a dependent
4834/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004835TemplateName
4836ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4837 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004838 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004839 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004840
4841 llvm::FoldingSetNodeID ID;
4842 DependentTemplateName::Profile(ID, NNS, Name);
4843
4844 void *InsertPos = 0;
4845 DependentTemplateName *QTN =
4846 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4847
4848 if (QTN)
4849 return TemplateName(QTN);
4850
4851 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4852 if (CanonNNS == NNS) {
4853 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4854 } else {
4855 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4856 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004857 DependentTemplateName *CheckQTN =
4858 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4859 assert(!CheckQTN && "Dependent type name canonicalization broken");
4860 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004861 }
4862
4863 DependentTemplateNames.InsertNode(QTN, InsertPos);
4864 return TemplateName(QTN);
4865}
4866
Douglas Gregor71395fa2009-11-04 00:56:37 +00004867/// \brief Retrieve the template name that represents a dependent
4868/// template name such as \c MetaFun::template operator+.
4869TemplateName
4870ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00004871 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00004872 assert((!NNS || NNS->isDependent()) &&
4873 "Nested name specifier must be dependent");
4874
4875 llvm::FoldingSetNodeID ID;
4876 DependentTemplateName::Profile(ID, NNS, Operator);
4877
4878 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004879 DependentTemplateName *QTN
4880 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004881
4882 if (QTN)
4883 return TemplateName(QTN);
4884
4885 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4886 if (CanonNNS == NNS) {
4887 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4888 } else {
4889 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4890 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004891
4892 DependentTemplateName *CheckQTN
4893 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4894 assert(!CheckQTN && "Dependent template name canonicalization broken");
4895 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004896 }
4897
4898 DependentTemplateNames.InsertNode(QTN, InsertPos);
4899 return TemplateName(QTN);
4900}
4901
Douglas Gregor5590be02011-01-15 06:45:20 +00004902TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00004903ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
4904 TemplateName replacement) const {
4905 llvm::FoldingSetNodeID ID;
4906 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
4907
4908 void *insertPos = 0;
4909 SubstTemplateTemplateParmStorage *subst
4910 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
4911
4912 if (!subst) {
4913 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
4914 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
4915 }
4916
4917 return TemplateName(subst);
4918}
4919
4920TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00004921ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4922 const TemplateArgument &ArgPack) const {
4923 ASTContext &Self = const_cast<ASTContext &>(*this);
4924 llvm::FoldingSetNodeID ID;
4925 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4926
4927 void *InsertPos = 0;
4928 SubstTemplateTemplateParmPackStorage *Subst
4929 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4930
4931 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00004932 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00004933 ArgPack.pack_size(),
4934 ArgPack.pack_begin());
4935 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4936 }
4937
4938 return TemplateName(Subst);
4939}
4940
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004941/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004942/// TargetInfo, produce the corresponding type. The unsigned @p Type
4943/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004944CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004945 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004946 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004947 case TargetInfo::SignedShort: return ShortTy;
4948 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4949 case TargetInfo::SignedInt: return IntTy;
4950 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4951 case TargetInfo::SignedLong: return LongTy;
4952 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4953 case TargetInfo::SignedLongLong: return LongLongTy;
4954 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4955 }
4956
David Blaikie83d382b2011-09-23 05:06:16 +00004957 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004958}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004959
4960//===----------------------------------------------------------------------===//
4961// Type Predicates.
4962//===----------------------------------------------------------------------===//
4963
Fariborz Jahanian96207692009-02-18 21:49:28 +00004964/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4965/// garbage collection attribute.
4966///
John McCall553d45a2011-01-12 00:34:59 +00004967Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
Douglas Gregor79a91412011-09-13 17:21:33 +00004968 if (getLangOptions().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00004969 return Qualifiers::GCNone;
4970
4971 assert(getLangOptions().ObjC1);
4972 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4973
4974 // Default behaviour under objective-C's gc is for ObjC pointers
4975 // (or pointers to them) be treated as though they were declared
4976 // as __strong.
4977 if (GCAttrs == Qualifiers::GCNone) {
4978 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4979 return Qualifiers::Strong;
4980 else if (Ty->isPointerType())
4981 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4982 } else {
4983 // It's not valid to set GC attributes on anything that isn't a
4984 // pointer.
4985#ifndef NDEBUG
4986 QualType CT = Ty->getCanonicalTypeInternal();
4987 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4988 CT = AT->getElementType();
4989 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4990#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00004991 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004992 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004993}
4994
Chris Lattner49af6a42008-04-07 06:51:04 +00004995//===----------------------------------------------------------------------===//
4996// Type Compatibility Testing
4997//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004998
Mike Stump11289f42009-09-09 15:08:12 +00004999/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005000/// compatible.
5001static bool areCompatVectorTypes(const VectorType *LHS,
5002 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005003 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005004 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005005 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005006}
5007
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005008bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5009 QualType SecondVec) {
5010 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5011 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5012
5013 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5014 return true;
5015
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005016 // Treat Neon vector types and most AltiVec vector types as if they are the
5017 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005018 const VectorType *First = FirstVec->getAs<VectorType>();
5019 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005020 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005021 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005022 First->getVectorKind() != VectorType::AltiVecPixel &&
5023 First->getVectorKind() != VectorType::AltiVecBool &&
5024 Second->getVectorKind() != VectorType::AltiVecPixel &&
5025 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005026 return true;
5027
5028 return false;
5029}
5030
Steve Naroff8e6aee52009-07-23 01:01:38 +00005031//===----------------------------------------------------------------------===//
5032// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5033//===----------------------------------------------------------------------===//
5034
5035/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5036/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005037bool
5038ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5039 ObjCProtocolDecl *rProto) const {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005040 if (lProto == rProto)
5041 return true;
5042 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5043 E = rProto->protocol_end(); PI != E; ++PI)
5044 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5045 return true;
5046 return false;
5047}
5048
Steve Naroff8e6aee52009-07-23 01:01:38 +00005049/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5050/// return true if lhs's protocols conform to rhs's protocol; false
5051/// otherwise.
5052bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5053 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5054 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5055 return false;
5056}
5057
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005058/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5059/// Class<p1, ...>.
5060bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5061 QualType rhs) {
5062 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5063 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5064 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5065
5066 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5067 E = lhsQID->qual_end(); I != E; ++I) {
5068 bool match = false;
5069 ObjCProtocolDecl *lhsProto = *I;
5070 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5071 E = rhsOPT->qual_end(); J != E; ++J) {
5072 ObjCProtocolDecl *rhsProto = *J;
5073 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5074 match = true;
5075 break;
5076 }
5077 }
5078 if (!match)
5079 return false;
5080 }
5081 return true;
5082}
5083
Steve Naroff8e6aee52009-07-23 01:01:38 +00005084/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5085/// ObjCQualifiedIDType.
5086bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5087 bool compare) {
5088 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005089 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005090 lhs->isObjCIdType() || lhs->isObjCClassType())
5091 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005092 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005093 rhs->isObjCIdType() || rhs->isObjCClassType())
5094 return true;
5095
5096 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005097 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005098
Steve Naroff8e6aee52009-07-23 01:01:38 +00005099 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005100
Steve Naroff8e6aee52009-07-23 01:01:38 +00005101 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005102 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005103 // make sure we check the class hierarchy.
5104 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5105 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5106 E = lhsQID->qual_end(); I != E; ++I) {
5107 // when comparing an id<P> on lhs with a static type on rhs,
5108 // see if static class implements all of id's protocols, directly or
5109 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005110 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005111 return false;
5112 }
5113 }
5114 // If there are no qualifiers and no interface, we have an 'id'.
5115 return true;
5116 }
Mike Stump11289f42009-09-09 15:08:12 +00005117 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005118 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5119 E = lhsQID->qual_end(); I != E; ++I) {
5120 ObjCProtocolDecl *lhsProto = *I;
5121 bool match = false;
5122
5123 // when comparing an id<P> on lhs with a static type on rhs,
5124 // see if static class implements all of id's protocols, directly or
5125 // through its super class and categories.
5126 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5127 E = rhsOPT->qual_end(); J != E; ++J) {
5128 ObjCProtocolDecl *rhsProto = *J;
5129 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5130 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5131 match = true;
5132 break;
5133 }
5134 }
Mike Stump11289f42009-09-09 15:08:12 +00005135 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005136 // make sure we check the class hierarchy.
5137 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5138 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5139 E = lhsQID->qual_end(); I != E; ++I) {
5140 // when comparing an id<P> on lhs with a static type on rhs,
5141 // see if static class implements all of id's protocols, directly or
5142 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005143 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005144 match = true;
5145 break;
5146 }
5147 }
5148 }
5149 if (!match)
5150 return false;
5151 }
Mike Stump11289f42009-09-09 15:08:12 +00005152
Steve Naroff8e6aee52009-07-23 01:01:38 +00005153 return true;
5154 }
Mike Stump11289f42009-09-09 15:08:12 +00005155
Steve Naroff8e6aee52009-07-23 01:01:38 +00005156 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5157 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5158
Mike Stump11289f42009-09-09 15:08:12 +00005159 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005160 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005161 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005162 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5163 E = lhsOPT->qual_end(); I != E; ++I) {
5164 ObjCProtocolDecl *lhsProto = *I;
5165 bool match = false;
5166
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005167 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005168 // see if static class implements all of id's protocols, directly or
5169 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005170 // First, lhs protocols in the qualifier list must be found, direct
5171 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005172 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5173 E = rhsQID->qual_end(); J != E; ++J) {
5174 ObjCProtocolDecl *rhsProto = *J;
5175 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5176 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5177 match = true;
5178 break;
5179 }
5180 }
5181 if (!match)
5182 return false;
5183 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005184
5185 // Static class's protocols, or its super class or category protocols
5186 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5187 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5188 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5189 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5190 // This is rather dubious but matches gcc's behavior. If lhs has
5191 // no type qualifier and its class has no static protocol(s)
5192 // assume that it is mismatch.
5193 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5194 return false;
5195 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5196 LHSInheritedProtocols.begin(),
5197 E = LHSInheritedProtocols.end(); I != E; ++I) {
5198 bool match = false;
5199 ObjCProtocolDecl *lhsProto = (*I);
5200 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5201 E = rhsQID->qual_end(); J != E; ++J) {
5202 ObjCProtocolDecl *rhsProto = *J;
5203 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5204 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5205 match = true;
5206 break;
5207 }
5208 }
5209 if (!match)
5210 return false;
5211 }
5212 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005213 return true;
5214 }
5215 return false;
5216}
5217
Eli Friedman47f77112008-08-22 00:56:42 +00005218/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005219/// compatible for assignment from RHS to LHS. This handles validation of any
5220/// protocol qualifiers on the LHS or RHS.
5221///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005222bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5223 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005224 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5225 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5226
Steve Naroff1329fa02009-07-15 18:40:39 +00005227 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005228 if (LHS->isObjCUnqualifiedIdOrClass() ||
5229 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005230 return true;
5231
John McCall8b07ec22010-05-15 11:32:37 +00005232 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005233 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5234 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005235 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005236
5237 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5238 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5239 QualType(RHSOPT,0));
5240
John McCall8b07ec22010-05-15 11:32:37 +00005241 // If we have 2 user-defined types, fall into that path.
5242 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005243 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005244
Steve Naroff8e6aee52009-07-23 01:01:38 +00005245 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005246}
5247
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005248/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005249/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005250/// arguments in block literals. When passed as arguments, passing 'A*' where
5251/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5252/// not OK. For the return type, the opposite is not OK.
5253bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5254 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005255 const ObjCObjectPointerType *RHSOPT,
5256 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005257 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005258 return true;
5259
5260 if (LHSOPT->isObjCBuiltinType()) {
5261 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5262 }
5263
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005264 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005265 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5266 QualType(RHSOPT,0),
5267 false);
5268
5269 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5270 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5271 if (LHS && RHS) { // We have 2 user-defined types.
5272 if (LHS != RHS) {
5273 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005274 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005275 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005276 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005277 }
5278 else
5279 return true;
5280 }
5281 return false;
5282}
5283
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005284/// getIntersectionOfProtocols - This routine finds the intersection of set
5285/// of protocols inherited from two distinct objective-c pointer objects.
5286/// It is used to build composite qualifier list of the composite type of
5287/// the conditional expression involving two objective-c pointer objects.
5288static
5289void getIntersectionOfProtocols(ASTContext &Context,
5290 const ObjCObjectPointerType *LHSOPT,
5291 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005292 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005293
John McCall8b07ec22010-05-15 11:32:37 +00005294 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5295 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5296 assert(LHS->getInterface() && "LHS must have an interface base");
5297 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005298
5299 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5300 unsigned LHSNumProtocols = LHS->getNumProtocols();
5301 if (LHSNumProtocols > 0)
5302 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5303 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005304 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005305 Context.CollectInheritedProtocols(LHS->getInterface(),
5306 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005307 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5308 LHSInheritedProtocols.end());
5309 }
5310
5311 unsigned RHSNumProtocols = RHS->getNumProtocols();
5312 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005313 ObjCProtocolDecl **RHSProtocols =
5314 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005315 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5316 if (InheritedProtocolSet.count(RHSProtocols[i]))
5317 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00005318 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005319 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005320 Context.CollectInheritedProtocols(RHS->getInterface(),
5321 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005322 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5323 RHSInheritedProtocols.begin(),
5324 E = RHSInheritedProtocols.end(); I != E; ++I)
5325 if (InheritedProtocolSet.count((*I)))
5326 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005327 }
5328}
5329
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005330/// areCommonBaseCompatible - Returns common base class of the two classes if
5331/// one found. Note that this is O'2 algorithm. But it will be called as the
5332/// last type comparison in a ?-exp of ObjC pointer types before a
5333/// warning is issued. So, its invokation is extremely rare.
5334QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005335 const ObjCObjectPointerType *Lptr,
5336 const ObjCObjectPointerType *Rptr) {
5337 const ObjCObjectType *LHS = Lptr->getObjectType();
5338 const ObjCObjectType *RHS = Rptr->getObjectType();
5339 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5340 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005341 if (!LDecl || !RDecl || (LDecl == RDecl))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005342 return QualType();
5343
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005344 do {
John McCall8b07ec22010-05-15 11:32:37 +00005345 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005346 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005347 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00005348 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5349
5350 QualType Result = QualType(LHS, 0);
5351 if (!Protocols.empty())
5352 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5353 Result = getObjCObjectPointerType(Result);
5354 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005355 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005356 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005357
5358 return QualType();
5359}
5360
John McCall8b07ec22010-05-15 11:32:37 +00005361bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5362 const ObjCObjectType *RHS) {
5363 assert(LHS->getInterface() && "LHS is not an interface type");
5364 assert(RHS->getInterface() && "RHS is not an interface type");
5365
Chris Lattner49af6a42008-04-07 06:51:04 +00005366 // Verify that the base decls are compatible: the RHS must be a subclass of
5367 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005368 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005369 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005370
Chris Lattner49af6a42008-04-07 06:51:04 +00005371 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5372 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005373 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005374 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005375
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005376 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5377 // more detailed analysis is required.
5378 if (RHS->getNumProtocols() == 0) {
5379 // OK, if LHS is a superclass of RHS *and*
5380 // this superclass is assignment compatible with LHS.
5381 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005382 bool IsSuperClass =
5383 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5384 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005385 // OK if conversion of LHS to SuperClass results in narrowing of types
5386 // ; i.e., SuperClass may implement at least one of the protocols
5387 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5388 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5389 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005390 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005391 // If super class has no protocols, it is not a match.
5392 if (SuperClassInheritedProtocols.empty())
5393 return false;
5394
5395 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5396 LHSPE = LHS->qual_end();
5397 LHSPI != LHSPE; LHSPI++) {
5398 bool SuperImplementsProtocol = false;
5399 ObjCProtocolDecl *LHSProto = (*LHSPI);
5400
5401 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5402 SuperClassInheritedProtocols.begin(),
5403 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5404 ObjCProtocolDecl *SuperClassProto = (*I);
5405 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5406 SuperImplementsProtocol = true;
5407 break;
5408 }
5409 }
5410 if (!SuperImplementsProtocol)
5411 return false;
5412 }
5413 return true;
5414 }
5415 return false;
5416 }
Mike Stump11289f42009-09-09 15:08:12 +00005417
John McCall8b07ec22010-05-15 11:32:37 +00005418 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5419 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005420 LHSPI != LHSPE; LHSPI++) {
5421 bool RHSImplementsProtocol = false;
5422
5423 // If the RHS doesn't implement the protocol on the left, the types
5424 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005425 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5426 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005427 RHSPI != RHSPE; RHSPI++) {
5428 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005429 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005430 break;
5431 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005432 }
5433 // FIXME: For better diagnostics, consider passing back the protocol name.
5434 if (!RHSImplementsProtocol)
5435 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005436 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005437 // The RHS implements all protocols listed on the LHS.
5438 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005439}
5440
Steve Naroffb7605152009-02-12 17:52:19 +00005441bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5442 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005443 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5444 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005445
Steve Naroff7cae42b2009-07-10 23:34:53 +00005446 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005447 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005448
5449 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5450 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005451}
5452
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005453bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5454 return canAssignObjCInterfaces(
5455 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5456 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5457}
5458
Mike Stump11289f42009-09-09 15:08:12 +00005459/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005460/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005461/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005462/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005463bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5464 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00005465 if (getLangOptions().CPlusPlus)
5466 return hasSameType(LHS, RHS);
5467
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005468 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005469}
5470
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005471bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00005472 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005473}
5474
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005475bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5476 return !mergeTypes(LHS, RHS, true).isNull();
5477}
5478
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005479/// mergeTransparentUnionType - if T is a transparent union type and a member
5480/// of T is compatible with SubType, return the merged type, else return
5481/// QualType()
5482QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5483 bool OfBlockPointer,
5484 bool Unqualified) {
5485 if (const RecordType *UT = T->getAsUnionType()) {
5486 RecordDecl *UD = UT->getDecl();
5487 if (UD->hasAttr<TransparentUnionAttr>()) {
5488 for (RecordDecl::field_iterator it = UD->field_begin(),
5489 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005490 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005491 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5492 if (!MT.isNull())
5493 return MT;
5494 }
5495 }
5496 }
5497
5498 return QualType();
5499}
5500
5501/// mergeFunctionArgumentTypes - merge two types which appear as function
5502/// argument types
5503QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5504 bool OfBlockPointer,
5505 bool Unqualified) {
5506 // GNU extension: two types are compatible if they appear as a function
5507 // argument, one of the types is a transparent union type and the other
5508 // type is compatible with a union member
5509 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5510 Unqualified);
5511 if (!lmerge.isNull())
5512 return lmerge;
5513
5514 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5515 Unqualified);
5516 if (!rmerge.isNull())
5517 return rmerge;
5518
5519 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5520}
5521
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005522QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005523 bool OfBlockPointer,
5524 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005525 const FunctionType *lbase = lhs->getAs<FunctionType>();
5526 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005527 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5528 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005529 bool allLTypes = true;
5530 bool allRTypes = true;
5531
5532 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005533 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00005534 if (OfBlockPointer) {
5535 QualType RHS = rbase->getResultType();
5536 QualType LHS = lbase->getResultType();
5537 bool UnqualifiedResult = Unqualified;
5538 if (!UnqualifiedResult)
5539 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005540 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00005541 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005542 else
John McCall8c6b56f2010-12-15 01:06:38 +00005543 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5544 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005545 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005546
5547 if (Unqualified)
5548 retType = retType.getUnqualifiedType();
5549
5550 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5551 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5552 if (Unqualified) {
5553 LRetType = LRetType.getUnqualifiedType();
5554 RRetType = RRetType.getUnqualifiedType();
5555 }
5556
5557 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005558 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005559 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005560 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005561
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005562 // FIXME: double check this
5563 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5564 // rbase->getRegParmAttr() != 0 &&
5565 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005566 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5567 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005568
Douglas Gregor8c940862010-01-18 17:14:39 +00005569 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005570 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005571 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005572
John McCall8c6b56f2010-12-15 01:06:38 +00005573 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00005574 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5575 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00005576 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5577 return QualType();
5578
John McCall31168b02011-06-15 23:02:42 +00005579 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5580 return QualType();
5581
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005582 // functypes which return are preferred over those that do not.
5583 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5584 allLTypes = false;
5585 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5586 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005587 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5588 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00005589
John McCall31168b02011-06-15 23:02:42 +00005590 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00005591
Eli Friedman47f77112008-08-22 00:56:42 +00005592 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005593 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5594 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005595 unsigned lproto_nargs = lproto->getNumArgs();
5596 unsigned rproto_nargs = rproto->getNumArgs();
5597
5598 // Compatible functions must have the same number of arguments
5599 if (lproto_nargs != rproto_nargs)
5600 return QualType();
5601
5602 // Variadic and non-variadic functions aren't compatible
5603 if (lproto->isVariadic() != rproto->isVariadic())
5604 return QualType();
5605
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005606 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5607 return QualType();
5608
Fariborz Jahanian97676972011-09-28 21:52:05 +00005609 if (LangOpts.ObjCAutoRefCount &&
5610 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5611 return QualType();
5612
Eli Friedman47f77112008-08-22 00:56:42 +00005613 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005614 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00005615 for (unsigned i = 0; i < lproto_nargs; i++) {
5616 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5617 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005618 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5619 OfBlockPointer,
5620 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005621 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005622
5623 if (Unqualified)
5624 argtype = argtype.getUnqualifiedType();
5625
Eli Friedman47f77112008-08-22 00:56:42 +00005626 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005627 if (Unqualified) {
5628 largtype = largtype.getUnqualifiedType();
5629 rargtype = rargtype.getUnqualifiedType();
5630 }
5631
Chris Lattner465fa322008-10-05 17:34:18 +00005632 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5633 allLTypes = false;
5634 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5635 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005636 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00005637
Eli Friedman47f77112008-08-22 00:56:42 +00005638 if (allLTypes) return lhs;
5639 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005640
5641 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5642 EPI.ExtInfo = einfo;
5643 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005644 }
5645
5646 if (lproto) allRTypes = false;
5647 if (rproto) allLTypes = false;
5648
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005649 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005650 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005651 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005652 if (proto->isVariadic()) return QualType();
5653 // Check that the types are compatible with the types that
5654 // would result from default argument promotions (C99 6.7.5.3p15).
5655 // The only types actually affected are promotable integer
5656 // types and floats, which would be passed as a different
5657 // type depending on whether the prototype is visible.
5658 unsigned proto_nargs = proto->getNumArgs();
5659 for (unsigned i = 0; i < proto_nargs; ++i) {
5660 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005661
5662 // Look at the promotion type of enum types, since that is the type used
5663 // to pass enum values.
5664 if (const EnumType *Enum = argTy->getAs<EnumType>())
5665 argTy = Enum->getDecl()->getPromotionType();
5666
Eli Friedman47f77112008-08-22 00:56:42 +00005667 if (argTy->isPromotableIntegerType() ||
5668 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5669 return QualType();
5670 }
5671
5672 if (allLTypes) return lhs;
5673 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005674
5675 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5676 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005677 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005678 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005679 }
5680
5681 if (allLTypes) return lhs;
5682 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005683 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005684}
5685
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005686QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005687 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005688 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005689 // C++ [expr]: If an expression initially has the type "reference to T", the
5690 // type is adjusted to "T" prior to any further analysis, the expression
5691 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005692 // expression is an lvalue unless the reference is an rvalue reference and
5693 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005694 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5695 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005696
5697 if (Unqualified) {
5698 LHS = LHS.getUnqualifiedType();
5699 RHS = RHS.getUnqualifiedType();
5700 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005701
Eli Friedman47f77112008-08-22 00:56:42 +00005702 QualType LHSCan = getCanonicalType(LHS),
5703 RHSCan = getCanonicalType(RHS);
5704
5705 // If two types are identical, they are compatible.
5706 if (LHSCan == RHSCan)
5707 return LHS;
5708
John McCall8ccfcb52009-09-24 19:53:00 +00005709 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005710 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5711 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005712 if (LQuals != RQuals) {
5713 // If any of these qualifiers are different, we have a type
5714 // mismatch.
5715 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00005716 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5717 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00005718 return QualType();
5719
5720 // Exactly one GC qualifier difference is allowed: __strong is
5721 // okay if the other type has no GC qualifier but is an Objective
5722 // C object pointer (i.e. implicitly strong by default). We fix
5723 // this by pretending that the unqualified type was actually
5724 // qualified __strong.
5725 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5726 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5727 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5728
5729 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5730 return QualType();
5731
5732 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5733 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5734 }
5735 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5736 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5737 }
Eli Friedman47f77112008-08-22 00:56:42 +00005738 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005739 }
5740
5741 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005742
Eli Friedmandcca6332009-06-01 01:22:52 +00005743 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5744 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005745
Chris Lattnerfd652912008-01-14 05:45:46 +00005746 // We want to consider the two function types to be the same for these
5747 // comparisons, just force one to the other.
5748 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5749 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005750
5751 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005752 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5753 LHSClass = Type::ConstantArray;
5754 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5755 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005756
John McCall8b07ec22010-05-15 11:32:37 +00005757 // ObjCInterfaces are just specialized ObjCObjects.
5758 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5759 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5760
Nate Begemance4d7fc2008-04-18 23:10:10 +00005761 // Canonicalize ExtVector -> Vector.
5762 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5763 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005764
Chris Lattner95554662008-04-07 05:43:21 +00005765 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005766 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005767 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005768 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005769 // Compatibility is based on the underlying type, not the promotion
5770 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005771 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005772 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5773 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005774 }
John McCall9dd450b2009-09-21 23:43:11 +00005775 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005776 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5777 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005778 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005779
Eli Friedman47f77112008-08-22 00:56:42 +00005780 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005781 }
Eli Friedman47f77112008-08-22 00:56:42 +00005782
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005783 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005784 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005785#define TYPE(Class, Base)
5786#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005787#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005788#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5789#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5790#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00005791 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005792
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005793 case Type::LValueReference:
5794 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005795 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00005796 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005797
John McCall8b07ec22010-05-15 11:32:37 +00005798 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005799 case Type::IncompleteArray:
5800 case Type::VariableArray:
5801 case Type::FunctionProto:
5802 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00005803 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005804
Chris Lattnerfd652912008-01-14 05:45:46 +00005805 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005806 {
5807 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005808 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5809 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005810 if (Unqualified) {
5811 LHSPointee = LHSPointee.getUnqualifiedType();
5812 RHSPointee = RHSPointee.getUnqualifiedType();
5813 }
5814 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5815 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005816 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005817 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005818 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005819 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005820 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005821 return getPointerType(ResultType);
5822 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005823 case Type::BlockPointer:
5824 {
5825 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005826 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5827 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005828 if (Unqualified) {
5829 LHSPointee = LHSPointee.getUnqualifiedType();
5830 RHSPointee = RHSPointee.getUnqualifiedType();
5831 }
5832 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5833 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005834 if (ResultType.isNull()) return QualType();
5835 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5836 return LHS;
5837 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5838 return RHS;
5839 return getBlockPointerType(ResultType);
5840 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00005841 case Type::Atomic:
5842 {
5843 // Merge two pointer types, while trying to preserve typedef info
5844 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
5845 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
5846 if (Unqualified) {
5847 LHSValue = LHSValue.getUnqualifiedType();
5848 RHSValue = RHSValue.getUnqualifiedType();
5849 }
5850 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
5851 Unqualified);
5852 if (ResultType.isNull()) return QualType();
5853 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
5854 return LHS;
5855 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
5856 return RHS;
5857 return getAtomicType(ResultType);
5858 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005859 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00005860 {
5861 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5862 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5863 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5864 return QualType();
5865
5866 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5867 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005868 if (Unqualified) {
5869 LHSElem = LHSElem.getUnqualifiedType();
5870 RHSElem = RHSElem.getUnqualifiedType();
5871 }
5872
5873 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005874 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00005875 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5876 return LHS;
5877 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5878 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00005879 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5880 ArrayType::ArraySizeModifier(), 0);
5881 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5882 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005883 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5884 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00005885 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5886 return LHS;
5887 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5888 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005889 if (LVAT) {
5890 // FIXME: This isn't correct! But tricky to implement because
5891 // the array's size has to be the size of LHS, but the type
5892 // has to be different.
5893 return LHS;
5894 }
5895 if (RVAT) {
5896 // FIXME: This isn't correct! But tricky to implement because
5897 // the array's size has to be the size of RHS, but the type
5898 // has to be different.
5899 return RHS;
5900 }
Eli Friedman3e62c212008-08-22 01:48:21 +00005901 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5902 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00005903 return getIncompleteArrayType(ResultType,
5904 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005905 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005906 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005907 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005908 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005909 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00005910 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00005911 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005912 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00005913 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00005914 case Type::Complex:
5915 // Distinct complex types are incompatible.
5916 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005917 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00005918 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00005919 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5920 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00005921 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00005922 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00005923 case Type::ObjCObject: {
5924 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00005925 // FIXME: This should be type compatibility, e.g. whether
5926 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00005927 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5928 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5929 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00005930 return LHS;
5931
Eli Friedman47f77112008-08-22 00:56:42 +00005932 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00005933 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005934 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005935 if (OfBlockPointer) {
5936 if (canAssignObjCInterfacesInBlockPointer(
5937 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005938 RHS->getAs<ObjCObjectPointerType>(),
5939 BlockReturnType))
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005940 return LHS;
5941 return QualType();
5942 }
John McCall9dd450b2009-09-21 23:43:11 +00005943 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5944 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005945 return LHS;
5946
Steve Naroffc68cfcf2008-12-10 22:14:21 +00005947 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005948 }
Steve Naroff32e44c02007-10-15 20:41:53 +00005949 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005950
5951 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005952}
Ted Kremenekfc581a92007-10-31 17:10:13 +00005953
Fariborz Jahanian97676972011-09-28 21:52:05 +00005954bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
5955 const FunctionProtoType *FromFunctionType,
5956 const FunctionProtoType *ToFunctionType) {
5957 if (FromFunctionType->hasAnyConsumedArgs() !=
5958 ToFunctionType->hasAnyConsumedArgs())
5959 return false;
5960 FunctionProtoType::ExtProtoInfo FromEPI =
5961 FromFunctionType->getExtProtoInfo();
5962 FunctionProtoType::ExtProtoInfo ToEPI =
5963 ToFunctionType->getExtProtoInfo();
5964 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
5965 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
5966 ArgIdx != NumArgs; ++ArgIdx) {
5967 if (FromEPI.ConsumedArguments[ArgIdx] !=
5968 ToEPI.ConsumedArguments[ArgIdx])
5969 return false;
5970 }
5971 return true;
5972}
5973
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005974/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5975/// 'RHS' attributes and returns the merged version; including for function
5976/// return types.
5977QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5978 QualType LHSCan = getCanonicalType(LHS),
5979 RHSCan = getCanonicalType(RHS);
5980 // If two types are identical, they are compatible.
5981 if (LHSCan == RHSCan)
5982 return LHS;
5983 if (RHSCan->isFunctionType()) {
5984 if (!LHSCan->isFunctionType())
5985 return QualType();
5986 QualType OldReturnType =
5987 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5988 QualType NewReturnType =
5989 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5990 QualType ResReturnType =
5991 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5992 if (ResReturnType.isNull())
5993 return QualType();
5994 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5995 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5996 // In either case, use OldReturnType to build the new function type.
5997 const FunctionType *F = LHS->getAs<FunctionType>();
5998 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00005999 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6000 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006001 QualType ResultType
6002 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006003 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006004 return ResultType;
6005 }
6006 }
6007 return QualType();
6008 }
6009
6010 // If the qualifiers are different, the types can still be merged.
6011 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6012 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6013 if (LQuals != RQuals) {
6014 // If any of these qualifiers are different, we have a type mismatch.
6015 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6016 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6017 return QualType();
6018
6019 // Exactly one GC qualifier difference is allowed: __strong is
6020 // okay if the other type has no GC qualifier but is an Objective
6021 // C object pointer (i.e. implicitly strong by default). We fix
6022 // this by pretending that the unqualified type was actually
6023 // qualified __strong.
6024 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6025 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6026 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6027
6028 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6029 return QualType();
6030
6031 if (GC_L == Qualifiers::Strong)
6032 return LHS;
6033 if (GC_R == Qualifiers::Strong)
6034 return RHS;
6035 return QualType();
6036 }
6037
6038 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6039 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6040 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6041 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6042 if (ResQT == LHSBaseQT)
6043 return LHS;
6044 if (ResQT == RHSBaseQT)
6045 return RHS;
6046 }
6047 return QualType();
6048}
6049
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006050//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006051// Integer Predicates
6052//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006053
Jay Foad39c79802011-01-12 09:06:06 +00006054unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006055 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006056 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006057 if (T->isBooleanType())
6058 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006059 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006060 return (unsigned)getTypeSize(T);
6061}
6062
6063QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006064 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006065
6066 // Turn <4 x signed int> -> <4 x unsigned int>
6067 if (const VectorType *VTy = T->getAs<VectorType>())
6068 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006069 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006070
6071 // For enums, we return the unsigned version of the base type.
6072 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006073 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006074
6075 const BuiltinType *BTy = T->getAs<BuiltinType>();
6076 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006077 switch (BTy->getKind()) {
6078 case BuiltinType::Char_S:
6079 case BuiltinType::SChar:
6080 return UnsignedCharTy;
6081 case BuiltinType::Short:
6082 return UnsignedShortTy;
6083 case BuiltinType::Int:
6084 return UnsignedIntTy;
6085 case BuiltinType::Long:
6086 return UnsignedLongTy;
6087 case BuiltinType::LongLong:
6088 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006089 case BuiltinType::Int128:
6090 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006091 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006092 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006093 }
6094}
6095
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006096ASTMutationListener::~ASTMutationListener() { }
6097
Chris Lattnerecd79c62009-06-14 00:45:47 +00006098
6099//===----------------------------------------------------------------------===//
6100// Builtin Type Computation
6101//===----------------------------------------------------------------------===//
6102
6103/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006104/// pointer over the consumed characters. This returns the resultant type. If
6105/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6106/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6107/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006108///
6109/// RequiresICE is filled in on return to indicate whether the value is required
6110/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006111static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006112 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006113 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006114 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006115 // Modifiers.
6116 int HowLong = 0;
6117 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006118 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006119
Chris Lattnerdc226c22010-10-01 22:42:38 +00006120 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006121 bool Done = false;
6122 while (!Done) {
6123 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006124 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006125 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006126 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006127 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006128 case 'S':
6129 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6130 assert(!Signed && "Can't use 'S' modifier multiple times!");
6131 Signed = true;
6132 break;
6133 case 'U':
6134 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6135 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6136 Unsigned = true;
6137 break;
6138 case 'L':
6139 assert(HowLong <= 2 && "Can't have LLLL modifier");
6140 ++HowLong;
6141 break;
6142 }
6143 }
6144
6145 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006146
Chris Lattnerecd79c62009-06-14 00:45:47 +00006147 // Read the base type.
6148 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006149 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006150 case 'v':
6151 assert(HowLong == 0 && !Signed && !Unsigned &&
6152 "Bad modifiers used with 'v'!");
6153 Type = Context.VoidTy;
6154 break;
6155 case 'f':
6156 assert(HowLong == 0 && !Signed && !Unsigned &&
6157 "Bad modifiers used with 'f'!");
6158 Type = Context.FloatTy;
6159 break;
6160 case 'd':
6161 assert(HowLong < 2 && !Signed && !Unsigned &&
6162 "Bad modifiers used with 'd'!");
6163 if (HowLong)
6164 Type = Context.LongDoubleTy;
6165 else
6166 Type = Context.DoubleTy;
6167 break;
6168 case 's':
6169 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6170 if (Unsigned)
6171 Type = Context.UnsignedShortTy;
6172 else
6173 Type = Context.ShortTy;
6174 break;
6175 case 'i':
6176 if (HowLong == 3)
6177 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6178 else if (HowLong == 2)
6179 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6180 else if (HowLong == 1)
6181 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6182 else
6183 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6184 break;
6185 case 'c':
6186 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6187 if (Signed)
6188 Type = Context.SignedCharTy;
6189 else if (Unsigned)
6190 Type = Context.UnsignedCharTy;
6191 else
6192 Type = Context.CharTy;
6193 break;
6194 case 'b': // boolean
6195 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6196 Type = Context.BoolTy;
6197 break;
6198 case 'z': // size_t.
6199 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6200 Type = Context.getSizeType();
6201 break;
6202 case 'F':
6203 Type = Context.getCFConstantStringType();
6204 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006205 case 'G':
6206 Type = Context.getObjCIdType();
6207 break;
6208 case 'H':
6209 Type = Context.getObjCSelType();
6210 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006211 case 'a':
6212 Type = Context.getBuiltinVaListType();
6213 assert(!Type.isNull() && "builtin va list type not initialized!");
6214 break;
6215 case 'A':
6216 // This is a "reference" to a va_list; however, what exactly
6217 // this means depends on how va_list is defined. There are two
6218 // different kinds of va_list: ones passed by value, and ones
6219 // passed by reference. An example of a by-value va_list is
6220 // x86, where va_list is a char*. An example of by-ref va_list
6221 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6222 // we want this argument to be a char*&; for x86-64, we want
6223 // it to be a __va_list_tag*.
6224 Type = Context.getBuiltinVaListType();
6225 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006226 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006227 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006228 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006229 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006230 break;
6231 case 'V': {
6232 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006233 unsigned NumElements = strtoul(Str, &End, 10);
6234 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006235 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006236
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006237 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6238 RequiresICE, false);
6239 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006240
6241 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006242 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006243 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006244 break;
6245 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006246 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006247 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6248 false);
6249 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006250 Type = Context.getComplexType(ElementType);
6251 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00006252 }
6253 case 'Y' : {
6254 Type = Context.getPointerDiffType();
6255 break;
6256 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006257 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006258 Type = Context.getFILEType();
6259 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006260 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006261 return QualType();
6262 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006263 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006264 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006265 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006266 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006267 else
6268 Type = Context.getjmp_bufType();
6269
Mike Stump2adb4da2009-07-28 23:47:15 +00006270 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006271 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006272 return QualType();
6273 }
6274 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006275 }
Mike Stump11289f42009-09-09 15:08:12 +00006276
Chris Lattnerdc226c22010-10-01 22:42:38 +00006277 // If there are modifiers and if we're allowed to parse them, go for it.
6278 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006279 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006280 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006281 default: Done = true; --Str; break;
6282 case '*':
6283 case '&': {
6284 // Both pointers and references can have their pointee types
6285 // qualified with an address space.
6286 char *End;
6287 unsigned AddrSpace = strtoul(Str, &End, 10);
6288 if (End != Str && AddrSpace != 0) {
6289 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6290 Str = End;
6291 }
6292 if (c == '*')
6293 Type = Context.getPointerType(Type);
6294 else
6295 Type = Context.getLValueReferenceType(Type);
6296 break;
6297 }
6298 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6299 case 'C':
6300 Type = Type.withConst();
6301 break;
6302 case 'D':
6303 Type = Context.getVolatileType(Type);
6304 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006305 }
6306 }
Chris Lattner84733392010-10-01 07:13:18 +00006307
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006308 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006309 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006310
Chris Lattnerecd79c62009-06-14 00:45:47 +00006311 return Type;
6312}
6313
6314/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006315QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006316 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006317 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006318 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006319
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006320 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006321
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006322 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006323 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006324 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6325 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006326 if (Error != GE_None)
6327 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006328
6329 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6330
Chris Lattnerecd79c62009-06-14 00:45:47 +00006331 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006332 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006333 if (Error != GE_None)
6334 return QualType();
6335
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006336 // If this argument is required to be an IntegerConstantExpression and the
6337 // caller cares, fill in the bitmask we return.
6338 if (RequiresICE && IntegerConstantArgs)
6339 *IntegerConstantArgs |= 1 << ArgTypes.size();
6340
Chris Lattnerecd79c62009-06-14 00:45:47 +00006341 // Do array -> pointer decay. The builtin should use the decayed type.
6342 if (Ty->isArrayType())
6343 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006344
Chris Lattnerecd79c62009-06-14 00:45:47 +00006345 ArgTypes.push_back(Ty);
6346 }
6347
6348 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6349 "'.' should only occur at end of builtin type list!");
6350
John McCall991eb4b2010-12-21 00:44:39 +00006351 FunctionType::ExtInfo EI;
6352 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6353
6354 bool Variadic = (TypeStr[0] == '.');
6355
6356 // We really shouldn't be making a no-proto type here, especially in C++.
6357 if (ArgTypes.empty() && Variadic)
6358 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006359
John McCalldb40c7f2010-12-14 08:05:40 +00006360 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006361 EPI.ExtInfo = EI;
6362 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006363
6364 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006365}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006366
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006367GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6368 GVALinkage External = GVA_StrongExternal;
6369
6370 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006371 switch (L) {
6372 case NoLinkage:
6373 case InternalLinkage:
6374 case UniqueExternalLinkage:
6375 return GVA_Internal;
6376
6377 case ExternalLinkage:
6378 switch (FD->getTemplateSpecializationKind()) {
6379 case TSK_Undeclared:
6380 case TSK_ExplicitSpecialization:
6381 External = GVA_StrongExternal;
6382 break;
6383
6384 case TSK_ExplicitInstantiationDefinition:
6385 return GVA_ExplicitTemplateInstantiation;
6386
6387 case TSK_ExplicitInstantiationDeclaration:
6388 case TSK_ImplicitInstantiation:
6389 External = GVA_TemplateInstantiation;
6390 break;
6391 }
6392 }
6393
6394 if (!FD->isInlined())
6395 return External;
6396
6397 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6398 // GNU or C99 inline semantics. Determine whether this symbol should be
6399 // externally visible.
6400 if (FD->isInlineDefinitionExternallyVisible())
6401 return External;
6402
6403 // C99 inline semantics, where the symbol is not externally visible.
6404 return GVA_C99Inline;
6405 }
6406
6407 // C++0x [temp.explicit]p9:
6408 // [ Note: The intent is that an inline function that is the subject of
6409 // an explicit instantiation declaration will still be implicitly
6410 // instantiated when used so that the body can be considered for
6411 // inlining, but that no out-of-line copy of the inline function would be
6412 // generated in the translation unit. -- end note ]
6413 if (FD->getTemplateSpecializationKind()
6414 == TSK_ExplicitInstantiationDeclaration)
6415 return GVA_C99Inline;
6416
6417 return GVA_CXXInline;
6418}
6419
6420GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6421 // If this is a static data member, compute the kind of template
6422 // specialization. Otherwise, this variable is not part of a
6423 // template.
6424 TemplateSpecializationKind TSK = TSK_Undeclared;
6425 if (VD->isStaticDataMember())
6426 TSK = VD->getTemplateSpecializationKind();
6427
6428 Linkage L = VD->getLinkage();
6429 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6430 VD->getType()->getLinkage() == UniqueExternalLinkage)
6431 L = UniqueExternalLinkage;
6432
6433 switch (L) {
6434 case NoLinkage:
6435 case InternalLinkage:
6436 case UniqueExternalLinkage:
6437 return GVA_Internal;
6438
6439 case ExternalLinkage:
6440 switch (TSK) {
6441 case TSK_Undeclared:
6442 case TSK_ExplicitSpecialization:
6443 return GVA_StrongExternal;
6444
6445 case TSK_ExplicitInstantiationDeclaration:
6446 llvm_unreachable("Variable should not be instantiated");
6447 // Fall through to treat this like any other instantiation.
6448
6449 case TSK_ExplicitInstantiationDefinition:
6450 return GVA_ExplicitTemplateInstantiation;
6451
6452 case TSK_ImplicitInstantiation:
6453 return GVA_TemplateInstantiation;
6454 }
6455 }
6456
6457 return GVA_StrongExternal;
6458}
6459
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00006460bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006461 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6462 if (!VD->isFileVarDecl())
6463 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00006464 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006465 return false;
6466
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006467 // Weak references don't produce any output by themselves.
6468 if (D->hasAttr<WeakRefAttr>())
6469 return false;
6470
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006471 // Aliases and used decls are required.
6472 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6473 return true;
6474
6475 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6476 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00006477 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00006478 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006479
6480 // Constructors and destructors are required.
6481 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6482 return true;
6483
6484 // The key function for a class is required.
6485 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6486 const CXXRecordDecl *RD = MD->getParent();
6487 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6488 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6489 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6490 return true;
6491 }
6492 }
6493
6494 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6495
6496 // static, static inline, always_inline, and extern inline functions can
6497 // always be deferred. Normal inline functions can be deferred in C99/C++.
6498 // Implicit template instantiations can also be deferred in C++.
6499 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6500 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6501 return false;
6502 return true;
6503 }
Douglas Gregor87d81242011-09-10 00:22:34 +00006504
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006505 const VarDecl *VD = cast<VarDecl>(D);
6506 assert(VD->isFileVarDecl() && "Expected file scoped var");
6507
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006508 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6509 return false;
6510
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006511 // Structs that have non-trivial constructors or destructors are required.
6512
6513 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00006514 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006515 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6516 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00006517 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6518 RD->hasTrivialCopyConstructor() &&
6519 RD->hasTrivialMoveConstructor() &&
6520 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006521 return true;
6522 }
6523 }
6524
6525 GVALinkage L = GetGVALinkageForVariable(VD);
6526 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6527 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6528 return false;
6529 }
6530
6531 return true;
6532}
Charles Davis53c59df2010-08-16 03:33:14 +00006533
Charles Davis99202b32010-11-09 18:04:24 +00006534CallingConv ASTContext::getDefaultMethodCallConv() {
6535 // Pass through to the C++ ABI object
6536 return ABI->getDefaultMethodCallConv();
6537}
6538
Jay Foad39c79802011-01-12 09:06:06 +00006539bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00006540 // Pass through to the C++ ABI object
6541 return ABI->isNearlyEmpty(RD);
6542}
6543
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006544MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00006545 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006546 case CXXABI_ARM:
6547 case CXXABI_Itanium:
6548 return createItaniumMangleContext(*this, getDiagnostics());
6549 case CXXABI_Microsoft:
6550 return createMicrosoftMangleContext(*this, getDiagnostics());
6551 }
David Blaikie83d382b2011-09-23 05:06:16 +00006552 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006553}
6554
Charles Davis53c59df2010-08-16 03:33:14 +00006555CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006556
6557size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00006558 return ASTRecordLayouts.getMemorySize()
6559 + llvm::capacity_in_bytes(ObjCLayouts)
6560 + llvm::capacity_in_bytes(KeyFunctions)
6561 + llvm::capacity_in_bytes(ObjCImpls)
6562 + llvm::capacity_in_bytes(BlockVarCopyInits)
6563 + llvm::capacity_in_bytes(DeclAttrs)
6564 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6565 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6566 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6567 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6568 + llvm::capacity_in_bytes(OverriddenMethods)
6569 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006570 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00006571 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006572}
Ted Kremenek540017e2011-10-06 05:00:56 +00006573
6574void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6575 ParamIndices[D] = index;
6576}
6577
6578unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6579 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6580 assert(I != ParamIndices.end() &&
6581 "ParmIndices lacks entry set by ParmVarDecl");
6582 return I->second;
6583}