blob: 4fbb5408dc0d2dca2b90c2e932744e314a273bcb [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Ted Kremenek7d39c9a2011-07-27 18:41:12 +000033#include "llvm/Support/Capacity.h"
Charles Davis53c59df2010-08-16 03:33:14 +000034#include "CXXABI.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000035#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000036
Chris Lattnerddc135e2006-11-10 06:34:16 +000037using namespace clang;
38
Douglas Gregor9672f922010-07-03 00:47:00 +000039unsigned ASTContext::NumImplicitDefaultConstructors;
40unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000041unsigned ASTContext::NumImplicitCopyConstructors;
42unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000043unsigned ASTContext::NumImplicitMoveConstructors;
44unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000045unsigned ASTContext::NumImplicitCopyAssignmentOperators;
46unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000047unsigned ASTContext::NumImplicitMoveAssignmentOperators;
48unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000049unsigned ASTContext::NumImplicitDestructors;
50unsigned ASTContext::NumImplicitDestructorsDeclared;
51
Steve Naroff0af91202007-04-27 21:51:21 +000052enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000053 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000054};
55
Douglas Gregor7dbfb462010-06-16 21:09:37 +000056void
57ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
58 TemplateTemplateParmDecl *Parm) {
59 ID.AddInteger(Parm->getDepth());
60 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +000061 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000062
63 TemplateParameterList *Params = Parm->getTemplateParameters();
64 ID.AddInteger(Params->size());
65 for (TemplateParameterList::const_iterator P = Params->begin(),
66 PEnd = Params->end();
67 P != PEnd; ++P) {
68 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
69 ID.AddInteger(0);
70 ID.AddBoolean(TTP->isParameterPack());
71 continue;
72 }
73
74 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
75 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +000076 ID.AddBoolean(NTTP->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000077 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +000078 if (NTTP->isExpandedParameterPack()) {
79 ID.AddBoolean(true);
80 ID.AddInteger(NTTP->getNumExpansionTypes());
81 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
82 ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
83 } else
84 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +000085 continue;
86 }
87
88 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
89 ID.AddInteger(2);
90 Profile(ID, TTP);
91 }
92}
93
94TemplateTemplateParmDecl *
95ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +000096 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +000097 // Check if we already have a canonical template template parameter.
98 llvm::FoldingSetNodeID ID;
99 CanonicalTemplateTemplateParm::Profile(ID, TTP);
100 void *InsertPos = 0;
101 CanonicalTemplateTemplateParm *Canonical
102 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
103 if (Canonical)
104 return Canonical->getParam();
105
106 // Build a canonical template parameter list.
107 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000108 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000109 CanonParams.reserve(Params->size());
110 for (TemplateParameterList::const_iterator P = Params->begin(),
111 PEnd = Params->end();
112 P != PEnd; ++P) {
113 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
114 CanonParams.push_back(
115 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000116 SourceLocation(),
117 SourceLocation(),
118 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000119 TTP->getIndex(), 0, false,
120 TTP->isParameterPack()));
121 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000122 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
123 QualType T = getCanonicalType(NTTP->getType());
124 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
125 NonTypeTemplateParmDecl *Param;
126 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000127 SmallVector<QualType, 2> ExpandedTypes;
128 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000129 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
130 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
131 ExpandedTInfos.push_back(
132 getTrivialTypeSourceInfo(ExpandedTypes.back()));
133 }
134
135 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000136 SourceLocation(),
137 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000138 NTTP->getDepth(),
139 NTTP->getPosition(), 0,
140 T,
141 TInfo,
142 ExpandedTypes.data(),
143 ExpandedTypes.size(),
144 ExpandedTInfos.data());
145 } else {
146 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000147 SourceLocation(),
148 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000149 NTTP->getDepth(),
150 NTTP->getPosition(), 0,
151 T,
152 NTTP->isParameterPack(),
153 TInfo);
154 }
155 CanonParams.push_back(Param);
156
157 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000158 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
159 cast<TemplateTemplateParmDecl>(*P)));
160 }
161
162 TemplateTemplateParmDecl *CanonTTP
163 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
164 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000165 TTP->getPosition(),
166 TTP->isParameterPack(),
167 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000168 TemplateParameterList::Create(*this, SourceLocation(),
169 SourceLocation(),
170 CanonParams.data(),
171 CanonParams.size(),
172 SourceLocation()));
173
174 // Get the new insert position for the node we care about.
175 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
176 assert(Canonical == 0 && "Shouldn't be in the map!");
177 (void)Canonical;
178
179 // Create the canonical template template parameter entry.
180 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
181 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
182 return CanonTTP;
183}
184
Charles Davis53c59df2010-08-16 03:33:14 +0000185CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000186 if (!LangOpts.CPlusPlus) return 0;
187
Charles Davis6bcb07a2010-08-19 02:18:14 +0000188 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000189 case CXXABI_ARM:
190 return CreateARMCXXABI(*this);
191 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000192 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000193 case CXXABI_Microsoft:
194 return CreateMicrosoftCXXABI(*this);
195 }
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
John McCall8a6b59a2011-10-17 18:09:15 +0000467 // Placeholder type for unbridged ARC casts.
468 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
469
Chris Lattner970e54e2006-11-12 00:37:36 +0000470 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000471 FloatComplexTy = getComplexType(FloatTy);
472 DoubleComplexTy = getComplexType(DoubleTy);
473 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000474
Steve Naroff66e9f332007-10-15 14:41:52 +0000475 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000476
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000477 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000478 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
479 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000480 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000481
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000482 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000483
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000484 // void * type
485 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000486
487 // nullptr type (C++0x 2.14.7)
488 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000489
490 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
491 InitBuiltinType(HalfTy, BuiltinType::Half);
Chris Lattner970e54e2006-11-12 00:37:36 +0000492}
493
David Blaikie9c902b52011-09-25 23:23:43 +0000494DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000495 return SourceMgr.getDiagnostics();
496}
497
Douglas Gregor561eceb2010-08-30 16:49:28 +0000498AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
499 AttrVec *&Result = DeclAttrs[D];
500 if (!Result) {
501 void *Mem = Allocate(sizeof(AttrVec));
502 Result = new (Mem) AttrVec;
503 }
504
505 return *Result;
506}
507
508/// \brief Erase the attributes corresponding to the given declaration.
509void ASTContext::eraseDeclAttrs(const Decl *D) {
510 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
511 if (Pos != DeclAttrs.end()) {
512 Pos->second->~AttrVec();
513 DeclAttrs.erase(Pos);
514 }
515}
516
Douglas Gregor86d142a2009-10-08 07:24:58 +0000517MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000518ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000519 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000520 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000521 = InstantiatedFromStaticDataMember.find(Var);
522 if (Pos == InstantiatedFromStaticDataMember.end())
523 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000524
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000525 return Pos->second;
526}
527
Mike Stump11289f42009-09-09 15:08:12 +0000528void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000529ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000530 TemplateSpecializationKind TSK,
531 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000532 assert(Inst->isStaticDataMember() && "Not a static data member");
533 assert(Tmpl->isStaticDataMember() && "Not a static data member");
534 assert(!InstantiatedFromStaticDataMember[Inst] &&
535 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000536 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000537 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000538}
539
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000540FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
541 const FunctionDecl *FD){
542 assert(FD && "Specialization is 0");
543 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000544 = ClassScopeSpecializationPattern.find(FD);
545 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000546 return 0;
547
548 return Pos->second;
549}
550
551void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
552 FunctionDecl *Pattern) {
553 assert(FD && "Specialization is 0");
554 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000555 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000556}
557
John McCalle61f2ba2009-11-18 02:36:19 +0000558NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000559ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000560 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000561 = InstantiatedFromUsingDecl.find(UUD);
562 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000563 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000564
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000565 return Pos->second;
566}
567
568void
John McCallb96ec562009-12-04 22:46:56 +0000569ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
570 assert((isa<UsingDecl>(Pattern) ||
571 isa<UnresolvedUsingValueDecl>(Pattern) ||
572 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
573 "pattern decl is not a using decl");
574 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
575 InstantiatedFromUsingDecl[Inst] = Pattern;
576}
577
578UsingShadowDecl *
579ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
580 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
581 = InstantiatedFromUsingShadowDecl.find(Inst);
582 if (Pos == InstantiatedFromUsingShadowDecl.end())
583 return 0;
584
585 return Pos->second;
586}
587
588void
589ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
590 UsingShadowDecl *Pattern) {
591 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
592 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000593}
594
Anders Carlsson5da84842009-09-01 04:26:58 +0000595FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
596 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
597 = InstantiatedFromUnnamedFieldDecl.find(Field);
598 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
599 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000600
Anders Carlsson5da84842009-09-01 04:26:58 +0000601 return Pos->second;
602}
603
604void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
605 FieldDecl *Tmpl) {
606 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
607 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
608 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
609 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000610
Anders Carlsson5da84842009-09-01 04:26:58 +0000611 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
612}
613
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000614bool ASTContext::ZeroBitfieldFollowsNonBitfield(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);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000618}
619
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000620bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
621 const FieldDecl *LastFD) const {
622 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000623 FD->getBitWidthValue(*this) == 0 &&
624 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000625}
626
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000627bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
628 const FieldDecl *LastFD) const {
629 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000630 FD->getBitWidthValue(*this) &&
631 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000632}
633
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000634bool ASTContext::NonBitfieldFollowsBitfield(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 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000638}
639
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000640bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000641 const FieldDecl *LastFD) const {
642 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000643 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000644}
645
Douglas Gregor832940b2010-03-02 23:58:15 +0000646ASTContext::overridden_cxx_method_iterator
647ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
648 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
649 = OverriddenMethods.find(Method);
650 if (Pos == OverriddenMethods.end())
651 return 0;
652
653 return Pos->second.begin();
654}
655
656ASTContext::overridden_cxx_method_iterator
657ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
658 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
659 = OverriddenMethods.find(Method);
660 if (Pos == OverriddenMethods.end())
661 return 0;
662
663 return Pos->second.end();
664}
665
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000666unsigned
667ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
668 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
669 = OverriddenMethods.find(Method);
670 if (Pos == OverriddenMethods.end())
671 return 0;
672
673 return Pos->second.size();
674}
675
Douglas Gregor832940b2010-03-02 23:58:15 +0000676void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
677 const CXXMethodDecl *Overridden) {
678 OverriddenMethods[Method].push_back(Overridden);
679}
680
Chris Lattner53cfe802007-07-18 17:52:12 +0000681//===----------------------------------------------------------------------===//
682// Type Sizing and Analysis
683//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000684
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000685/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
686/// scalar floating point type.
687const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000688 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000689 assert(BT && "Not a floating point type!");
690 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000691 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000692 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +0000693 case BuiltinType::Float: return Target->getFloatFormat();
694 case BuiltinType::Double: return Target->getDoubleFormat();
695 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000696 }
697}
698
Ken Dyck160146e2010-01-27 17:10:57 +0000699/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000700/// specified decl. Note that bitfields do not have a valid alignment, so
701/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000702/// If @p RefAsPointee, references are treated like their underlying type
703/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000704CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000705 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +0000706
John McCall94268702010-10-08 18:24:19 +0000707 bool UseAlignAttrOnly = false;
708 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
709 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000710
John McCall94268702010-10-08 18:24:19 +0000711 // __attribute__((aligned)) can increase or decrease alignment
712 // *except* on a struct or struct member, where it only increases
713 // alignment unless 'packed' is also specified.
714 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +0000715 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +0000716 // ignore that possibility; Sema should diagnose it.
717 if (isa<FieldDecl>(D)) {
718 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
719 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
720 } else {
721 UseAlignAttrOnly = true;
722 }
723 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000724 else if (isa<FieldDecl>(D))
725 UseAlignAttrOnly =
726 D->hasAttr<PackedAttr>() ||
727 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000728
John McCall4e819612011-01-20 07:57:12 +0000729 // If we're using the align attribute only, just ignore everything
730 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000731 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000732 // do nothing
733
John McCall94268702010-10-08 18:24:19 +0000734 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000735 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000736 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000737 if (RefAsPointee)
738 T = RT->getPointeeType();
739 else
740 T = getPointerType(RT->getPointeeType());
741 }
742 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000743 // Adjust alignments of declarations with array type by the
744 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +0000745 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000746 const ArrayType *arrayType;
747 if (MinWidth && (arrayType = getAsArrayType(T))) {
748 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000749 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +0000750 else if (isa<ConstantArrayType>(arrayType) &&
751 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000752 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000753
John McCall33ddac02011-01-19 10:06:00 +0000754 // Walk through any array types while we're at it.
755 T = getBaseElementType(arrayType);
756 }
Chad Rosier99ee7822011-07-26 07:03:04 +0000757 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +0000758 }
John McCall4e819612011-01-20 07:57:12 +0000759
760 // Fields can be subject to extra alignment constraints, like if
761 // the field is packed, the struct is packed, or the struct has a
762 // a max-field-alignment constraint (#pragma pack). So calculate
763 // the actual alignment of the field within the struct, and then
764 // (as we're expected to) constrain that by the alignment of the type.
765 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
766 // So calculate the alignment of the field.
767 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
768
769 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000770 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000771
772 // Use the GCD of that and the offset within the record.
773 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
774 if (offset > 0) {
775 // Alignment is always a power of 2, so the GCD will be a power of 2,
776 // which means we get to do this crazy thing instead of Euclid's.
777 uint64_t lowBitOfOffset = offset & (~offset + 1);
778 if (lowBitOfOffset < fieldAlign)
779 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
780 }
781
782 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000783 }
Chris Lattner68061312009-01-24 21:53:27 +0000784 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000785
Ken Dyckcc56c542011-01-15 18:38:59 +0000786 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000787}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000788
John McCall87fe5d52010-05-20 01:18:31 +0000789std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000790ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000791 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000792 return std::make_pair(toCharUnitsFromBits(Info.first),
793 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000794}
795
796std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000797ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000798 return getTypeInfoInChars(T.getTypePtr());
799}
800
Chris Lattner983a8bb2007-07-13 22:13:22 +0000801/// getTypeSize - Return the size of the specified type, in bits. This method
802/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000803///
804/// FIXME: Pointers into different addr spaces could have different sizes and
805/// alignment requirements: getPointerInfo should take an AddrSpace, this
806/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000807std::pair<uint64_t, unsigned>
Jay Foad39c79802011-01-12 09:06:06 +0000808ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000809 uint64_t Width=0;
810 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000811 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000812#define TYPE(Class, Base)
813#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000814#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000815#define DEPENDENT_TYPE(Class, Base) case Type::Class:
816#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +0000817 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000818 break;
819
Chris Lattner355332d2007-07-13 22:27:08 +0000820 case Type::FunctionNoProto:
821 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000822 // GCC extension: alignof(function) = 32 bits
823 Width = 0;
824 Align = 32;
825 break;
826
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000827 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000828 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000829 Width = 0;
830 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
831 break;
832
Steve Naroff5c131802007-08-30 01:06:46 +0000833 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000834 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000835
Chris Lattner37e05872008-03-05 18:54:05 +0000836 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000837 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000838 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +0000839 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000840 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000841 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000842 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000843 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000844 const VectorType *VT = cast<VectorType>(T);
845 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
846 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000847 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000848 // If the alignment is not a power of 2, round up to the next power of 2.
849 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000850 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000851 Align = llvm::NextPowerOf2(Align);
852 Width = llvm::RoundUpToAlignment(Width, Align);
853 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000854 break;
855 }
Chris Lattner647fb222007-07-18 18:26:58 +0000856
Chris Lattner7570e9c2008-03-08 08:52:55 +0000857 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000858 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000859 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000860 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000861 // GCC extension: alignof(void) = 8 bits.
862 Width = 0;
863 Align = 8;
864 break;
865
Chris Lattner6a4f7452007-12-19 19:23:28 +0000866 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000867 Width = Target->getBoolWidth();
868 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000869 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000870 case BuiltinType::Char_S:
871 case BuiltinType::Char_U:
872 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000873 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000874 Width = Target->getCharWidth();
875 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000876 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000877 case BuiltinType::WChar_S:
878 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000879 Width = Target->getWCharWidth();
880 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000881 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000882 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000883 Width = Target->getChar16Width();
884 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000885 break;
886 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000887 Width = Target->getChar32Width();
888 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000889 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000890 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000891 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000892 Width = Target->getShortWidth();
893 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000894 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000895 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000896 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000897 Width = Target->getIntWidth();
898 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000899 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000900 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000901 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000902 Width = Target->getLongWidth();
903 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000904 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000905 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000906 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000907 Width = Target->getLongLongWidth();
908 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000909 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000910 case BuiltinType::Int128:
911 case BuiltinType::UInt128:
912 Width = 128;
913 Align = 128; // int128_t is 128-bit aligned on all targets.
914 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000915 case BuiltinType::Half:
916 Width = Target->getHalfWidth();
917 Align = Target->getHalfAlign();
918 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000919 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000920 Width = Target->getFloatWidth();
921 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000922 break;
923 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000924 Width = Target->getDoubleWidth();
925 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000926 break;
927 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000928 Width = Target->getLongDoubleWidth();
929 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000930 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000931 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000932 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
933 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000934 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000935 case BuiltinType::ObjCId:
936 case BuiltinType::ObjCClass:
937 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000938 Width = Target->getPointerWidth(0);
939 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000940 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000941 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000942 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000943 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000944 Width = Target->getPointerWidth(0);
945 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000946 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000947 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000948 unsigned AS = getTargetAddressSpace(
949 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000950 Width = Target->getPointerWidth(AS);
951 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +0000952 break;
953 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000954 case Type::LValueReference:
955 case Type::RValueReference: {
956 // alignof and sizeof should never enter this code path here, so we go
957 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000958 unsigned AS = getTargetAddressSpace(
959 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000960 Width = Target->getPointerWidth(AS);
961 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000962 break;
963 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000964 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000965 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000966 Width = Target->getPointerWidth(AS);
967 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000968 break;
969 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000970 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000971 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000972 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000973 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000974 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000975 Align = PtrDiffInfo.second;
976 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000977 }
Chris Lattner647fb222007-07-18 18:26:58 +0000978 case Type::Complex: {
979 // Complex types have the same alignment as their elements, but twice the
980 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000981 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000982 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000983 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000984 Align = EltInfo.second;
985 break;
986 }
John McCall8b07ec22010-05-15 11:32:37 +0000987 case Type::ObjCObject:
988 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000989 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000990 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000991 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000992 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000993 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +0000994 break;
995 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000996 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000997 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000998 const TagType *TT = cast<TagType>(T);
999
1000 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001001 Width = 8;
1002 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001003 break;
1004 }
Mike Stump11289f42009-09-09 15:08:12 +00001005
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001006 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001007 return getTypeInfo(ET->getDecl()->getIntegerType());
1008
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001009 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001010 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001011 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001012 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001013 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001014 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001015
Chris Lattner63d2b362009-10-22 05:17:15 +00001016 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001017 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1018 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001019
Richard Smith30482bc2011-02-20 03:19:35 +00001020 case Type::Auto: {
1021 const AutoType *A = cast<AutoType>(T);
1022 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001023 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001024 }
1025
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001026 case Type::Paren:
1027 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1028
Douglas Gregoref462e62009-04-30 17:32:17 +00001029 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001030 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001031 std::pair<uint64_t, unsigned> Info
1032 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001033 // If the typedef has an aligned attribute on it, it overrides any computed
1034 // alignment we have. This violates the GCC documentation (which says that
1035 // attribute(aligned) can only round up) but matches its implementation.
1036 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1037 Align = AttrAlign;
1038 else
1039 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001040 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001041 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001042 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001043
1044 case Type::TypeOfExpr:
1045 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1046 .getTypePtr());
1047
1048 case Type::TypeOf:
1049 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1050
Anders Carlsson81df7b82009-06-24 19:06:50 +00001051 case Type::Decltype:
1052 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1053 .getTypePtr());
1054
Alexis Hunte852b102011-05-24 22:41:36 +00001055 case Type::UnaryTransform:
1056 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1057
Abramo Bagnara6150c882010-05-11 21:36:43 +00001058 case Type::Elaborated:
1059 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001060
John McCall81904512011-01-06 01:58:22 +00001061 case Type::Attributed:
1062 return getTypeInfo(
1063 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1064
Richard Smith3f1b5d02011-05-05 21:57:07 +00001065 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001066 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001067 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001068 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1069 // A type alias template specialization may refer to a typedef with the
1070 // aligned attribute on it.
1071 if (TST->isTypeAlias())
1072 return getTypeInfo(TST->getAliasedType().getTypePtr());
1073 else
1074 return getTypeInfo(getCanonicalType(T));
1075 }
1076
Eli Friedman0dfb8892011-10-06 23:00:33 +00001077 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001078 std::pair<uint64_t, unsigned> Info
1079 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1080 Width = Info.first;
1081 Align = Info.second;
1082 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1083 llvm::isPowerOf2_64(Width)) {
1084 // We can potentially perform lock-free atomic operations for this
1085 // type; promote the alignment appropriately.
1086 // FIXME: We could potentially promote the width here as well...
1087 // is that worthwhile? (Non-struct atomic types generally have
1088 // power-of-two size anyway, but structs might not. Requires a bit
1089 // of implementation work to make sure we zero out the extra bits.)
1090 Align = static_cast<unsigned>(Width);
1091 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001092 }
1093
Douglas Gregoref462e62009-04-30 17:32:17 +00001094 }
Mike Stump11289f42009-09-09 15:08:12 +00001095
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001096 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001097 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001098}
1099
Ken Dyckcc56c542011-01-15 18:38:59 +00001100/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1101CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1102 return CharUnits::fromQuantity(BitSize / getCharWidth());
1103}
1104
Ken Dyckb0fcc592011-02-11 01:54:29 +00001105/// toBits - Convert a size in characters to a size in characters.
1106int64_t ASTContext::toBits(CharUnits CharSize) const {
1107 return CharSize.getQuantity() * getCharWidth();
1108}
1109
Ken Dyck8c89d592009-12-22 14:23:30 +00001110/// getTypeSizeInChars - Return the size of the specified type, in characters.
1111/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001112CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001113 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001114}
Jay Foad39c79802011-01-12 09:06:06 +00001115CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001116 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001117}
1118
Ken Dycka6046ab2010-01-26 17:25:18 +00001119/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001120/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001121CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001122 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001123}
Jay Foad39c79802011-01-12 09:06:06 +00001124CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001125 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001126}
1127
Chris Lattnera3402cd2009-01-27 18:08:34 +00001128/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1129/// type for the current target in bits. This can be different than the ABI
1130/// alignment in cases where it is beneficial for performance to overalign
1131/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001132unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001133 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001134
1135 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001136 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001137 T = CT->getElementType().getTypePtr();
1138 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1139 T->isSpecificBuiltinType(BuiltinType::LongLong))
1140 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1141
Chris Lattnera3402cd2009-01-27 18:08:34 +00001142 return ABIAlign;
1143}
1144
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001145/// DeepCollectObjCIvars -
1146/// This routine first collects all declared, but not synthesized, ivars in
1147/// super class and then collects all ivars, including those synthesized for
1148/// current class. This routine is used for implementation of current class
1149/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001150///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001151void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1152 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001153 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001154 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1155 DeepCollectObjCIvars(SuperClass, false, Ivars);
1156 if (!leafClass) {
1157 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1158 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +00001159 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001160 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001161 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001162 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001163 Iv= Iv->getNextIvar())
1164 Ivars.push_back(Iv);
1165 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001166}
1167
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001168/// CollectInheritedProtocols - Collect all protocols in current class and
1169/// those inherited by it.
1170void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001171 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001172 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001173 // We can use protocol_iterator here instead of
1174 // all_referenced_protocol_iterator since we are walking all categories.
1175 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1176 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001177 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001178 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001179 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001180 PE = Proto->protocol_end(); P != PE; ++P) {
1181 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001182 CollectInheritedProtocols(*P, Protocols);
1183 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001184 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001185
1186 // Categories of this Interface.
1187 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1188 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1189 CollectInheritedProtocols(CDeclChain, Protocols);
1190 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1191 while (SD) {
1192 CollectInheritedProtocols(SD, Protocols);
1193 SD = SD->getSuperClass();
1194 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001195 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001196 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001197 PE = OC->protocol_end(); P != PE; ++P) {
1198 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001199 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001200 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1201 PE = Proto->protocol_end(); P != PE; ++P)
1202 CollectInheritedProtocols(*P, Protocols);
1203 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001204 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001205 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1206 PE = OP->protocol_end(); P != PE; ++P) {
1207 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001208 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001209 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1210 PE = Proto->protocol_end(); P != PE; ++P)
1211 CollectInheritedProtocols(*P, Protocols);
1212 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001213 }
1214}
1215
Jay Foad39c79802011-01-12 09:06:06 +00001216unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001217 unsigned count = 0;
1218 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001219 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1220 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001221 count += CDecl->ivar_size();
1222
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001223 // Count ivar defined in this class's implementation. This
1224 // includes synthesized ivars.
1225 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001226 count += ImplDecl->ivar_size();
1227
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001228 return count;
1229}
1230
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001231/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1232ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1233 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1234 I = ObjCImpls.find(D);
1235 if (I != ObjCImpls.end())
1236 return cast<ObjCImplementationDecl>(I->second);
1237 return 0;
1238}
1239/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1240ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1241 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1242 I = ObjCImpls.find(D);
1243 if (I != ObjCImpls.end())
1244 return cast<ObjCCategoryImplDecl>(I->second);
1245 return 0;
1246}
1247
1248/// \brief Set the implementation of ObjCInterfaceDecl.
1249void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1250 ObjCImplementationDecl *ImplD) {
1251 assert(IFaceD && ImplD && "Passed null params");
1252 ObjCImpls[IFaceD] = ImplD;
1253}
1254/// \brief Set the implementation of ObjCCategoryDecl.
1255void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1256 ObjCCategoryImplDecl *ImplD) {
1257 assert(CatD && ImplD && "Passed null params");
1258 ObjCImpls[CatD] = ImplD;
1259}
1260
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001261/// \brief Get the copy initialization expression of VarDecl,or NULL if
1262/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001263Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001264 assert(VD && "Passed null params");
1265 assert(VD->hasAttr<BlocksAttr>() &&
1266 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001267 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001268 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001269 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1270}
1271
1272/// \brief Set the copy inialization expression of a block var decl.
1273void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1274 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001275 assert(VD->hasAttr<BlocksAttr>() &&
1276 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001277 BlockVarCopyInits[VD] = Init;
1278}
1279
John McCallbcd03502009-12-07 02:54:59 +00001280/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001281///
John McCallbcd03502009-12-07 02:54:59 +00001282/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001283/// the TypeLoc wrappers.
1284///
1285/// \param T the type that will be the basis for type source info. This type
1286/// should refer to how the declarator was written in source code, not to
1287/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001288TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001289 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001290 if (!DataSize)
1291 DataSize = TypeLoc::getFullDataSizeForType(T);
1292 else
1293 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001294 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001295
John McCallbcd03502009-12-07 02:54:59 +00001296 TypeSourceInfo *TInfo =
1297 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1298 new (TInfo) TypeSourceInfo(T);
1299 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001300}
1301
John McCallbcd03502009-12-07 02:54:59 +00001302TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001303 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001304 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001305 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001306 return DI;
1307}
1308
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001309const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001310ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001311 return getObjCLayout(D, 0);
1312}
1313
1314const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001315ASTContext::getASTObjCImplementationLayout(
1316 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001317 return getObjCLayout(D->getClassInterface(), D);
1318}
1319
Chris Lattner983a8bb2007-07-13 22:13:22 +00001320//===----------------------------------------------------------------------===//
1321// Type creation/memoization methods
1322//===----------------------------------------------------------------------===//
1323
Jay Foad39c79802011-01-12 09:06:06 +00001324QualType
John McCall33ddac02011-01-19 10:06:00 +00001325ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1326 unsigned fastQuals = quals.getFastQualifiers();
1327 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001328
1329 // Check if we've already instantiated this type.
1330 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001331 ExtQuals::Profile(ID, baseType, quals);
1332 void *insertPos = 0;
1333 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1334 assert(eq->getQualifiers() == quals);
1335 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001336 }
1337
John McCall33ddac02011-01-19 10:06:00 +00001338 // If the base type is not canonical, make the appropriate canonical type.
1339 QualType canon;
1340 if (!baseType->isCanonicalUnqualified()) {
1341 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1342 canonSplit.second.addConsistentQualifiers(quals);
1343 canon = getExtQualType(canonSplit.first, canonSplit.second);
1344
1345 // Re-find the insert position.
1346 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1347 }
1348
1349 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1350 ExtQualNodes.InsertNode(eq, insertPos);
1351 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001352}
1353
Jay Foad39c79802011-01-12 09:06:06 +00001354QualType
1355ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001356 QualType CanT = getCanonicalType(T);
1357 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001358 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001359
John McCall8ccfcb52009-09-24 19:53:00 +00001360 // If we are composing extended qualifiers together, merge together
1361 // into one ExtQuals node.
1362 QualifierCollector Quals;
1363 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001364
John McCall8ccfcb52009-09-24 19:53:00 +00001365 // If this type already has an address space specified, it cannot get
1366 // another one.
1367 assert(!Quals.hasAddressSpace() &&
1368 "Type cannot be in multiple addr spaces!");
1369 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001370
John McCall8ccfcb52009-09-24 19:53:00 +00001371 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001372}
1373
Chris Lattnerd60183d2009-02-18 22:53:11 +00001374QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001375 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001376 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001377 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001378 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001379
John McCall53fa7142010-12-24 02:08:15 +00001380 if (const PointerType *ptr = T->getAs<PointerType>()) {
1381 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001382 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001383 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1384 return getPointerType(ResultType);
1385 }
1386 }
Mike Stump11289f42009-09-09 15:08:12 +00001387
John McCall8ccfcb52009-09-24 19:53:00 +00001388 // If we are composing extended qualifiers together, merge together
1389 // into one ExtQuals node.
1390 QualifierCollector Quals;
1391 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001392
John McCall8ccfcb52009-09-24 19:53:00 +00001393 // If this type already has an ObjCGC specified, it cannot get
1394 // another one.
1395 assert(!Quals.hasObjCGCAttr() &&
1396 "Type cannot have multiple ObjCGCs!");
1397 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001398
John McCall8ccfcb52009-09-24 19:53:00 +00001399 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001400}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001401
John McCall4f5019e2010-12-19 02:44:49 +00001402const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1403 FunctionType::ExtInfo Info) {
1404 if (T->getExtInfo() == Info)
1405 return T;
1406
1407 QualType Result;
1408 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1409 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1410 } else {
1411 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1412 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1413 EPI.ExtInfo = Info;
1414 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1415 FPT->getNumArgs(), EPI);
1416 }
1417
1418 return cast<FunctionType>(Result.getTypePtr());
1419}
1420
Chris Lattnerc6395932007-06-22 20:56:16 +00001421/// getComplexType - Return the uniqued reference to the type for a complex
1422/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001423QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001424 // Unique pointers, to guarantee there is only one pointer of a particular
1425 // structure.
1426 llvm::FoldingSetNodeID ID;
1427 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001428
Chris Lattnerc6395932007-06-22 20:56:16 +00001429 void *InsertPos = 0;
1430 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1431 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001432
Chris Lattnerc6395932007-06-22 20:56:16 +00001433 // If the pointee type isn't canonical, this won't be a canonical type either,
1434 // so fill in the canonical type field.
1435 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001436 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001437 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001438
Chris Lattnerc6395932007-06-22 20:56:16 +00001439 // Get the new insert position for the node we care about.
1440 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001441 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001442 }
John McCall90d1c2d2009-09-24 23:30:46 +00001443 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001444 Types.push_back(New);
1445 ComplexTypes.InsertNode(New, InsertPos);
1446 return QualType(New, 0);
1447}
1448
Chris Lattner970e54e2006-11-12 00:37:36 +00001449/// getPointerType - Return the uniqued reference to the type for a pointer to
1450/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001451QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001452 // Unique pointers, to guarantee there is only one pointer of a particular
1453 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001454 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001455 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001456
Chris Lattner67521df2007-01-27 01:29:36 +00001457 void *InsertPos = 0;
1458 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001459 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001460
Chris Lattner7ccecb92006-11-12 08:50:50 +00001461 // If the pointee type isn't canonical, this won't be a canonical type either,
1462 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001463 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001464 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001465 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001466
Chris Lattner67521df2007-01-27 01:29:36 +00001467 // Get the new insert position for the node we care about.
1468 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001469 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001470 }
John McCall90d1c2d2009-09-24 23:30:46 +00001471 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001472 Types.push_back(New);
1473 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001474 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001475}
1476
Mike Stump11289f42009-09-09 15:08:12 +00001477/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001478/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001479QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001480 assert(T->isFunctionType() && "block of function types only");
1481 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001482 // structure.
1483 llvm::FoldingSetNodeID ID;
1484 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001485
Steve Naroffec33ed92008-08-27 16:04:49 +00001486 void *InsertPos = 0;
1487 if (BlockPointerType *PT =
1488 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1489 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001490
1491 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001492 // type either so fill in the canonical type field.
1493 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001494 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001495 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001496
Steve Naroffec33ed92008-08-27 16:04:49 +00001497 // Get the new insert position for the node we care about.
1498 BlockPointerType *NewIP =
1499 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001500 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001501 }
John McCall90d1c2d2009-09-24 23:30:46 +00001502 BlockPointerType *New
1503 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001504 Types.push_back(New);
1505 BlockPointerTypes.InsertNode(New, InsertPos);
1506 return QualType(New, 0);
1507}
1508
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001509/// getLValueReferenceType - Return the uniqued reference to the type for an
1510/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001511QualType
1512ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001513 assert(getCanonicalType(T) != OverloadTy &&
1514 "Unresolved overloaded function type");
1515
Bill Wendling3708c182007-05-27 10:15:43 +00001516 // Unique pointers, to guarantee there is only one pointer of a particular
1517 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001518 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001519 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001520
1521 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001522 if (LValueReferenceType *RT =
1523 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001524 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001525
John McCallfc93cf92009-10-22 22:37:11 +00001526 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1527
Bill Wendling3708c182007-05-27 10:15:43 +00001528 // If the referencee type isn't canonical, this won't be a canonical type
1529 // either, so fill in the canonical type field.
1530 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001531 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1532 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1533 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001534
Bill Wendling3708c182007-05-27 10:15:43 +00001535 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001536 LValueReferenceType *NewIP =
1537 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001538 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001539 }
1540
John McCall90d1c2d2009-09-24 23:30:46 +00001541 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001542 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1543 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001544 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001545 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001546
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001547 return QualType(New, 0);
1548}
1549
1550/// getRValueReferenceType - Return the uniqued reference to the type for an
1551/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001552QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001553 // Unique pointers, to guarantee there is only one pointer of a particular
1554 // structure.
1555 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001556 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001557
1558 void *InsertPos = 0;
1559 if (RValueReferenceType *RT =
1560 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1561 return QualType(RT, 0);
1562
John McCallfc93cf92009-10-22 22:37:11 +00001563 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1564
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001565 // If the referencee type isn't canonical, this won't be a canonical type
1566 // either, so fill in the canonical type field.
1567 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001568 if (InnerRef || !T.isCanonical()) {
1569 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1570 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001571
1572 // Get the new insert position for the node we care about.
1573 RValueReferenceType *NewIP =
1574 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001575 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001576 }
1577
John McCall90d1c2d2009-09-24 23:30:46 +00001578 RValueReferenceType *New
1579 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001580 Types.push_back(New);
1581 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001582 return QualType(New, 0);
1583}
1584
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001585/// getMemberPointerType - Return the uniqued reference to the type for a
1586/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001587QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001588 // Unique pointers, to guarantee there is only one pointer of a particular
1589 // structure.
1590 llvm::FoldingSetNodeID ID;
1591 MemberPointerType::Profile(ID, T, Cls);
1592
1593 void *InsertPos = 0;
1594 if (MemberPointerType *PT =
1595 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1596 return QualType(PT, 0);
1597
1598 // If the pointee or class type isn't canonical, this won't be a canonical
1599 // type either, so fill in the canonical type field.
1600 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001601 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001602 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1603
1604 // Get the new insert position for the node we care about.
1605 MemberPointerType *NewIP =
1606 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001607 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001608 }
John McCall90d1c2d2009-09-24 23:30:46 +00001609 MemberPointerType *New
1610 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001611 Types.push_back(New);
1612 MemberPointerTypes.InsertNode(New, InsertPos);
1613 return QualType(New, 0);
1614}
1615
Mike Stump11289f42009-09-09 15:08:12 +00001616/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001617/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001618QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001619 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001620 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001621 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001622 assert((EltTy->isDependentType() ||
1623 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001624 "Constant array of VLAs is illegal!");
1625
Chris Lattnere2df3f92009-05-13 04:12:56 +00001626 // Convert the array size into a canonical width matching the pointer size for
1627 // the target.
1628 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001629 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001630 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001631
Chris Lattner23b7eb62007-06-15 23:05:46 +00001632 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001633 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001634
Chris Lattner36f8e652007-01-27 08:31:04 +00001635 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001636 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001637 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001638 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001639
John McCall33ddac02011-01-19 10:06:00 +00001640 // If the element type isn't canonical or has qualifiers, this won't
1641 // be a canonical type either, so fill in the canonical type field.
1642 QualType Canon;
1643 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1644 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1645 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001646 ASM, IndexTypeQuals);
John McCall33ddac02011-01-19 10:06:00 +00001647 Canon = getQualifiedType(Canon, canonSplit.second);
1648
Chris Lattner36f8e652007-01-27 08:31:04 +00001649 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001650 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001651 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001652 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001653 }
Mike Stump11289f42009-09-09 15:08:12 +00001654
John McCall90d1c2d2009-09-24 23:30:46 +00001655 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001656 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001657 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001658 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001659 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001660}
1661
John McCall06549462011-01-18 08:40:38 +00001662/// getVariableArrayDecayedType - Turns the given type, which may be
1663/// variably-modified, into the corresponding type with all the known
1664/// sizes replaced with [*].
1665QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1666 // Vastly most common case.
1667 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001668
John McCall06549462011-01-18 08:40:38 +00001669 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001670
John McCall06549462011-01-18 08:40:38 +00001671 SplitQualType split = type.getSplitDesugaredType();
1672 const Type *ty = split.first;
1673 switch (ty->getTypeClass()) {
1674#define TYPE(Class, Base)
1675#define ABSTRACT_TYPE(Class, Base)
1676#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1677#include "clang/AST/TypeNodes.def"
1678 llvm_unreachable("didn't desugar past all non-canonical types?");
1679
1680 // These types should never be variably-modified.
1681 case Type::Builtin:
1682 case Type::Complex:
1683 case Type::Vector:
1684 case Type::ExtVector:
1685 case Type::DependentSizedExtVector:
1686 case Type::ObjCObject:
1687 case Type::ObjCInterface:
1688 case Type::ObjCObjectPointer:
1689 case Type::Record:
1690 case Type::Enum:
1691 case Type::UnresolvedUsing:
1692 case Type::TypeOfExpr:
1693 case Type::TypeOf:
1694 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001695 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001696 case Type::DependentName:
1697 case Type::InjectedClassName:
1698 case Type::TemplateSpecialization:
1699 case Type::DependentTemplateSpecialization:
1700 case Type::TemplateTypeParm:
1701 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001702 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001703 case Type::PackExpansion:
1704 llvm_unreachable("type should never be variably-modified");
1705
1706 // These types can be variably-modified but should never need to
1707 // further decay.
1708 case Type::FunctionNoProto:
1709 case Type::FunctionProto:
1710 case Type::BlockPointer:
1711 case Type::MemberPointer:
1712 return type;
1713
1714 // These types can be variably-modified. All these modifications
1715 // preserve structure except as noted by comments.
1716 // TODO: if we ever care about optimizing VLAs, there are no-op
1717 // optimizations available here.
1718 case Type::Pointer:
1719 result = getPointerType(getVariableArrayDecayedType(
1720 cast<PointerType>(ty)->getPointeeType()));
1721 break;
1722
1723 case Type::LValueReference: {
1724 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1725 result = getLValueReferenceType(
1726 getVariableArrayDecayedType(lv->getPointeeType()),
1727 lv->isSpelledAsLValue());
1728 break;
1729 }
1730
1731 case Type::RValueReference: {
1732 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1733 result = getRValueReferenceType(
1734 getVariableArrayDecayedType(lv->getPointeeType()));
1735 break;
1736 }
1737
Eli Friedman0dfb8892011-10-06 23:00:33 +00001738 case Type::Atomic: {
1739 const AtomicType *at = cast<AtomicType>(ty);
1740 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1741 break;
1742 }
1743
John McCall06549462011-01-18 08:40:38 +00001744 case Type::ConstantArray: {
1745 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1746 result = getConstantArrayType(
1747 getVariableArrayDecayedType(cat->getElementType()),
1748 cat->getSize(),
1749 cat->getSizeModifier(),
1750 cat->getIndexTypeCVRQualifiers());
1751 break;
1752 }
1753
1754 case Type::DependentSizedArray: {
1755 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1756 result = getDependentSizedArrayType(
1757 getVariableArrayDecayedType(dat->getElementType()),
1758 dat->getSizeExpr(),
1759 dat->getSizeModifier(),
1760 dat->getIndexTypeCVRQualifiers(),
1761 dat->getBracketsRange());
1762 break;
1763 }
1764
1765 // Turn incomplete types into [*] types.
1766 case Type::IncompleteArray: {
1767 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1768 result = getVariableArrayType(
1769 getVariableArrayDecayedType(iat->getElementType()),
1770 /*size*/ 0,
1771 ArrayType::Normal,
1772 iat->getIndexTypeCVRQualifiers(),
1773 SourceRange());
1774 break;
1775 }
1776
1777 // Turn VLA types into [*] types.
1778 case Type::VariableArray: {
1779 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1780 result = getVariableArrayType(
1781 getVariableArrayDecayedType(vat->getElementType()),
1782 /*size*/ 0,
1783 ArrayType::Star,
1784 vat->getIndexTypeCVRQualifiers(),
1785 vat->getBracketsRange());
1786 break;
1787 }
1788 }
1789
1790 // Apply the top-level qualifiers from the original.
1791 return getQualifiedType(result, split.second);
1792}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001793
Steve Naroffcadebd02007-08-30 18:14:25 +00001794/// getVariableArrayType - Returns a non-unique reference to the type for a
1795/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001796QualType ASTContext::getVariableArrayType(QualType EltTy,
1797 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001798 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001799 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001800 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001801 // Since we don't unique expressions, it isn't possible to unique VLA's
1802 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001803 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001804
John McCall33ddac02011-01-19 10:06:00 +00001805 // Be sure to pull qualifiers off the element type.
1806 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1807 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1808 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001809 IndexTypeQuals, Brackets);
John McCall33ddac02011-01-19 10:06:00 +00001810 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001811 }
1812
John McCall90d1c2d2009-09-24 23:30:46 +00001813 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001814 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001815
1816 VariableArrayTypes.push_back(New);
1817 Types.push_back(New);
1818 return QualType(New, 0);
1819}
1820
Douglas Gregor4619e432008-12-05 23:32:09 +00001821/// getDependentSizedArrayType - Returns a non-unique reference to
1822/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001823/// type.
John McCall33ddac02011-01-19 10:06:00 +00001824QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1825 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001826 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001827 unsigned elementTypeQuals,
1828 SourceRange brackets) const {
1829 assert((!numElements || numElements->isTypeDependent() ||
1830 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001831 "Size must be type- or value-dependent!");
1832
John McCall33ddac02011-01-19 10:06:00 +00001833 // Dependently-sized array types that do not have a specified number
1834 // of elements will have their sizes deduced from a dependent
1835 // initializer. We do no canonicalization here at all, which is okay
1836 // because they can't be used in most locations.
1837 if (!numElements) {
1838 DependentSizedArrayType *newType
1839 = new (*this, TypeAlignment)
1840 DependentSizedArrayType(*this, elementType, QualType(),
1841 numElements, ASM, elementTypeQuals,
1842 brackets);
1843 Types.push_back(newType);
1844 return QualType(newType, 0);
1845 }
1846
1847 // Otherwise, we actually build a new type every time, but we
1848 // also build a canonical type.
1849
1850 SplitQualType canonElementType = getCanonicalType(elementType).split();
1851
1852 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001853 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001854 DependentSizedArrayType::Profile(ID, *this,
1855 QualType(canonElementType.first, 0),
1856 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001857
John McCall33ddac02011-01-19 10:06:00 +00001858 // Look for an existing type with these properties.
1859 DependentSizedArrayType *canonTy =
1860 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001861
John McCall33ddac02011-01-19 10:06:00 +00001862 // If we don't have one, build one.
1863 if (!canonTy) {
1864 canonTy = new (*this, TypeAlignment)
1865 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1866 QualType(), numElements, ASM, elementTypeQuals,
1867 brackets);
1868 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1869 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001870 }
1871
John McCall33ddac02011-01-19 10:06:00 +00001872 // Apply qualifiers from the element type to the array.
1873 QualType canon = getQualifiedType(QualType(canonTy,0),
1874 canonElementType.second);
Mike Stump11289f42009-09-09 15:08:12 +00001875
John McCall33ddac02011-01-19 10:06:00 +00001876 // If we didn't need extra canonicalization for the element type,
1877 // then just use that as our result.
1878 if (QualType(canonElementType.first, 0) == elementType)
1879 return canon;
1880
1881 // Otherwise, we need to build a type which follows the spelling
1882 // of the element type.
1883 DependentSizedArrayType *sugaredType
1884 = new (*this, TypeAlignment)
1885 DependentSizedArrayType(*this, elementType, canon, numElements,
1886 ASM, elementTypeQuals, brackets);
1887 Types.push_back(sugaredType);
1888 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00001889}
1890
John McCall33ddac02011-01-19 10:06:00 +00001891QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00001892 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001893 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001894 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001895 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001896
John McCall33ddac02011-01-19 10:06:00 +00001897 void *insertPos = 0;
1898 if (IncompleteArrayType *iat =
1899 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1900 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00001901
1902 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00001903 // either, so fill in the canonical type field. We also have to pull
1904 // qualifiers off the element type.
1905 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00001906
John McCall33ddac02011-01-19 10:06:00 +00001907 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1908 SplitQualType canonSplit = getCanonicalType(elementType).split();
1909 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1910 ASM, elementTypeQuals);
1911 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanbd258282008-02-15 18:16:39 +00001912
1913 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00001914 IncompleteArrayType *existing =
1915 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1916 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001917 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001918
John McCall33ddac02011-01-19 10:06:00 +00001919 IncompleteArrayType *newType = new (*this, TypeAlignment)
1920 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001921
John McCall33ddac02011-01-19 10:06:00 +00001922 IncompleteArrayTypes.InsertNode(newType, insertPos);
1923 Types.push_back(newType);
1924 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001925}
1926
Steve Naroff91fcddb2007-07-18 18:00:27 +00001927/// getVectorType - Return the unique reference to a vector type of
1928/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001929QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001930 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00001931 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001932
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001933 // Check if we've already instantiated a vector of this type.
1934 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001935 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001936
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001937 void *InsertPos = 0;
1938 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1939 return QualType(VTP, 0);
1940
1941 // If the element type isn't canonical, this won't be a canonical type either,
1942 // so fill in the canonical type field.
1943 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001944 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001945 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001946
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001947 // Get the new insert position for the node we care about.
1948 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001949 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001950 }
John McCall90d1c2d2009-09-24 23:30:46 +00001951 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001952 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001953 VectorTypes.InsertNode(New, InsertPos);
1954 Types.push_back(New);
1955 return QualType(New, 0);
1956}
1957
Nate Begemance4d7fc2008-04-18 23:10:10 +00001958/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001959/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00001960QualType
1961ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00001962 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00001963
Steve Naroff91fcddb2007-07-18 18:00:27 +00001964 // Check if we've already instantiated a vector of this type.
1965 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001966 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001967 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001968 void *InsertPos = 0;
1969 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1970 return QualType(VTP, 0);
1971
1972 // If the element type isn't canonical, this won't be a canonical type either,
1973 // so fill in the canonical type field.
1974 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001975 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001976 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001977
Steve Naroff91fcddb2007-07-18 18:00:27 +00001978 // Get the new insert position for the node we care about.
1979 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001980 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001981 }
John McCall90d1c2d2009-09-24 23:30:46 +00001982 ExtVectorType *New = new (*this, TypeAlignment)
1983 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001984 VectorTypes.InsertNode(New, InsertPos);
1985 Types.push_back(New);
1986 return QualType(New, 0);
1987}
1988
Jay Foad39c79802011-01-12 09:06:06 +00001989QualType
1990ASTContext::getDependentSizedExtVectorType(QualType vecType,
1991 Expr *SizeExpr,
1992 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00001993 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001994 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001995 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001996
Douglas Gregor352169a2009-07-31 03:54:25 +00001997 void *InsertPos = 0;
1998 DependentSizedExtVectorType *Canon
1999 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2000 DependentSizedExtVectorType *New;
2001 if (Canon) {
2002 // We already have a canonical version of this array type; use it as
2003 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002004 New = new (*this, TypeAlignment)
2005 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2006 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002007 } else {
2008 QualType CanonVecTy = getCanonicalType(vecType);
2009 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002010 New = new (*this, TypeAlignment)
2011 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2012 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002013
2014 DependentSizedExtVectorType *CanonCheck
2015 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2016 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2017 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002018 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2019 } else {
2020 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2021 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002022 New = new (*this, TypeAlignment)
2023 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002024 }
2025 }
Mike Stump11289f42009-09-09 15:08:12 +00002026
Douglas Gregor758a8692009-06-17 21:51:59 +00002027 Types.push_back(New);
2028 return QualType(New, 0);
2029}
2030
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002031/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002032///
Jay Foad39c79802011-01-12 09:06:06 +00002033QualType
2034ASTContext::getFunctionNoProtoType(QualType ResultTy,
2035 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002036 const CallingConv DefaultCC = Info.getCC();
2037 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2038 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002039 // Unique functions, to guarantee there is only one function of a particular
2040 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002041 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002042 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002043
Chris Lattner47955de2007-01-27 08:37:20 +00002044 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002045 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002046 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002047 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002048
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002049 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002050 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002051 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002052 Canonical =
2053 getFunctionNoProtoType(getCanonicalType(ResultTy),
2054 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002055
Chris Lattner47955de2007-01-27 08:37:20 +00002056 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002057 FunctionNoProtoType *NewIP =
2058 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002059 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002060 }
Mike Stump11289f42009-09-09 15:08:12 +00002061
Roman Divacky65b88cd2011-03-01 17:40:53 +00002062 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002063 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002064 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002065 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002066 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002067 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002068}
2069
2070/// getFunctionType - Return a normal function type with a typed argument
2071/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002072QualType
2073ASTContext::getFunctionType(QualType ResultTy,
2074 const QualType *ArgArray, unsigned NumArgs,
2075 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002076 // Unique functions, to guarantee there is only one function of a particular
2077 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002078 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002079 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002080
2081 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002082 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002083 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002084 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002085
2086 // Determine whether the type being created is already canonical or not.
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002087 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002088 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002089 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002090 isCanonical = false;
2091
Roman Divacky65b88cd2011-03-01 17:40:53 +00002092 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2093 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2094 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002095
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002096 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002097 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002098 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002099 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002100 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002101 CanonicalArgs.reserve(NumArgs);
2102 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002103 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002104
John McCalldb40c7f2010-12-14 08:05:40 +00002105 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002106 CanonicalEPI.ExceptionSpecType = EST_None;
2107 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002108 CanonicalEPI.ExtInfo
2109 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2110
Chris Lattner76a00cf2008-04-06 22:59:24 +00002111 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002112 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002113 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002114
Chris Lattnerfd4de792007-01-27 01:15:32 +00002115 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002116 FunctionProtoType *NewIP =
2117 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002118 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002119 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002120
John McCall31168b02011-06-15 23:02:42 +00002121 // FunctionProtoType objects are allocated with extra bytes after
2122 // them for three variable size arrays at the end:
2123 // - parameter types
2124 // - exception types
2125 // - consumed-arguments flags
2126 // Instead of the exception types, there could be a noexcept
2127 // expression.
John McCalldb40c7f2010-12-14 08:05:40 +00002128 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002129 NumArgs * sizeof(QualType);
2130 if (EPI.ExceptionSpecType == EST_Dynamic)
2131 Size += EPI.NumExceptions * sizeof(QualType);
2132 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002133 Size += sizeof(Expr*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002134 }
John McCall31168b02011-06-15 23:02:42 +00002135 if (EPI.ConsumedArguments)
2136 Size += NumArgs * sizeof(bool);
2137
John McCalldb40c7f2010-12-14 08:05:40 +00002138 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002139 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2140 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002141 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002142 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002143 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002144 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002145}
Chris Lattneref51c202006-11-10 07:17:23 +00002146
John McCalle78aac42010-03-10 03:28:59 +00002147#ifndef NDEBUG
2148static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2149 if (!isa<CXXRecordDecl>(D)) return false;
2150 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2151 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2152 return true;
2153 if (RD->getDescribedClassTemplate() &&
2154 !isa<ClassTemplateSpecializationDecl>(RD))
2155 return true;
2156 return false;
2157}
2158#endif
2159
2160/// getInjectedClassNameType - Return the unique reference to the
2161/// injected class name type for the specified templated declaration.
2162QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002163 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002164 assert(NeedsInjectedClassNameType(Decl));
2165 if (Decl->TypeForDecl) {
2166 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00002167 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00002168 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2169 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2170 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2171 } else {
John McCall424cec92011-01-19 06:33:43 +00002172 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002173 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002174 Decl->TypeForDecl = newType;
2175 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002176 }
2177 return QualType(Decl->TypeForDecl, 0);
2178}
2179
Douglas Gregor83a586e2008-04-13 21:07:44 +00002180/// getTypeDeclType - Return the unique reference to the type for the
2181/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002182QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002183 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002184 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002185
Richard Smithdda56e42011-04-15 14:24:37 +00002186 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002187 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002188
John McCall96f0b5f2010-03-10 06:48:02 +00002189 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2190 "Template type parameter types are always available.");
2191
John McCall81e38502010-02-16 03:57:14 +00002192 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002193 assert(!Record->getPreviousDeclaration() &&
2194 "struct/union has previous declaration");
2195 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002196 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002197 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002198 assert(!Enum->getPreviousDeclaration() &&
2199 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002200 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002201 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002202 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002203 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2204 Decl->TypeForDecl = newType;
2205 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002206 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002207 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002208
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002209 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002210}
2211
Chris Lattner32d920b2007-01-26 02:01:53 +00002212/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002213/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002214QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002215ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2216 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002217 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002218
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002219 if (Canonical.isNull())
2220 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002221 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002222 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002223 Decl->TypeForDecl = newType;
2224 Types.push_back(newType);
2225 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002226}
2227
Jay Foad39c79802011-01-12 09:06:06 +00002228QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002229 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2230
2231 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2232 if (PrevDecl->TypeForDecl)
2233 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2234
John McCall424cec92011-01-19 06:33:43 +00002235 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2236 Decl->TypeForDecl = newType;
2237 Types.push_back(newType);
2238 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002239}
2240
Jay Foad39c79802011-01-12 09:06:06 +00002241QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002242 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2243
2244 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2245 if (PrevDecl->TypeForDecl)
2246 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2247
John McCall424cec92011-01-19 06:33:43 +00002248 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2249 Decl->TypeForDecl = newType;
2250 Types.push_back(newType);
2251 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002252}
2253
John McCall81904512011-01-06 01:58:22 +00002254QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2255 QualType modifiedType,
2256 QualType equivalentType) {
2257 llvm::FoldingSetNodeID id;
2258 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2259
2260 void *insertPos = 0;
2261 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2262 if (type) return QualType(type, 0);
2263
2264 QualType canon = getCanonicalType(equivalentType);
2265 type = new (*this, TypeAlignment)
2266 AttributedType(canon, attrKind, modifiedType, equivalentType);
2267
2268 Types.push_back(type);
2269 AttributedTypes.InsertNode(type, insertPos);
2270
2271 return QualType(type, 0);
2272}
2273
2274
John McCallcebee162009-10-18 09:09:24 +00002275/// \brief Retrieve a substitution-result type.
2276QualType
2277ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002278 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002279 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002280 && "replacement types must always be canonical");
2281
2282 llvm::FoldingSetNodeID ID;
2283 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2284 void *InsertPos = 0;
2285 SubstTemplateTypeParmType *SubstParm
2286 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2287
2288 if (!SubstParm) {
2289 SubstParm = new (*this, TypeAlignment)
2290 SubstTemplateTypeParmType(Parm, Replacement);
2291 Types.push_back(SubstParm);
2292 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2293 }
2294
2295 return QualType(SubstParm, 0);
2296}
2297
Douglas Gregorada4b792011-01-14 02:55:32 +00002298/// \brief Retrieve a
2299QualType ASTContext::getSubstTemplateTypeParmPackType(
2300 const TemplateTypeParmType *Parm,
2301 const TemplateArgument &ArgPack) {
2302#ifndef NDEBUG
2303 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2304 PEnd = ArgPack.pack_end();
2305 P != PEnd; ++P) {
2306 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2307 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2308 }
2309#endif
2310
2311 llvm::FoldingSetNodeID ID;
2312 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2313 void *InsertPos = 0;
2314 if (SubstTemplateTypeParmPackType *SubstParm
2315 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2316 return QualType(SubstParm, 0);
2317
2318 QualType Canon;
2319 if (!Parm->isCanonicalUnqualified()) {
2320 Canon = getCanonicalType(QualType(Parm, 0));
2321 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2322 ArgPack);
2323 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2324 }
2325
2326 SubstTemplateTypeParmPackType *SubstParm
2327 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2328 ArgPack);
2329 Types.push_back(SubstParm);
2330 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2331 return QualType(SubstParm, 0);
2332}
2333
Douglas Gregoreff93e02009-02-05 23:33:38 +00002334/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002335/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002336/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002337QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002338 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002339 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002340 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002341 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002342 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002343 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002344 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2345
2346 if (TypeParm)
2347 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002348
Chandler Carruth08836322011-05-01 00:51:33 +00002349 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002350 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002351 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002352
2353 TemplateTypeParmType *TypeCheck
2354 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2355 assert(!TypeCheck && "Template type parameter canonical type broken");
2356 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002357 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002358 TypeParm = new (*this, TypeAlignment)
2359 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002360
2361 Types.push_back(TypeParm);
2362 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2363
2364 return QualType(TypeParm, 0);
2365}
2366
John McCalle78aac42010-03-10 03:28:59 +00002367TypeSourceInfo *
2368ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2369 SourceLocation NameLoc,
2370 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002371 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002372 assert(!Name.getAsDependentTemplateName() &&
2373 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002374 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002375
2376 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2377 TemplateSpecializationTypeLoc TL
2378 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2379 TL.setTemplateNameLoc(NameLoc);
2380 TL.setLAngleLoc(Args.getLAngleLoc());
2381 TL.setRAngleLoc(Args.getRAngleLoc());
2382 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2383 TL.setArgLocInfo(i, Args[i].getLocInfo());
2384 return DI;
2385}
2386
Mike Stump11289f42009-09-09 15:08:12 +00002387QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002388ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002389 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002390 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002391 assert(!Template.getAsDependentTemplateName() &&
2392 "No dependent template names here!");
2393
John McCall6b51f282009-11-23 01:53:49 +00002394 unsigned NumArgs = Args.size();
2395
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002396 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002397 ArgVec.reserve(NumArgs);
2398 for (unsigned i = 0; i != NumArgs; ++i)
2399 ArgVec.push_back(Args[i].getArgument());
2400
John McCall2408e322010-04-27 00:57:59 +00002401 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002402 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002403}
2404
2405QualType
2406ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002407 const TemplateArgument *Args,
2408 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002409 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002410 assert(!Template.getAsDependentTemplateName() &&
2411 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002412 // Look through qualified template names.
2413 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2414 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002415
Richard Smith3f1b5d02011-05-05 21:57:07 +00002416 bool isTypeAlias =
2417 Template.getAsTemplateDecl() &&
2418 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2419
2420 QualType CanonType;
2421 if (!Underlying.isNull())
2422 CanonType = getCanonicalType(Underlying);
2423 else {
2424 assert(!isTypeAlias &&
2425 "Underlying type for template alias must be computed by caller");
2426 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2427 NumArgs);
2428 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002429
Douglas Gregora8e02e72009-07-28 23:00:59 +00002430 // Allocate the (non-canonical) template specialization type, but don't
2431 // try to unique it: these types typically have location information that
2432 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002433 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2434 sizeof(TemplateArgument) * NumArgs +
2435 (isTypeAlias ? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002436 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002437 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00002438 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00002439 Args, NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002440 CanonType,
2441 isTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002442
Douglas Gregor8bf42052009-02-09 18:46:07 +00002443 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002444 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002445}
2446
Mike Stump11289f42009-09-09 15:08:12 +00002447QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002448ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2449 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002450 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002451 assert(!Template.getAsDependentTemplateName() &&
2452 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002453 assert((!Template.getAsTemplateDecl() ||
2454 !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2455 "Underlying type for template alias must be computed by caller");
2456
Douglas Gregore29139c2011-03-03 17:04:51 +00002457 // Look through qualified template names.
2458 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2459 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002460
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002461 // Build the canonical template specialization type.
2462 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002463 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002464 CanonArgs.reserve(NumArgs);
2465 for (unsigned I = 0; I != NumArgs; ++I)
2466 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2467
2468 // Determine whether this canonical template specialization type already
2469 // exists.
2470 llvm::FoldingSetNodeID ID;
2471 TemplateSpecializationType::Profile(ID, CanonTemplate,
2472 CanonArgs.data(), NumArgs, *this);
2473
2474 void *InsertPos = 0;
2475 TemplateSpecializationType *Spec
2476 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2477
2478 if (!Spec) {
2479 // Allocate a new canonical template specialization type.
2480 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2481 sizeof(TemplateArgument) * NumArgs),
2482 TypeAlignment);
2483 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2484 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002485 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002486 Types.push_back(Spec);
2487 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2488 }
2489
2490 assert(Spec->isDependentType() &&
2491 "Non-dependent template-id type must have a canonical type");
2492 return QualType(Spec, 0);
2493}
2494
2495QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002496ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2497 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002498 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002499 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002500 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002501
2502 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002503 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002504 if (T)
2505 return QualType(T, 0);
2506
Douglas Gregorc42075a2010-02-04 18:10:26 +00002507 QualType Canon = NamedType;
2508 if (!Canon.isCanonical()) {
2509 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002510 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2511 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002512 (void)CheckT;
2513 }
2514
Abramo Bagnara6150c882010-05-11 21:36:43 +00002515 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002516 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002517 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002518 return QualType(T, 0);
2519}
2520
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002521QualType
Jay Foad39c79802011-01-12 09:06:06 +00002522ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002523 llvm::FoldingSetNodeID ID;
2524 ParenType::Profile(ID, InnerType);
2525
2526 void *InsertPos = 0;
2527 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2528 if (T)
2529 return QualType(T, 0);
2530
2531 QualType Canon = InnerType;
2532 if (!Canon.isCanonical()) {
2533 Canon = getCanonicalType(InnerType);
2534 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2535 assert(!CheckT && "Paren canonical type broken");
2536 (void)CheckT;
2537 }
2538
2539 T = new (*this) ParenType(InnerType, Canon);
2540 Types.push_back(T);
2541 ParenTypes.InsertNode(T, InsertPos);
2542 return QualType(T, 0);
2543}
2544
Douglas Gregor02085352010-03-31 20:19:30 +00002545QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2546 NestedNameSpecifier *NNS,
2547 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002548 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002549 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2550
2551 if (Canon.isNull()) {
2552 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002553 ElaboratedTypeKeyword CanonKeyword = Keyword;
2554 if (Keyword == ETK_None)
2555 CanonKeyword = ETK_Typename;
2556
2557 if (CanonNNS != NNS || CanonKeyword != Keyword)
2558 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002559 }
2560
2561 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002562 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002563
2564 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002565 DependentNameType *T
2566 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002567 if (T)
2568 return QualType(T, 0);
2569
Douglas Gregor02085352010-03-31 20:19:30 +00002570 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002571 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002572 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002573 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002574}
2575
Mike Stump11289f42009-09-09 15:08:12 +00002576QualType
John McCallc392f372010-06-11 00:33:02 +00002577ASTContext::getDependentTemplateSpecializationType(
2578 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002579 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002580 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002581 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002582 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002583 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002584 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2585 ArgCopy.push_back(Args[I].getArgument());
2586 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2587 ArgCopy.size(),
2588 ArgCopy.data());
2589}
2590
2591QualType
2592ASTContext::getDependentTemplateSpecializationType(
2593 ElaboratedTypeKeyword Keyword,
2594 NestedNameSpecifier *NNS,
2595 const IdentifierInfo *Name,
2596 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002597 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002598 assert((!NNS || NNS->isDependent()) &&
2599 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002600
Douglas Gregorc42075a2010-02-04 18:10:26 +00002601 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002602 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2603 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002604
2605 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002606 DependentTemplateSpecializationType *T
2607 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002608 if (T)
2609 return QualType(T, 0);
2610
John McCallc392f372010-06-11 00:33:02 +00002611 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002612
John McCallc392f372010-06-11 00:33:02 +00002613 ElaboratedTypeKeyword CanonKeyword = Keyword;
2614 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2615
2616 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002617 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002618 for (unsigned I = 0; I != NumArgs; ++I) {
2619 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2620 if (!CanonArgs[I].structurallyEquals(Args[I]))
2621 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002622 }
2623
John McCallc392f372010-06-11 00:33:02 +00002624 QualType Canon;
2625 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2626 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2627 Name, NumArgs,
2628 CanonArgs.data());
2629
2630 // Find the insert position again.
2631 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2632 }
2633
2634 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2635 sizeof(TemplateArgument) * NumArgs),
2636 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002637 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002638 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002639 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002640 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002641 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002642}
2643
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002644QualType ASTContext::getPackExpansionType(QualType Pattern,
2645 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002646 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002647 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002648
2649 assert(Pattern->containsUnexpandedParameterPack() &&
2650 "Pack expansions must expand one or more parameter packs");
2651 void *InsertPos = 0;
2652 PackExpansionType *T
2653 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2654 if (T)
2655 return QualType(T, 0);
2656
2657 QualType Canon;
2658 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002659 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002660
2661 // Find the insert position again.
2662 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2663 }
2664
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002665 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002666 Types.push_back(T);
2667 PackExpansionTypes.InsertNode(T, InsertPos);
2668 return QualType(T, 0);
2669}
2670
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002671/// CmpProtocolNames - Comparison predicate for sorting protocols
2672/// alphabetically.
2673static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2674 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002675 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002676}
2677
John McCall8b07ec22010-05-15 11:32:37 +00002678static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002679 unsigned NumProtocols) {
2680 if (NumProtocols == 0) return true;
2681
2682 for (unsigned i = 1; i != NumProtocols; ++i)
2683 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2684 return false;
2685 return true;
2686}
2687
2688static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002689 unsigned &NumProtocols) {
2690 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002691
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002692 // Sort protocols, keyed by name.
2693 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2694
2695 // Remove duplicates.
2696 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2697 NumProtocols = ProtocolsEnd-Protocols;
2698}
2699
John McCall8b07ec22010-05-15 11:32:37 +00002700QualType ASTContext::getObjCObjectType(QualType BaseType,
2701 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002702 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002703 // If the base type is an interface and there aren't any protocols
2704 // to add, then the interface type will do just fine.
2705 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2706 return BaseType;
2707
2708 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002709 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002710 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002711 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002712 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2713 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002714
John McCall8b07ec22010-05-15 11:32:37 +00002715 // Build the canonical type, which has the canonical base type and
2716 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002717 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002718 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2719 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2720 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002721 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002722 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002723 unsigned UniqueCount = NumProtocols;
2724
John McCallfc93cf92009-10-22 22:37:11 +00002725 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002726 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2727 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002728 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002729 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2730 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002731 }
2732
2733 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002734 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2735 }
2736
2737 unsigned Size = sizeof(ObjCObjectTypeImpl);
2738 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2739 void *Mem = Allocate(Size, TypeAlignment);
2740 ObjCObjectTypeImpl *T =
2741 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2742
2743 Types.push_back(T);
2744 ObjCObjectTypes.InsertNode(T, InsertPos);
2745 return QualType(T, 0);
2746}
2747
2748/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2749/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002750QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002751 llvm::FoldingSetNodeID ID;
2752 ObjCObjectPointerType::Profile(ID, ObjectT);
2753
2754 void *InsertPos = 0;
2755 if (ObjCObjectPointerType *QT =
2756 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2757 return QualType(QT, 0);
2758
2759 // Find the canonical object type.
2760 QualType Canonical;
2761 if (!ObjectT.isCanonical()) {
2762 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2763
2764 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002765 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2766 }
2767
Douglas Gregorf85bee62010-02-08 22:59:26 +00002768 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002769 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2770 ObjCObjectPointerType *QType =
2771 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002772
Steve Narofffb4330f2009-06-17 22:40:22 +00002773 Types.push_back(QType);
2774 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002775 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002776}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002777
Douglas Gregor1c283312010-08-11 12:19:30 +00002778/// getObjCInterfaceType - Return the unique reference to the type for the
2779/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad39c79802011-01-12 09:06:06 +00002780QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002781 if (Decl->TypeForDecl)
2782 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002783
Douglas Gregor1c283312010-08-11 12:19:30 +00002784 // FIXME: redeclarations?
2785 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2786 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2787 Decl->TypeForDecl = T;
2788 Types.push_back(T);
2789 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002790}
2791
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002792/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2793/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002794/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002795/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002796/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002797QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002798 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002799 if (tofExpr->isTypeDependent()) {
2800 llvm::FoldingSetNodeID ID;
2801 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002802
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002803 void *InsertPos = 0;
2804 DependentTypeOfExprType *Canon
2805 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2806 if (Canon) {
2807 // We already have a "canonical" version of an identical, dependent
2808 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002809 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002810 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002811 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002812 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002813 Canon
2814 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002815 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2816 toe = Canon;
2817 }
2818 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002819 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002820 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002821 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002822 Types.push_back(toe);
2823 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002824}
2825
Steve Naroffa773cd52007-08-01 18:02:17 +00002826/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2827/// TypeOfType AST's. The only motivation to unique these nodes would be
2828/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002829/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002830/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002831QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002832 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002833 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002834 Types.push_back(tot);
2835 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002836}
2837
Anders Carlssonad6bd352009-06-24 21:24:56 +00002838/// getDecltypeForExpr - Given an expr, will return the decltype for that
2839/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad39c79802011-01-12 09:06:06 +00002840static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002841 if (e->isTypeDependent())
2842 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002843
Anders Carlssonad6bd352009-06-24 21:24:56 +00002844 // If e is an id expression or a class member access, decltype(e) is defined
2845 // as the type of the entity named by e.
2846 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2847 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2848 return VD->getType();
2849 }
2850 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2851 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2852 return FD->getType();
2853 }
2854 // If e is a function call or an invocation of an overloaded operator,
2855 // (parentheses around e are ignored), decltype(e) is defined as the
2856 // return type of that function.
2857 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2858 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002859
Anders Carlssonad6bd352009-06-24 21:24:56 +00002860 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002861
2862 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002863 // defined as T&, otherwise decltype(e) is defined as T.
John McCall086a4642010-11-24 05:12:34 +00002864 if (e->isLValue())
Anders Carlssonad6bd352009-06-24 21:24:56 +00002865 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002866
Anders Carlssonad6bd352009-06-24 21:24:56 +00002867 return T;
2868}
2869
Anders Carlsson81df7b82009-06-24 19:06:50 +00002870/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2871/// DecltypeType AST's. The only motivation to unique these nodes would be
2872/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002873/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002874/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002875QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002876 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00002877
2878 // C++0x [temp.type]p2:
2879 // If an expression e involves a template parameter, decltype(e) denotes a
2880 // unique dependent type. Two such decltype-specifiers refer to the same
2881 // type only if their expressions are equivalent (14.5.6.1).
2882 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002883 llvm::FoldingSetNodeID ID;
2884 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002885
Douglas Gregora21f6c32009-07-30 23:36:40 +00002886 void *InsertPos = 0;
2887 DependentDecltypeType *Canon
2888 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2889 if (Canon) {
2890 // We already have a "canonical" version of an equivalent, dependent
2891 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002892 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002893 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002894 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002895 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002896 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002897 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2898 dt = Canon;
2899 }
2900 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002901 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002902 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002903 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002904 Types.push_back(dt);
2905 return QualType(dt, 0);
2906}
2907
Alexis Hunte852b102011-05-24 22:41:36 +00002908/// getUnaryTransformationType - We don't unique these, since the memory
2909/// savings are minimal and these are rare.
2910QualType ASTContext::getUnaryTransformType(QualType BaseType,
2911 QualType UnderlyingType,
2912 UnaryTransformType::UTTKind Kind)
2913 const {
2914 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00002915 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2916 Kind,
2917 UnderlyingType->isDependentType() ?
2918 QualType() : UnderlyingType);
Alexis Hunte852b102011-05-24 22:41:36 +00002919 Types.push_back(Ty);
2920 return QualType(Ty, 0);
2921}
2922
Richard Smithb2bc2e62011-02-21 20:05:19 +00002923/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00002924QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00002925 void *InsertPos = 0;
2926 if (!DeducedType.isNull()) {
2927 // Look in the folding set for an existing type.
2928 llvm::FoldingSetNodeID ID;
2929 AutoType::Profile(ID, DeducedType);
2930 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2931 return QualType(AT, 0);
2932 }
2933
2934 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2935 Types.push_back(AT);
2936 if (InsertPos)
2937 AutoTypes.InsertNode(AT, InsertPos);
2938 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00002939}
2940
Eli Friedman0dfb8892011-10-06 23:00:33 +00002941/// getAtomicType - Return the uniqued reference to the atomic type for
2942/// the given value type.
2943QualType ASTContext::getAtomicType(QualType T) const {
2944 // Unique pointers, to guarantee there is only one pointer of a particular
2945 // structure.
2946 llvm::FoldingSetNodeID ID;
2947 AtomicType::Profile(ID, T);
2948
2949 void *InsertPos = 0;
2950 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
2951 return QualType(AT, 0);
2952
2953 // If the atomic value type isn't canonical, this won't be a canonical type
2954 // either, so fill in the canonical type field.
2955 QualType Canonical;
2956 if (!T.isCanonical()) {
2957 Canonical = getAtomicType(getCanonicalType(T));
2958
2959 // Get the new insert position for the node we care about.
2960 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
2961 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2962 }
2963 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
2964 Types.push_back(New);
2965 AtomicTypes.InsertNode(New, InsertPos);
2966 return QualType(New, 0);
2967}
2968
Richard Smith02e85f32011-04-14 22:09:26 +00002969/// getAutoDeductType - Get type pattern for deducing against 'auto'.
2970QualType ASTContext::getAutoDeductType() const {
2971 if (AutoDeductTy.isNull())
2972 AutoDeductTy = getAutoType(QualType());
2973 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
2974 return AutoDeductTy;
2975}
2976
2977/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
2978QualType ASTContext::getAutoRRefDeductType() const {
2979 if (AutoRRefDeductTy.isNull())
2980 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
2981 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
2982 return AutoRRefDeductTy;
2983}
2984
Chris Lattnerfb072462007-01-23 05:45:31 +00002985/// getTagDeclType - Return the unique reference to the type for the
2986/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00002987QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002988 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002989 // FIXME: What is the design on getTagDeclType when it requires casting
2990 // away const? mutable?
2991 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002992}
2993
Mike Stump11289f42009-09-09 15:08:12 +00002994/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2995/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2996/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002997CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002998 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002999}
Chris Lattnerfb072462007-01-23 05:45:31 +00003000
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003001/// getSignedWCharType - Return the type of "signed wchar_t".
3002/// Used when in C++, as a GCC extension.
3003QualType ASTContext::getSignedWCharType() const {
3004 // FIXME: derive from "Target" ?
3005 return WCharTy;
3006}
3007
3008/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3009/// Used when in C++, as a GCC extension.
3010QualType ASTContext::getUnsignedWCharType() const {
3011 // FIXME: derive from "Target" ?
3012 return UnsignedIntTy;
3013}
3014
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003015/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
3016/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3017QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003018 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003019}
3020
Chris Lattnera21ad802008-04-02 05:18:44 +00003021//===----------------------------------------------------------------------===//
3022// Type Operators
3023//===----------------------------------------------------------------------===//
3024
Jay Foad39c79802011-01-12 09:06:06 +00003025CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003026 // Push qualifiers into arrays, and then discard any remaining
3027 // qualifiers.
3028 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003029 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003030 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003031 QualType Result;
3032 if (isa<ArrayType>(Ty)) {
3033 Result = getArrayDecayedType(QualType(Ty,0));
3034 } else if (isa<FunctionType>(Ty)) {
3035 Result = getPointerType(QualType(Ty, 0));
3036 } else {
3037 Result = QualType(Ty, 0);
3038 }
3039
3040 return CanQualType::CreateUnsafe(Result);
3041}
3042
John McCall6c9dd522011-01-18 07:41:22 +00003043QualType ASTContext::getUnqualifiedArrayType(QualType type,
3044 Qualifiers &quals) {
3045 SplitQualType splitType = type.getSplitUnqualifiedType();
3046
3047 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3048 // the unqualified desugared type and then drops it on the floor.
3049 // We then have to strip that sugar back off with
3050 // getUnqualifiedDesugaredType(), which is silly.
3051 const ArrayType *AT =
3052 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
3053
3054 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003055 if (!AT) {
John McCall6c9dd522011-01-18 07:41:22 +00003056 quals = splitType.second;
3057 return QualType(splitType.first, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003058 }
3059
John McCall6c9dd522011-01-18 07:41:22 +00003060 // Otherwise, recurse on the array's element type.
3061 QualType elementType = AT->getElementType();
3062 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3063
3064 // If that didn't change the element type, AT has no qualifiers, so we
3065 // can just use the results in splitType.
3066 if (elementType == unqualElementType) {
3067 assert(quals.empty()); // from the recursive call
3068 quals = splitType.second;
3069 return QualType(splitType.first, 0);
3070 }
3071
3072 // Otherwise, add in the qualifiers from the outermost type, then
3073 // build the type back up.
3074 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003075
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003076 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003077 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003078 CAT->getSizeModifier(), 0);
3079 }
3080
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003081 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003082 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003083 }
3084
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003085 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003086 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003087 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003088 VAT->getSizeModifier(),
3089 VAT->getIndexTypeCVRQualifiers(),
3090 VAT->getBracketsRange());
3091 }
3092
3093 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003094 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003095 DSAT->getSizeModifier(), 0,
3096 SourceRange());
3097}
3098
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003099/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3100/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3101/// they point to and return true. If T1 and T2 aren't pointer types
3102/// or pointer-to-member types, or if they are not similar at this
3103/// level, returns false and leaves T1 and T2 unchanged. Top-level
3104/// qualifiers on T1 and T2 are ignored. This function will typically
3105/// be called in a loop that successively "unwraps" pointer and
3106/// pointer-to-member types to compare them at each level.
3107bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3108 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3109 *T2PtrType = T2->getAs<PointerType>();
3110 if (T1PtrType && T2PtrType) {
3111 T1 = T1PtrType->getPointeeType();
3112 T2 = T2PtrType->getPointeeType();
3113 return true;
3114 }
3115
3116 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3117 *T2MPType = T2->getAs<MemberPointerType>();
3118 if (T1MPType && T2MPType &&
3119 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3120 QualType(T2MPType->getClass(), 0))) {
3121 T1 = T1MPType->getPointeeType();
3122 T2 = T2MPType->getPointeeType();
3123 return true;
3124 }
3125
3126 if (getLangOptions().ObjC1) {
3127 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3128 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3129 if (T1OPType && T2OPType) {
3130 T1 = T1OPType->getPointeeType();
3131 T2 = T2OPType->getPointeeType();
3132 return true;
3133 }
3134 }
3135
3136 // FIXME: Block pointers, too?
3137
3138 return false;
3139}
3140
Jay Foad39c79802011-01-12 09:06:06 +00003141DeclarationNameInfo
3142ASTContext::getNameForTemplate(TemplateName Name,
3143 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003144 switch (Name.getKind()) {
3145 case TemplateName::QualifiedTemplate:
3146 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003147 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003148 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3149 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003150
John McCalld9dfe3a2011-06-30 08:33:18 +00003151 case TemplateName::OverloadedTemplate: {
3152 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3153 // DNInfo work in progress: CHECKME: what about DNLoc?
3154 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3155 }
3156
3157 case TemplateName::DependentTemplate: {
3158 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003159 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003160 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003161 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3162 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003163 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003164 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3165 // DNInfo work in progress: FIXME: source locations?
3166 DeclarationNameLoc DNLoc;
3167 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3168 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3169 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003170 }
3171 }
3172
John McCalld9dfe3a2011-06-30 08:33:18 +00003173 case TemplateName::SubstTemplateTemplateParm: {
3174 SubstTemplateTemplateParmStorage *subst
3175 = Name.getAsSubstTemplateTemplateParm();
3176 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3177 NameLoc);
3178 }
3179
3180 case TemplateName::SubstTemplateTemplateParmPack: {
3181 SubstTemplateTemplateParmPackStorage *subst
3182 = Name.getAsSubstTemplateTemplateParmPack();
3183 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3184 NameLoc);
3185 }
3186 }
3187
3188 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003189}
3190
Jay Foad39c79802011-01-12 09:06:06 +00003191TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003192 switch (Name.getKind()) {
3193 case TemplateName::QualifiedTemplate:
3194 case TemplateName::Template: {
3195 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003196 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003197 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003198 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3199
3200 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003201 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003202 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003203
John McCalld9dfe3a2011-06-30 08:33:18 +00003204 case TemplateName::OverloadedTemplate:
3205 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003206
John McCalld9dfe3a2011-06-30 08:33:18 +00003207 case TemplateName::DependentTemplate: {
3208 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3209 assert(DTN && "Non-dependent template names must refer to template decls.");
3210 return DTN->CanonicalTemplateName;
3211 }
3212
3213 case TemplateName::SubstTemplateTemplateParm: {
3214 SubstTemplateTemplateParmStorage *subst
3215 = Name.getAsSubstTemplateTemplateParm();
3216 return getCanonicalTemplateName(subst->getReplacement());
3217 }
3218
3219 case TemplateName::SubstTemplateTemplateParmPack: {
3220 SubstTemplateTemplateParmPackStorage *subst
3221 = Name.getAsSubstTemplateTemplateParmPack();
3222 TemplateTemplateParmDecl *canonParameter
3223 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3224 TemplateArgument canonArgPack
3225 = getCanonicalTemplateArgument(subst->getArgumentPack());
3226 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3227 }
3228 }
3229
3230 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003231}
3232
Douglas Gregoradee3e32009-11-11 23:06:43 +00003233bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3234 X = getCanonicalTemplateName(X);
3235 Y = getCanonicalTemplateName(Y);
3236 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3237}
3238
Mike Stump11289f42009-09-09 15:08:12 +00003239TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003240ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003241 switch (Arg.getKind()) {
3242 case TemplateArgument::Null:
3243 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003244
Douglas Gregora8e02e72009-07-28 23:00:59 +00003245 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003246 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003247
Douglas Gregora8e02e72009-07-28 23:00:59 +00003248 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00003249 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003250
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003251 case TemplateArgument::Template:
3252 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003253
3254 case TemplateArgument::TemplateExpansion:
3255 return TemplateArgument(getCanonicalTemplateName(
3256 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003257 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003258
Douglas Gregora8e02e72009-07-28 23:00:59 +00003259 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00003260 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003261 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003262
Douglas Gregora8e02e72009-07-28 23:00:59 +00003263 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003264 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003265
Douglas Gregora8e02e72009-07-28 23:00:59 +00003266 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003267 if (Arg.pack_size() == 0)
3268 return Arg;
3269
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003270 TemplateArgument *CanonArgs
3271 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003272 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003273 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003274 AEnd = Arg.pack_end();
3275 A != AEnd; (void)++A, ++Idx)
3276 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003277
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003278 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003279 }
3280 }
3281
3282 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003283 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003284}
3285
Douglas Gregor333489b2009-03-27 23:10:48 +00003286NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003287ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003288 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003289 return 0;
3290
3291 switch (NNS->getKind()) {
3292 case NestedNameSpecifier::Identifier:
3293 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003294 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003295 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3296 NNS->getAsIdentifier());
3297
3298 case NestedNameSpecifier::Namespace:
3299 // A namespace is canonical; build a nested-name-specifier with
3300 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003301 return NestedNameSpecifier::Create(*this, 0,
3302 NNS->getAsNamespace()->getOriginalNamespace());
3303
3304 case NestedNameSpecifier::NamespaceAlias:
3305 // A namespace is canonical; build a nested-name-specifier with
3306 // this namespace and no prefix.
3307 return NestedNameSpecifier::Create(*this, 0,
3308 NNS->getAsNamespaceAlias()->getNamespace()
3309 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003310
3311 case NestedNameSpecifier::TypeSpec:
3312 case NestedNameSpecifier::TypeSpecWithTemplate: {
3313 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003314
3315 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3316 // break it apart into its prefix and identifier, then reconsititute those
3317 // as the canonical nested-name-specifier. This is required to canonicalize
3318 // a dependent nested-name-specifier involving typedefs of dependent-name
3319 // types, e.g.,
3320 // typedef typename T::type T1;
3321 // typedef typename T1::type T2;
3322 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3323 NestedNameSpecifier *Prefix
3324 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3325 return NestedNameSpecifier::Create(*this, Prefix,
3326 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3327 }
3328
Douglas Gregorcc10cbf2010-11-04 00:14:23 +00003329 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor3ade5702010-11-04 00:09:33 +00003330 if (const DependentTemplateSpecializationType *DTST
3331 = T->getAs<DependentTemplateSpecializationType>()) {
3332 NestedNameSpecifier *Prefix
3333 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregor6e068012011-02-28 00:04:36 +00003334
3335 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3336 Prefix, DTST->getIdentifier(),
3337 DTST->getNumArgs(),
3338 DTST->getArgs());
Douglas Gregor3ade5702010-11-04 00:09:33 +00003339 T = getCanonicalType(T);
3340 }
3341
John McCall33ddac02011-01-19 10:06:00 +00003342 return NestedNameSpecifier::Create(*this, 0, false,
3343 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003344 }
3345
3346 case NestedNameSpecifier::Global:
3347 // The global specifier is canonical and unique.
3348 return NNS;
3349 }
3350
3351 // Required to silence a GCC warning
3352 return 0;
3353}
3354
Chris Lattner7adf0762008-08-04 07:31:14 +00003355
Jay Foad39c79802011-01-12 09:06:06 +00003356const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003357 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003358 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003359 // Handle the common positive case fast.
3360 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3361 return AT;
3362 }
Mike Stump11289f42009-09-09 15:08:12 +00003363
John McCall8ccfcb52009-09-24 19:53:00 +00003364 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003365 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003366 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003367
John McCall8ccfcb52009-09-24 19:53:00 +00003368 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003369 // implements C99 6.7.3p8: "If the specification of an array type includes
3370 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003371
Chris Lattner7adf0762008-08-04 07:31:14 +00003372 // If we get here, we either have type qualifiers on the type, or we have
3373 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003374 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003375
John McCall33ddac02011-01-19 10:06:00 +00003376 SplitQualType split = T.getSplitDesugaredType();
3377 Qualifiers qs = split.second;
Mike Stump11289f42009-09-09 15:08:12 +00003378
Chris Lattner7adf0762008-08-04 07:31:14 +00003379 // If we have a simple case, just return now.
John McCall33ddac02011-01-19 10:06:00 +00003380 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3381 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003382 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003383
Chris Lattner7adf0762008-08-04 07:31:14 +00003384 // Otherwise, we have an array and we have qualifiers on it. Push the
3385 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003386 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003387
Chris Lattner7adf0762008-08-04 07:31:14 +00003388 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3389 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3390 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003391 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003392 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3393 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3394 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003395 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003396
Mike Stump11289f42009-09-09 15:08:12 +00003397 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003398 = dyn_cast<DependentSizedArrayType>(ATy))
3399 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003400 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003401 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003402 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003403 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003404 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003405
Chris Lattner7adf0762008-08-04 07:31:14 +00003406 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003407 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003408 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003409 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003410 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003411 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003412}
3413
Douglas Gregor84280642011-07-12 04:42:08 +00003414QualType ASTContext::getAdjustedParameterType(QualType T) {
3415 // C99 6.7.5.3p7:
3416 // A declaration of a parameter as "array of type" shall be
3417 // adjusted to "qualified pointer to type", where the type
3418 // qualifiers (if any) are those specified within the [ and ] of
3419 // the array type derivation.
3420 if (T->isArrayType())
3421 return getArrayDecayedType(T);
3422
3423 // C99 6.7.5.3p8:
3424 // A declaration of a parameter as "function returning type"
3425 // shall be adjusted to "pointer to function returning type", as
3426 // in 6.3.2.1.
3427 if (T->isFunctionType())
3428 return getPointerType(T);
3429
3430 return T;
3431}
3432
3433QualType ASTContext::getSignatureParameterType(QualType T) {
3434 T = getVariableArrayDecayedType(T);
3435 T = getAdjustedParameterType(T);
3436 return T.getUnqualifiedType();
3437}
3438
Chris Lattnera21ad802008-04-02 05:18:44 +00003439/// getArrayDecayedType - Return the properly qualified result of decaying the
3440/// specified array type to a pointer. This operation is non-trivial when
3441/// handling typedefs etc. The canonical type of "T" must be an array type,
3442/// this returns a pointer to a properly qualified element of the array.
3443///
3444/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003445QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003446 // Get the element type with 'getAsArrayType' so that we don't lose any
3447 // typedefs in the element type of the array. This also handles propagation
3448 // of type qualifiers from the array type into the element type if present
3449 // (C99 6.7.3p8).
3450 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3451 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003452
Chris Lattner7adf0762008-08-04 07:31:14 +00003453 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003454
3455 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003456 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003457}
3458
John McCall33ddac02011-01-19 10:06:00 +00003459QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3460 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003461}
3462
John McCall33ddac02011-01-19 10:06:00 +00003463QualType ASTContext::getBaseElementType(QualType type) const {
3464 Qualifiers qs;
3465 while (true) {
3466 SplitQualType split = type.getSplitDesugaredType();
3467 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3468 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003469
John McCall33ddac02011-01-19 10:06:00 +00003470 type = array->getElementType();
3471 qs.addConsistentQualifiers(split.second);
3472 }
Mike Stump11289f42009-09-09 15:08:12 +00003473
John McCall33ddac02011-01-19 10:06:00 +00003474 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003475}
3476
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003477/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003478uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003479ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3480 uint64_t ElementCount = 1;
3481 do {
3482 ElementCount *= CA->getSize().getZExtValue();
3483 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3484 } while (CA);
3485 return ElementCount;
3486}
3487
Steve Naroff0af91202007-04-27 21:51:21 +00003488/// getFloatingRank - Return a relative rank for floating point types.
3489/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003490static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003491 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003492 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003493
John McCall9dd450b2009-09-21 23:43:11 +00003494 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3495 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003496 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003497 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003498 case BuiltinType::Float: return FloatRank;
3499 case BuiltinType::Double: return DoubleRank;
3500 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003501 }
3502}
3503
Mike Stump11289f42009-09-09 15:08:12 +00003504/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3505/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003506/// 'typeDomain' is a real floating point or complex type.
3507/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003508QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3509 QualType Domain) const {
3510 FloatingRank EltRank = getFloatingRank(Size);
3511 if (Domain->isComplexType()) {
3512 switch (EltRank) {
David Blaikie83d382b2011-09-23 05:06:16 +00003513 default: llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00003514 case FloatRank: return FloatComplexTy;
3515 case DoubleRank: return DoubleComplexTy;
3516 case LongDoubleRank: return LongDoubleComplexTy;
3517 }
Steve Naroff0af91202007-04-27 21:51:21 +00003518 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003519
3520 assert(Domain->isRealFloatingType() && "Unknown domain!");
3521 switch (EltRank) {
David Blaikie83d382b2011-09-23 05:06:16 +00003522 default: llvm_unreachable("getFloatingRank(): illegal value for rank");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003523 case FloatRank: return FloatTy;
3524 case DoubleRank: return DoubleTy;
3525 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003526 }
Steve Naroffe4718892007-04-27 18:30:00 +00003527}
3528
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003529/// getFloatingTypeOrder - Compare the rank of the two specified floating
3530/// point types, ignoring the domain of the type (i.e. 'double' ==
3531/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003532/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003533int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003534 FloatingRank LHSR = getFloatingRank(LHS);
3535 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003536
Chris Lattnerb90739d2008-04-06 23:38:49 +00003537 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003538 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003539 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003540 return 1;
3541 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003542}
3543
Chris Lattner76a00cf2008-04-06 22:59:24 +00003544/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3545/// routine will assert if passed a built-in type that isn't an integer or enum,
3546/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003547unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003548 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCall424cec92011-01-19 06:33:43 +00003549 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00003550 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00003551
Chris Lattnerad3467e2010-12-25 23:25:43 +00003552 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3553 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Douglas Gregore8bbc122011-09-02 00:18:52 +00003554 T = getFromTargetType(Target->getWCharType()).getTypePtr();
Eli Friedmanc131d3b2009-07-05 23:44:27 +00003555
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003556 if (T->isSpecificBuiltinType(BuiltinType::Char16))
Douglas Gregore8bbc122011-09-02 00:18:52 +00003557 T = getFromTargetType(Target->getChar16Type()).getTypePtr();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003558
3559 if (T->isSpecificBuiltinType(BuiltinType::Char32))
Douglas Gregore8bbc122011-09-02 00:18:52 +00003560 T = getFromTargetType(Target->getChar32Type()).getTypePtr();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003561
Chris Lattner76a00cf2008-04-06 22:59:24 +00003562 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003563 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003564 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003565 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003566 case BuiltinType::Char_S:
3567 case BuiltinType::Char_U:
3568 case BuiltinType::SChar:
3569 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003570 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003571 case BuiltinType::Short:
3572 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003573 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003574 case BuiltinType::Int:
3575 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003576 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003577 case BuiltinType::Long:
3578 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003579 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003580 case BuiltinType::LongLong:
3581 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003582 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003583 case BuiltinType::Int128:
3584 case BuiltinType::UInt128:
3585 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003586 }
3587}
3588
Eli Friedman629ffb92009-08-20 04:21:42 +00003589/// \brief Whether this is a promotable bitfield reference according
3590/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3591///
3592/// \returns the type this bit-field will promote to, or NULL if no
3593/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003594QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003595 if (E->isTypeDependent() || E->isValueDependent())
3596 return QualType();
3597
Eli Friedman629ffb92009-08-20 04:21:42 +00003598 FieldDecl *Field = E->getBitField();
3599 if (!Field)
3600 return QualType();
3601
3602 QualType FT = Field->getType();
3603
Richard Smithcaf33902011-10-10 18:28:20 +00003604 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00003605 uint64_t IntSize = getTypeSize(IntTy);
3606 // GCC extension compatibility: if the bit-field size is less than or equal
3607 // to the size of int, it gets promoted no matter what its type is.
3608 // For instance, unsigned long bf : 4 gets promoted to signed int.
3609 if (BitWidth < IntSize)
3610 return IntTy;
3611
3612 if (BitWidth == IntSize)
3613 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3614
3615 // Types bigger than int are not subject to promotions, and therefore act
3616 // like the base type.
3617 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3618 // is ridiculous.
3619 return QualType();
3620}
3621
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003622/// getPromotedIntegerType - Returns the type that Promotable will
3623/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3624/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003625QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003626 assert(!Promotable.isNull());
3627 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003628 if (const EnumType *ET = Promotable->getAs<EnumType>())
3629 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003630 if (Promotable->isSignedIntegerType())
3631 return IntTy;
3632 uint64_t PromotableSize = getTypeSize(Promotable);
3633 uint64_t IntSize = getTypeSize(IntTy);
3634 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3635 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3636}
3637
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003638/// \brief Recurses in pointer/array types until it finds an objc retainable
3639/// type and returns its ownership.
3640Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3641 while (!T.isNull()) {
3642 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3643 return T.getObjCLifetime();
3644 if (T->isArrayType())
3645 T = getBaseElementType(T);
3646 else if (const PointerType *PT = T->getAs<PointerType>())
3647 T = PT->getPointeeType();
3648 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003649 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003650 else
3651 break;
3652 }
3653
3654 return Qualifiers::OCL_None;
3655}
3656
Mike Stump11289f42009-09-09 15:08:12 +00003657/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003658/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003659/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003660int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003661 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3662 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003663 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003664
Chris Lattner76a00cf2008-04-06 22:59:24 +00003665 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3666 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003667
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003668 unsigned LHSRank = getIntegerRank(LHSC);
3669 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003670
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003671 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3672 if (LHSRank == RHSRank) return 0;
3673 return LHSRank > RHSRank ? 1 : -1;
3674 }
Mike Stump11289f42009-09-09 15:08:12 +00003675
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003676 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3677 if (LHSUnsigned) {
3678 // If the unsigned [LHS] type is larger, return it.
3679 if (LHSRank >= RHSRank)
3680 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003681
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003682 // If the signed type can represent all values of the unsigned type, it
3683 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003684 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003685 return -1;
3686 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003687
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003688 // If the unsigned [RHS] type is larger, return it.
3689 if (RHSRank >= LHSRank)
3690 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003691
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003692 // If the signed type can represent all values of the unsigned type, it
3693 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003694 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003695 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003696}
Anders Carlsson98f07902007-08-17 05:31:46 +00003697
Anders Carlsson6d417272009-11-14 21:45:58 +00003698static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003699CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3700 DeclContext *DC, IdentifierInfo *Id) {
3701 SourceLocation Loc;
Anders Carlsson6d417272009-11-14 21:45:58 +00003702 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003703 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003704 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003705 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003706}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003707
Mike Stump11289f42009-09-09 15:08:12 +00003708// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003709QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003710 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003711 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003712 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003713 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003714 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003715
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003716 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003717
Anders Carlsson98f07902007-08-17 05:31:46 +00003718 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003719 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003720 // int flags;
3721 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003722 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003723 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003724 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003725 FieldTypes[3] = LongTy;
3726
Anders Carlsson98f07902007-08-17 05:31:46 +00003727 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003728 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003729 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003730 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003731 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003732 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003733 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003734 /*Mutable=*/false,
3735 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003736 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003737 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003738 }
3739
Douglas Gregord5058122010-02-11 01:19:42 +00003740 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003741 }
Mike Stump11289f42009-09-09 15:08:12 +00003742
Anders Carlsson98f07902007-08-17 05:31:46 +00003743 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003744}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003745
Douglas Gregor512b0772009-04-23 22:29:11 +00003746void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003747 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003748 assert(Rec && "Invalid CFConstantStringType");
3749 CFConstantStringTypeDecl = Rec->getDecl();
3750}
3751
Jay Foad39c79802011-01-12 09:06:06 +00003752QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003753 if (BlockDescriptorType)
3754 return getTagDeclType(BlockDescriptorType);
3755
3756 RecordDecl *T;
3757 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003758 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003759 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003760 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003761
3762 QualType FieldTypes[] = {
3763 UnsignedLongTy,
3764 UnsignedLongTy,
3765 };
3766
3767 const char *FieldNames[] = {
3768 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003769 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003770 };
3771
3772 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003773 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003774 SourceLocation(),
3775 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003776 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003777 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003778 /*Mutable=*/false,
3779 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003780 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003781 T->addDecl(Field);
3782 }
3783
Douglas Gregord5058122010-02-11 01:19:42 +00003784 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003785
3786 BlockDescriptorType = T;
3787
3788 return getTagDeclType(BlockDescriptorType);
3789}
3790
Jay Foad39c79802011-01-12 09:06:06 +00003791QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003792 if (BlockDescriptorExtendedType)
3793 return getTagDeclType(BlockDescriptorExtendedType);
3794
3795 RecordDecl *T;
3796 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003797 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003798 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003799 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003800
3801 QualType FieldTypes[] = {
3802 UnsignedLongTy,
3803 UnsignedLongTy,
3804 getPointerType(VoidPtrTy),
3805 getPointerType(VoidPtrTy)
3806 };
3807
3808 const char *FieldNames[] = {
3809 "reserved",
3810 "Size",
3811 "CopyFuncPtr",
3812 "DestroyFuncPtr"
3813 };
3814
3815 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003816 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003817 SourceLocation(),
3818 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003819 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003820 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003821 /*Mutable=*/false,
3822 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003823 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003824 T->addDecl(Field);
3825 }
3826
Douglas Gregord5058122010-02-11 01:19:42 +00003827 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003828
3829 BlockDescriptorExtendedType = T;
3830
3831 return getTagDeclType(BlockDescriptorExtendedType);
3832}
3833
Jay Foad39c79802011-01-12 09:06:06 +00003834bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00003835 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00003836 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003837 if (getLangOptions().CPlusPlus) {
3838 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3839 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00003840 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003841
3842 }
3843 }
Mike Stump94967902009-10-21 18:16:27 +00003844 return false;
3845}
3846
Jay Foad39c79802011-01-12 09:06:06 +00003847QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003848ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003849 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003850 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003851 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003852 // unsigned int __flags;
3853 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003854 // void *__copy_helper; // as needed
3855 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003856 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003857 // } *
3858
Mike Stump94967902009-10-21 18:16:27 +00003859 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3860
3861 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003862 llvm::SmallString<36> Name;
3863 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3864 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003865 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003866 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003867 T->startDefinition();
3868 QualType Int32Ty = IntTy;
3869 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3870 QualType FieldTypes[] = {
3871 getPointerType(VoidPtrTy),
3872 getPointerType(getTagDeclType(T)),
3873 Int32Ty,
3874 Int32Ty,
3875 getPointerType(VoidPtrTy),
3876 getPointerType(VoidPtrTy),
3877 Ty
3878 };
3879
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003880 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003881 "__isa",
3882 "__forwarding",
3883 "__flags",
3884 "__size",
3885 "__copy_helper",
3886 "__destroy_helper",
3887 DeclName,
3888 };
3889
3890 for (size_t i = 0; i < 7; ++i) {
3891 if (!HasCopyAndDispose && i >=4 && i <= 5)
3892 continue;
3893 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003894 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00003895 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003896 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003897 /*BitWidth=*/0, /*Mutable=*/false,
3898 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003899 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003900 T->addDecl(Field);
3901 }
3902
Douglas Gregord5058122010-02-11 01:19:42 +00003903 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003904
3905 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003906}
3907
Douglas Gregorbab8a962011-09-08 01:46:34 +00003908TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
3909 if (!ObjCInstanceTypeDecl)
3910 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
3911 getTranslationUnitDecl(),
3912 SourceLocation(),
3913 SourceLocation(),
3914 &Idents.get("instancetype"),
3915 getTrivialTypeSourceInfo(getObjCIdType()));
3916 return ObjCInstanceTypeDecl;
3917}
3918
Anders Carlsson18acd442007-10-29 06:33:42 +00003919// This returns true if a type has been typedefed to BOOL:
3920// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003921static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003922 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003923 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3924 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003925
Anders Carlssond8499822007-10-29 05:01:08 +00003926 return false;
3927}
3928
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003929/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003930/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00003931CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00003932 if (!type->isIncompleteArrayType() && type->isIncompleteType())
3933 return CharUnits::Zero();
3934
Ken Dyck40775002010-01-11 17:06:35 +00003935 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003936
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003937 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003938 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003939 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003940 // Treat arrays as pointers, since that's how they're passed in.
3941 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003942 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003943 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003944}
3945
3946static inline
3947std::string charUnitsToString(const CharUnits &CU) {
3948 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003949}
3950
John McCall351762c2011-02-07 10:33:21 +00003951/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003952/// declaration.
John McCall351762c2011-02-07 10:33:21 +00003953std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3954 std::string S;
3955
David Chisnall950a9512009-11-17 19:33:30 +00003956 const BlockDecl *Decl = Expr->getBlockDecl();
3957 QualType BlockTy =
3958 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3959 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003960 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003961 // Compute size of all parameters.
3962 // Start with computing size of a pointer in number of bytes.
3963 // FIXME: There might(should) be a better way of doing this computation!
3964 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003965 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3966 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003967 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003968 E = Decl->param_end(); PI != E; ++PI) {
3969 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003970 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003971 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003972 ParmOffset += sz;
3973 }
3974 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003975 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003976 // Block pointer and offset.
3977 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00003978
3979 // Argument types.
3980 ParmOffset = PtrSize;
3981 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3982 Decl->param_end(); PI != E; ++PI) {
3983 ParmVarDecl *PVDecl = *PI;
3984 QualType PType = PVDecl->getOriginalType();
3985 if (const ArrayType *AT =
3986 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3987 // Use array's original type only if it has known number of
3988 // elements.
3989 if (!isa<ConstantArrayType>(AT))
3990 PType = PVDecl->getType();
3991 } else if (PType->isFunctionType())
3992 PType = PVDecl->getType();
3993 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003994 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003995 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003996 }
John McCall351762c2011-02-07 10:33:21 +00003997
3998 return S;
David Chisnall950a9512009-11-17 19:33:30 +00003999}
4000
Douglas Gregora9d84932011-05-27 01:19:52 +00004001bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004002 std::string& S) {
4003 // Encode result type.
4004 getObjCEncodingForType(Decl->getResultType(), S);
4005 CharUnits ParmOffset;
4006 // Compute size of all parameters.
4007 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4008 E = Decl->param_end(); PI != E; ++PI) {
4009 QualType PType = (*PI)->getType();
4010 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004011 if (sz.isZero())
4012 return true;
4013
David Chisnall50e4eba2010-12-30 14:05:53 +00004014 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004015 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004016 ParmOffset += sz;
4017 }
4018 S += charUnitsToString(ParmOffset);
4019 ParmOffset = CharUnits::Zero();
4020
4021 // Argument types.
4022 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4023 E = Decl->param_end(); PI != E; ++PI) {
4024 ParmVarDecl *PVDecl = *PI;
4025 QualType PType = PVDecl->getOriginalType();
4026 if (const ArrayType *AT =
4027 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4028 // Use array's original type only if it has known number of
4029 // elements.
4030 if (!isa<ConstantArrayType>(AT))
4031 PType = PVDecl->getType();
4032 } else if (PType->isFunctionType())
4033 PType = PVDecl->getType();
4034 getObjCEncodingForType(PType, S);
4035 S += charUnitsToString(ParmOffset);
4036 ParmOffset += getObjCEncodingTypeSize(PType);
4037 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004038
4039 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004040}
4041
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004042/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004043/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004044bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00004045 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004046 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004047 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004048 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004049 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004050 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004051 // Compute size of all parameters.
4052 // Start with computing size of a pointer in number of bytes.
4053 // FIXME: There might(should) be a better way of doing this computation!
4054 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004055 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004056 // The first two arguments (self and _cmd) are pointers; account for
4057 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004058 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004059 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004060 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004061 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004062 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004063 if (sz.isZero())
4064 return true;
4065
Ken Dyck40775002010-01-11 17:06:35 +00004066 assert (sz.isPositive() &&
4067 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004068 ParmOffset += sz;
4069 }
Ken Dyck40775002010-01-11 17:06:35 +00004070 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004071 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004072 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004073
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004074 // Argument types.
4075 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004076 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004077 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004078 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004079 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004080 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004081 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4082 // Use array's original type only if it has known number of
4083 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004084 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004085 PType = PVDecl->getType();
4086 } else if (PType->isFunctionType())
4087 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004088 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004089 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004090 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004091 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004092 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004093 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004094 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004095
4096 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004097}
4098
Daniel Dunbar4932b362008-08-28 04:38:10 +00004099/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004100/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004101/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4102/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004103/// Property attributes are stored as a comma-delimited C string. The simple
4104/// attributes readonly and bycopy are encoded as single characters. The
4105/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4106/// encoded as single characters, followed by an identifier. Property types
4107/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004108/// these attributes are defined by the following enumeration:
4109/// @code
4110/// enum PropertyAttributes {
4111/// kPropertyReadOnly = 'R', // property is read-only.
4112/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4113/// kPropertyByref = '&', // property is a reference to the value last assigned
4114/// kPropertyDynamic = 'D', // property is dynamic
4115/// kPropertyGetter = 'G', // followed by getter selector name
4116/// kPropertySetter = 'S', // followed by setter selector name
4117/// kPropertyInstanceVariable = 'V' // followed by instance variable name
4118/// kPropertyType = 't' // followed by old-style type encoding.
4119/// kPropertyWeak = 'W' // 'weak' property
4120/// kPropertyStrong = 'P' // property GC'able
4121/// kPropertyNonAtomic = 'N' // property non-atomic
4122/// };
4123/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004124void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004125 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004126 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004127 // Collect information from the property implementation decl(s).
4128 bool Dynamic = false;
4129 ObjCPropertyImplDecl *SynthesizePID = 0;
4130
4131 // FIXME: Duplicated code due to poor abstraction.
4132 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004133 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004134 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4135 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004136 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004137 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004138 ObjCPropertyImplDecl *PID = *i;
4139 if (PID->getPropertyDecl() == PD) {
4140 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4141 Dynamic = true;
4142 } else {
4143 SynthesizePID = PID;
4144 }
4145 }
4146 }
4147 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004148 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004149 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004150 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004151 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004152 ObjCPropertyImplDecl *PID = *i;
4153 if (PID->getPropertyDecl() == PD) {
4154 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4155 Dynamic = true;
4156 } else {
4157 SynthesizePID = PID;
4158 }
4159 }
Mike Stump11289f42009-09-09 15:08:12 +00004160 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004161 }
4162 }
4163
4164 // FIXME: This is not very efficient.
4165 S = "T";
4166
4167 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004168 // GCC has some special rules regarding encoding of properties which
4169 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004170 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004171 true /* outermost type */,
4172 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004173
4174 if (PD->isReadOnly()) {
4175 S += ",R";
4176 } else {
4177 switch (PD->getSetterKind()) {
4178 case ObjCPropertyDecl::Assign: break;
4179 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004180 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004181 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004182 }
4183 }
4184
4185 // It really isn't clear at all what this means, since properties
4186 // are "dynamic by default".
4187 if (Dynamic)
4188 S += ",D";
4189
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004190 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4191 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004192
Daniel Dunbar4932b362008-08-28 04:38:10 +00004193 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4194 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004195 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004196 }
4197
4198 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4199 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004200 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004201 }
4202
4203 if (SynthesizePID) {
4204 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4205 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004206 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004207 }
4208
4209 // FIXME: OBJCGC: weak & strong
4210}
4211
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004212/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004213/// Another legacy compatibility encoding: 32-bit longs are encoded as
4214/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004215/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4216///
4217void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004218 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004219 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004220 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004221 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004222 else
Jay Foad39c79802011-01-12 09:06:06 +00004223 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004224 PointeeTy = IntTy;
4225 }
4226 }
4227}
4228
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004229void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004230 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004231 // We follow the behavior of gcc, expanding structures which are
4232 // directly pointed to, and expanding embedded structures. Note that
4233 // these rules are sufficient to prevent recursive encoding of the
4234 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004235 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004236 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004237}
4238
David Chisnallb190a2c2010-06-04 01:10:52 +00004239static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4240 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004241 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004242 case BuiltinType::Void: return 'v';
4243 case BuiltinType::Bool: return 'B';
4244 case BuiltinType::Char_U:
4245 case BuiltinType::UChar: return 'C';
4246 case BuiltinType::UShort: return 'S';
4247 case BuiltinType::UInt: return 'I';
4248 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004249 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004250 case BuiltinType::UInt128: return 'T';
4251 case BuiltinType::ULongLong: return 'Q';
4252 case BuiltinType::Char_S:
4253 case BuiltinType::SChar: return 'c';
4254 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004255 case BuiltinType::WChar_S:
4256 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004257 case BuiltinType::Int: return 'i';
4258 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004259 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004260 case BuiltinType::LongLong: return 'q';
4261 case BuiltinType::Int128: return 't';
4262 case BuiltinType::Float: return 'f';
4263 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004264 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004265 }
4266}
4267
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004268static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4269 EnumDecl *Enum = ET->getDecl();
4270
4271 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4272 if (!Enum->isFixed())
4273 return 'i';
4274
4275 // The encoding of a fixed enum type matches its fixed underlying type.
4276 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4277}
4278
Jay Foad39c79802011-01-12 09:06:06 +00004279static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004280 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004281 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004282 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004283 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4284 // The GNU runtime requires more information; bitfields are encoded as b,
4285 // then the offset (in bits) of the first element, then the type of the
4286 // bitfield, then the size in bits. For example, in this structure:
4287 //
4288 // struct
4289 // {
4290 // int integer;
4291 // int flags:2;
4292 // };
4293 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4294 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4295 // information is not especially sensible, but we're stuck with it for
4296 // compatibility with GCC, although providing it breaks anything that
4297 // actually uses runtime introspection and wants to work on both runtimes...
4298 if (!Ctx->getLangOptions().NeXTRuntime) {
4299 const RecordDecl *RD = FD->getParent();
4300 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004301 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004302 if (const EnumType *ET = T->getAs<EnumType>())
4303 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004304 else
Jay Foad39c79802011-01-12 09:06:06 +00004305 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004306 }
Richard Smithcaf33902011-10-10 18:28:20 +00004307 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004308}
4309
Daniel Dunbar07d07852009-10-18 21:17:35 +00004310// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004311void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4312 bool ExpandPointedToStructures,
4313 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004314 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004315 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004316 bool EncodingProperty,
4317 bool StructField) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004318 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004319 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004320 return EncodeBitField(this, S, T, FD);
4321 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004322 return;
4323 }
Mike Stump11289f42009-09-09 15:08:12 +00004324
John McCall9dd450b2009-09-21 23:43:11 +00004325 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004326 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004327 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004328 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004329 return;
4330 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004331
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004332 // encoding for pointer or r3eference types.
4333 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004334 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004335 if (PT->isObjCSelType()) {
4336 S += ':';
4337 return;
4338 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004339 PointeeTy = PT->getPointeeType();
4340 }
4341 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4342 PointeeTy = RT->getPointeeType();
4343 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004344 bool isReadOnly = false;
4345 // For historical/compatibility reasons, the read-only qualifier of the
4346 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4347 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004348 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004349 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004350 if (OutermostType && T.isConstQualified()) {
4351 isReadOnly = true;
4352 S += 'r';
4353 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004354 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004355 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004356 while (P->getAs<PointerType>())
4357 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004358 if (P.isConstQualified()) {
4359 isReadOnly = true;
4360 S += 'r';
4361 }
4362 }
4363 if (isReadOnly) {
4364 // Another legacy compatibility encoding. Some ObjC qualifier and type
4365 // combinations need to be rearranged.
4366 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004367 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004368 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004369 }
Mike Stump11289f42009-09-09 15:08:12 +00004370
Anders Carlssond8499822007-10-29 05:01:08 +00004371 if (PointeeTy->isCharType()) {
4372 // char pointer types should be encoded as '*' unless it is a
4373 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004374 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004375 S += '*';
4376 return;
4377 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004378 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004379 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4380 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4381 S += '#';
4382 return;
4383 }
4384 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4385 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4386 S += '@';
4387 return;
4388 }
4389 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004390 }
Anders Carlssond8499822007-10-29 05:01:08 +00004391 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004392 getLegacyIntegralTypeEncoding(PointeeTy);
4393
Mike Stump11289f42009-09-09 15:08:12 +00004394 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004395 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004396 return;
4397 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004398
Chris Lattnere7cabb92009-07-13 00:10:46 +00004399 if (const ArrayType *AT =
4400 // Ignore type qualifiers etc.
4401 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004402 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004403 // Incomplete arrays are encoded as a pointer to the array element.
4404 S += '^';
4405
Mike Stump11289f42009-09-09 15:08:12 +00004406 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004407 false, ExpandStructures, FD);
4408 } else {
4409 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004410
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004411 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4412 if (getTypeSize(CAT->getElementType()) == 0)
4413 S += '0';
4414 else
4415 S += llvm::utostr(CAT->getSize().getZExtValue());
4416 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004417 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004418 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4419 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004420 S += '0';
4421 }
Mike Stump11289f42009-09-09 15:08:12 +00004422
4423 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004424 false, ExpandStructures, FD);
4425 S += ']';
4426 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004427 return;
4428 }
Mike Stump11289f42009-09-09 15:08:12 +00004429
John McCall9dd450b2009-09-21 23:43:11 +00004430 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004431 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004432 return;
4433 }
Mike Stump11289f42009-09-09 15:08:12 +00004434
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004435 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004436 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004437 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004438 // Anonymous structures print as '?'
4439 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4440 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004441 if (ClassTemplateSpecializationDecl *Spec
4442 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4443 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4444 std::string TemplateArgsStr
4445 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004446 TemplateArgs.data(),
4447 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004448 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004449
4450 S += TemplateArgsStr;
4451 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004452 } else {
4453 S += '?';
4454 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004455 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004456 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004457 if (!RDecl->isUnion()) {
4458 getObjCEncodingForStructureImpl(RDecl, S, FD);
4459 } else {
4460 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4461 FieldEnd = RDecl->field_end();
4462 Field != FieldEnd; ++Field) {
4463 if (FD) {
4464 S += '"';
4465 S += Field->getNameAsString();
4466 S += '"';
4467 }
Mike Stump11289f42009-09-09 15:08:12 +00004468
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004469 // Special case bit-fields.
4470 if (Field->isBitField()) {
4471 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4472 (*Field));
4473 } else {
4474 QualType qt = Field->getType();
4475 getLegacyIntegralTypeEncoding(qt);
4476 getObjCEncodingForTypeImpl(qt, S, false, true,
4477 FD, /*OutermostType*/false,
4478 /*EncodingProperty*/false,
4479 /*StructField*/true);
4480 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004481 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004482 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004483 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004484 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004485 return;
4486 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004487
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004488 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004489 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004490 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004491 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004492 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004493 return;
4494 }
Mike Stump11289f42009-09-09 15:08:12 +00004495
Chris Lattnere7cabb92009-07-13 00:10:46 +00004496 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004497 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00004498 return;
4499 }
Mike Stump11289f42009-09-09 15:08:12 +00004500
John McCall8b07ec22010-05-15 11:32:37 +00004501 // Ignore protocol qualifiers when mangling at this level.
4502 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4503 T = OT->getBaseType();
4504
John McCall8ccfcb52009-09-24 19:53:00 +00004505 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004506 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004507 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004508 S += '{';
4509 const IdentifierInfo *II = OI->getIdentifier();
4510 S += II->getName();
4511 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004512 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004513 DeepCollectObjCIvars(OI, true, Ivars);
4514 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004515 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004516 if (Field->isBitField())
4517 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004518 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004519 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004520 }
4521 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004522 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004523 }
Mike Stump11289f42009-09-09 15:08:12 +00004524
John McCall9dd450b2009-09-21 23:43:11 +00004525 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004526 if (OPT->isObjCIdType()) {
4527 S += '@';
4528 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004529 }
Mike Stump11289f42009-09-09 15:08:12 +00004530
Steve Narofff0c86112009-10-28 22:03:49 +00004531 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4532 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4533 // Since this is a binary compatibility issue, need to consult with runtime
4534 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004535 S += '#';
4536 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004537 }
Mike Stump11289f42009-09-09 15:08:12 +00004538
Chris Lattnere7cabb92009-07-13 00:10:46 +00004539 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004540 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004541 ExpandPointedToStructures,
4542 ExpandStructures, FD);
4543 if (FD || EncodingProperty) {
4544 // Note that we do extended encoding of protocol qualifer list
4545 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004546 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004547 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4548 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004549 S += '<';
4550 S += (*I)->getNameAsString();
4551 S += '>';
4552 }
4553 S += '"';
4554 }
4555 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004556 }
Mike Stump11289f42009-09-09 15:08:12 +00004557
Chris Lattnere7cabb92009-07-13 00:10:46 +00004558 QualType PointeeTy = OPT->getPointeeType();
4559 if (!EncodingProperty &&
4560 isa<TypedefType>(PointeeTy.getTypePtr())) {
4561 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004562 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004563 // {...};
4564 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004565 getObjCEncodingForTypeImpl(PointeeTy, S,
4566 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004567 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004568 return;
4569 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004570
4571 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00004572 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004573 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004574 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004575 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4576 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004577 S += '<';
4578 S += (*I)->getNameAsString();
4579 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004580 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004581 S += '"';
4582 }
4583 return;
4584 }
Mike Stump11289f42009-09-09 15:08:12 +00004585
John McCalla9e6e8d2010-05-17 23:56:34 +00004586 // gcc just blithely ignores member pointers.
4587 // TODO: maybe there should be a mangling for these
4588 if (T->getAs<MemberPointerType>())
4589 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004590
4591 if (T->isVectorType()) {
4592 // This matches gcc's encoding, even though technically it is
4593 // insufficient.
4594 // FIXME. We should do a better job than gcc.
4595 return;
4596 }
4597
David Blaikie83d382b2011-09-23 05:06:16 +00004598 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004599}
4600
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004601void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4602 std::string &S,
4603 const FieldDecl *FD,
4604 bool includeVBases) const {
4605 assert(RDecl && "Expected non-null RecordDecl");
4606 assert(!RDecl->isUnion() && "Should not be called for unions");
4607 if (!RDecl->getDefinition())
4608 return;
4609
4610 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4611 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4612 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4613
4614 if (CXXRec) {
4615 for (CXXRecordDecl::base_class_iterator
4616 BI = CXXRec->bases_begin(),
4617 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4618 if (!BI->isVirtual()) {
4619 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004620 if (base->isEmpty())
4621 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004622 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4623 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4624 std::make_pair(offs, base));
4625 }
4626 }
4627 }
4628
4629 unsigned i = 0;
4630 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4631 FieldEnd = RDecl->field_end();
4632 Field != FieldEnd; ++Field, ++i) {
4633 uint64_t offs = layout.getFieldOffset(i);
4634 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4635 std::make_pair(offs, *Field));
4636 }
4637
4638 if (CXXRec && includeVBases) {
4639 for (CXXRecordDecl::base_class_iterator
4640 BI = CXXRec->vbases_begin(),
4641 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4642 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004643 if (base->isEmpty())
4644 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004645 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00004646 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4647 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4648 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004649 }
4650 }
4651
4652 CharUnits size;
4653 if (CXXRec) {
4654 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4655 } else {
4656 size = layout.getSize();
4657 }
4658
4659 uint64_t CurOffs = 0;
4660 std::multimap<uint64_t, NamedDecl *>::iterator
4661 CurLayObj = FieldOrBaseOffsets.begin();
4662
Argyrios Kyrtzidisc7e50c52011-08-22 16:03:14 +00004663 if ((CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) ||
4664 (CurLayObj == FieldOrBaseOffsets.end() &&
4665 CXXRec && CXXRec->isDynamicClass())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004666 assert(CXXRec && CXXRec->isDynamicClass() &&
4667 "Offset 0 was empty but no VTable ?");
4668 if (FD) {
4669 S += "\"_vptr$";
4670 std::string recname = CXXRec->getNameAsString();
4671 if (recname.empty()) recname = "?";
4672 S += recname;
4673 S += '"';
4674 }
4675 S += "^^?";
4676 CurOffs += getTypeSize(VoidPtrTy);
4677 }
4678
4679 if (!RDecl->hasFlexibleArrayMember()) {
4680 // Mark the end of the structure.
4681 uint64_t offs = toBits(size);
4682 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4683 std::make_pair(offs, (NamedDecl*)0));
4684 }
4685
4686 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4687 assert(CurOffs <= CurLayObj->first);
4688
4689 if (CurOffs < CurLayObj->first) {
4690 uint64_t padding = CurLayObj->first - CurOffs;
4691 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4692 // packing/alignment of members is different that normal, in which case
4693 // the encoding will be out-of-sync with the real layout.
4694 // If the runtime switches to just consider the size of types without
4695 // taking into account alignment, we could make padding explicit in the
4696 // encoding (e.g. using arrays of chars). The encoding strings would be
4697 // longer then though.
4698 CurOffs += padding;
4699 }
4700
4701 NamedDecl *dcl = CurLayObj->second;
4702 if (dcl == 0)
4703 break; // reached end of structure.
4704
4705 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4706 // We expand the bases without their virtual bases since those are going
4707 // in the initial structure. Note that this differs from gcc which
4708 // expands virtual bases each time one is encountered in the hierarchy,
4709 // making the encoding type bigger than it really is.
4710 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004711 assert(!base->isEmpty());
4712 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004713 } else {
4714 FieldDecl *field = cast<FieldDecl>(dcl);
4715 if (FD) {
4716 S += '"';
4717 S += field->getNameAsString();
4718 S += '"';
4719 }
4720
4721 if (field->isBitField()) {
4722 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00004723 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004724 } else {
4725 QualType qt = field->getType();
4726 getLegacyIntegralTypeEncoding(qt);
4727 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4728 /*OutermostType*/false,
4729 /*EncodingProperty*/false,
4730 /*StructField*/true);
4731 CurOffs += getTypeSize(field->getType());
4732 }
4733 }
4734 }
4735}
4736
Mike Stump11289f42009-09-09 15:08:12 +00004737void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004738 std::string& S) const {
4739 if (QT & Decl::OBJC_TQ_In)
4740 S += 'n';
4741 if (QT & Decl::OBJC_TQ_Inout)
4742 S += 'N';
4743 if (QT & Decl::OBJC_TQ_Out)
4744 S += 'o';
4745 if (QT & Decl::OBJC_TQ_Bycopy)
4746 S += 'O';
4747 if (QT & Decl::OBJC_TQ_Byref)
4748 S += 'R';
4749 if (QT & Decl::OBJC_TQ_Oneway)
4750 S += 'V';
4751}
4752
Chris Lattnere7cabb92009-07-13 00:10:46 +00004753void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004754 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004755
Anders Carlsson87c149b2007-10-11 01:00:40 +00004756 BuiltinVaListType = T;
4757}
4758
Douglas Gregor3ea72692011-08-12 05:46:01 +00004759TypedefDecl *ASTContext::getObjCIdDecl() const {
4760 if (!ObjCIdDecl) {
4761 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4762 T = getObjCObjectPointerType(T);
4763 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4764 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4765 getTranslationUnitDecl(),
4766 SourceLocation(), SourceLocation(),
4767 &Idents.get("id"), IdInfo);
4768 }
4769
4770 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00004771}
4772
Douglas Gregor52e02802011-08-12 06:17:30 +00004773TypedefDecl *ASTContext::getObjCSelDecl() const {
4774 if (!ObjCSelDecl) {
4775 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4776 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4777 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4778 getTranslationUnitDecl(),
4779 SourceLocation(), SourceLocation(),
4780 &Idents.get("SEL"), SelInfo);
4781 }
4782 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004783}
4784
Chris Lattnere7cabb92009-07-13 00:10:46 +00004785void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004786 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004787}
4788
Douglas Gregor0a586182011-08-12 05:59:41 +00004789TypedefDecl *ASTContext::getObjCClassDecl() const {
4790 if (!ObjCClassDecl) {
4791 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4792 T = getObjCObjectPointerType(T);
4793 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4794 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4795 getTranslationUnitDecl(),
4796 SourceLocation(), SourceLocation(),
4797 &Idents.get("Class"), ClassInfo);
4798 }
4799
4800 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004801}
4802
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004803void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004804 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004805 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004806
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004807 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004808}
4809
John McCalld28ae272009-12-02 08:04:21 +00004810/// \brief Retrieve the template name that corresponds to a non-empty
4811/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004812TemplateName
4813ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4814 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004815 unsigned size = End - Begin;
4816 assert(size > 1 && "set is not overloaded!");
4817
4818 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4819 size * sizeof(FunctionTemplateDecl*));
4820 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4821
4822 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004823 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004824 NamedDecl *D = *I;
4825 assert(isa<FunctionTemplateDecl>(D) ||
4826 (isa<UsingShadowDecl>(D) &&
4827 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4828 *Storage++ = D;
4829 }
4830
4831 return TemplateName(OT);
4832}
4833
Douglas Gregordc572a32009-03-30 22:58:21 +00004834/// \brief Retrieve the template name that represents a qualified
4835/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004836TemplateName
4837ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4838 bool TemplateKeyword,
4839 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00004840 assert(NNS && "Missing nested-name-specifier in qualified template name");
4841
Douglas Gregorc42075a2010-02-04 18:10:26 +00004842 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004843 llvm::FoldingSetNodeID ID;
4844 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4845
4846 void *InsertPos = 0;
4847 QualifiedTemplateName *QTN =
4848 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4849 if (!QTN) {
4850 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4851 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4852 }
4853
4854 return TemplateName(QTN);
4855}
4856
4857/// \brief Retrieve the template name that represents a dependent
4858/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004859TemplateName
4860ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4861 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004862 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004863 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004864
4865 llvm::FoldingSetNodeID ID;
4866 DependentTemplateName::Profile(ID, NNS, Name);
4867
4868 void *InsertPos = 0;
4869 DependentTemplateName *QTN =
4870 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4871
4872 if (QTN)
4873 return TemplateName(QTN);
4874
4875 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4876 if (CanonNNS == NNS) {
4877 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4878 } else {
4879 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4880 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004881 DependentTemplateName *CheckQTN =
4882 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4883 assert(!CheckQTN && "Dependent type name canonicalization broken");
4884 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004885 }
4886
4887 DependentTemplateNames.InsertNode(QTN, InsertPos);
4888 return TemplateName(QTN);
4889}
4890
Douglas Gregor71395fa2009-11-04 00:56:37 +00004891/// \brief Retrieve the template name that represents a dependent
4892/// template name such as \c MetaFun::template operator+.
4893TemplateName
4894ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00004895 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00004896 assert((!NNS || NNS->isDependent()) &&
4897 "Nested name specifier must be dependent");
4898
4899 llvm::FoldingSetNodeID ID;
4900 DependentTemplateName::Profile(ID, NNS, Operator);
4901
4902 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004903 DependentTemplateName *QTN
4904 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004905
4906 if (QTN)
4907 return TemplateName(QTN);
4908
4909 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4910 if (CanonNNS == NNS) {
4911 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4912 } else {
4913 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4914 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004915
4916 DependentTemplateName *CheckQTN
4917 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4918 assert(!CheckQTN && "Dependent template name canonicalization broken");
4919 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004920 }
4921
4922 DependentTemplateNames.InsertNode(QTN, InsertPos);
4923 return TemplateName(QTN);
4924}
4925
Douglas Gregor5590be02011-01-15 06:45:20 +00004926TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00004927ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
4928 TemplateName replacement) const {
4929 llvm::FoldingSetNodeID ID;
4930 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
4931
4932 void *insertPos = 0;
4933 SubstTemplateTemplateParmStorage *subst
4934 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
4935
4936 if (!subst) {
4937 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
4938 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
4939 }
4940
4941 return TemplateName(subst);
4942}
4943
4944TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00004945ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4946 const TemplateArgument &ArgPack) const {
4947 ASTContext &Self = const_cast<ASTContext &>(*this);
4948 llvm::FoldingSetNodeID ID;
4949 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4950
4951 void *InsertPos = 0;
4952 SubstTemplateTemplateParmPackStorage *Subst
4953 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4954
4955 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00004956 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00004957 ArgPack.pack_size(),
4958 ArgPack.pack_begin());
4959 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4960 }
4961
4962 return TemplateName(Subst);
4963}
4964
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004965/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004966/// TargetInfo, produce the corresponding type. The unsigned @p Type
4967/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004968CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004969 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004970 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004971 case TargetInfo::SignedShort: return ShortTy;
4972 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4973 case TargetInfo::SignedInt: return IntTy;
4974 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4975 case TargetInfo::SignedLong: return LongTy;
4976 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4977 case TargetInfo::SignedLongLong: return LongLongTy;
4978 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4979 }
4980
David Blaikie83d382b2011-09-23 05:06:16 +00004981 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004982}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004983
4984//===----------------------------------------------------------------------===//
4985// Type Predicates.
4986//===----------------------------------------------------------------------===//
4987
Fariborz Jahanian96207692009-02-18 21:49:28 +00004988/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4989/// garbage collection attribute.
4990///
John McCall553d45a2011-01-12 00:34:59 +00004991Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
Douglas Gregor79a91412011-09-13 17:21:33 +00004992 if (getLangOptions().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00004993 return Qualifiers::GCNone;
4994
4995 assert(getLangOptions().ObjC1);
4996 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4997
4998 // Default behaviour under objective-C's gc is for ObjC pointers
4999 // (or pointers to them) be treated as though they were declared
5000 // as __strong.
5001 if (GCAttrs == Qualifiers::GCNone) {
5002 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5003 return Qualifiers::Strong;
5004 else if (Ty->isPointerType())
5005 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5006 } else {
5007 // It's not valid to set GC attributes on anything that isn't a
5008 // pointer.
5009#ifndef NDEBUG
5010 QualType CT = Ty->getCanonicalTypeInternal();
5011 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5012 CT = AT->getElementType();
5013 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5014#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005015 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005016 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005017}
5018
Chris Lattner49af6a42008-04-07 06:51:04 +00005019//===----------------------------------------------------------------------===//
5020// Type Compatibility Testing
5021//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005022
Mike Stump11289f42009-09-09 15:08:12 +00005023/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005024/// compatible.
5025static bool areCompatVectorTypes(const VectorType *LHS,
5026 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005027 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005028 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005029 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005030}
5031
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005032bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5033 QualType SecondVec) {
5034 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5035 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5036
5037 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5038 return true;
5039
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005040 // Treat Neon vector types and most AltiVec vector types as if they are the
5041 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005042 const VectorType *First = FirstVec->getAs<VectorType>();
5043 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005044 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005045 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005046 First->getVectorKind() != VectorType::AltiVecPixel &&
5047 First->getVectorKind() != VectorType::AltiVecBool &&
5048 Second->getVectorKind() != VectorType::AltiVecPixel &&
5049 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005050 return true;
5051
5052 return false;
5053}
5054
Steve Naroff8e6aee52009-07-23 01:01:38 +00005055//===----------------------------------------------------------------------===//
5056// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5057//===----------------------------------------------------------------------===//
5058
5059/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5060/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005061bool
5062ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5063 ObjCProtocolDecl *rProto) const {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005064 if (lProto == rProto)
5065 return true;
5066 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5067 E = rProto->protocol_end(); PI != E; ++PI)
5068 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5069 return true;
5070 return false;
5071}
5072
Steve Naroff8e6aee52009-07-23 01:01:38 +00005073/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5074/// return true if lhs's protocols conform to rhs's protocol; false
5075/// otherwise.
5076bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5077 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5078 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5079 return false;
5080}
5081
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005082/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5083/// Class<p1, ...>.
5084bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5085 QualType rhs) {
5086 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5087 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5088 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5089
5090 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5091 E = lhsQID->qual_end(); I != E; ++I) {
5092 bool match = false;
5093 ObjCProtocolDecl *lhsProto = *I;
5094 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5095 E = rhsOPT->qual_end(); J != E; ++J) {
5096 ObjCProtocolDecl *rhsProto = *J;
5097 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5098 match = true;
5099 break;
5100 }
5101 }
5102 if (!match)
5103 return false;
5104 }
5105 return true;
5106}
5107
Steve Naroff8e6aee52009-07-23 01:01:38 +00005108/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5109/// ObjCQualifiedIDType.
5110bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5111 bool compare) {
5112 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005113 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005114 lhs->isObjCIdType() || lhs->isObjCClassType())
5115 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005116 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005117 rhs->isObjCIdType() || rhs->isObjCClassType())
5118 return true;
5119
5120 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005121 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005122
Steve Naroff8e6aee52009-07-23 01:01:38 +00005123 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005124
Steve Naroff8e6aee52009-07-23 01:01:38 +00005125 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005126 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005127 // make sure we check the class hierarchy.
5128 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5129 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5130 E = lhsQID->qual_end(); I != E; ++I) {
5131 // when comparing an id<P> on lhs with a static type on rhs,
5132 // see if static class implements all of id's protocols, directly or
5133 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005134 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005135 return false;
5136 }
5137 }
5138 // If there are no qualifiers and no interface, we have an 'id'.
5139 return true;
5140 }
Mike Stump11289f42009-09-09 15:08:12 +00005141 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005142 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5143 E = lhsQID->qual_end(); I != E; ++I) {
5144 ObjCProtocolDecl *lhsProto = *I;
5145 bool match = false;
5146
5147 // when comparing an id<P> on lhs with a static type on rhs,
5148 // see if static class implements all of id's protocols, directly or
5149 // through its super class and categories.
5150 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5151 E = rhsOPT->qual_end(); J != E; ++J) {
5152 ObjCProtocolDecl *rhsProto = *J;
5153 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5154 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5155 match = true;
5156 break;
5157 }
5158 }
Mike Stump11289f42009-09-09 15:08:12 +00005159 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005160 // make sure we check the class hierarchy.
5161 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5162 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5163 E = lhsQID->qual_end(); I != E; ++I) {
5164 // when comparing an id<P> on lhs with a static type on rhs,
5165 // see if static class implements all of id's protocols, directly or
5166 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005167 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005168 match = true;
5169 break;
5170 }
5171 }
5172 }
5173 if (!match)
5174 return false;
5175 }
Mike Stump11289f42009-09-09 15:08:12 +00005176
Steve Naroff8e6aee52009-07-23 01:01:38 +00005177 return true;
5178 }
Mike Stump11289f42009-09-09 15:08:12 +00005179
Steve Naroff8e6aee52009-07-23 01:01:38 +00005180 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5181 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5182
Mike Stump11289f42009-09-09 15:08:12 +00005183 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005184 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005185 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005186 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5187 E = lhsOPT->qual_end(); I != E; ++I) {
5188 ObjCProtocolDecl *lhsProto = *I;
5189 bool match = false;
5190
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005191 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005192 // see if static class implements all of id's protocols, directly or
5193 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005194 // First, lhs protocols in the qualifier list must be found, direct
5195 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005196 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5197 E = rhsQID->qual_end(); J != E; ++J) {
5198 ObjCProtocolDecl *rhsProto = *J;
5199 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5200 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5201 match = true;
5202 break;
5203 }
5204 }
5205 if (!match)
5206 return false;
5207 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005208
5209 // Static class's protocols, or its super class or category protocols
5210 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5211 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5212 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5213 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5214 // This is rather dubious but matches gcc's behavior. If lhs has
5215 // no type qualifier and its class has no static protocol(s)
5216 // assume that it is mismatch.
5217 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5218 return false;
5219 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5220 LHSInheritedProtocols.begin(),
5221 E = LHSInheritedProtocols.end(); I != E; ++I) {
5222 bool match = false;
5223 ObjCProtocolDecl *lhsProto = (*I);
5224 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5225 E = rhsQID->qual_end(); J != E; ++J) {
5226 ObjCProtocolDecl *rhsProto = *J;
5227 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5228 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5229 match = true;
5230 break;
5231 }
5232 }
5233 if (!match)
5234 return false;
5235 }
5236 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005237 return true;
5238 }
5239 return false;
5240}
5241
Eli Friedman47f77112008-08-22 00:56:42 +00005242/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005243/// compatible for assignment from RHS to LHS. This handles validation of any
5244/// protocol qualifiers on the LHS or RHS.
5245///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005246bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5247 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005248 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5249 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5250
Steve Naroff1329fa02009-07-15 18:40:39 +00005251 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005252 if (LHS->isObjCUnqualifiedIdOrClass() ||
5253 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005254 return true;
5255
John McCall8b07ec22010-05-15 11:32:37 +00005256 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005257 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5258 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005259 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005260
5261 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5262 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5263 QualType(RHSOPT,0));
5264
John McCall8b07ec22010-05-15 11:32:37 +00005265 // If we have 2 user-defined types, fall into that path.
5266 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005267 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005268
Steve Naroff8e6aee52009-07-23 01:01:38 +00005269 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005270}
5271
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005272/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005273/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005274/// arguments in block literals. When passed as arguments, passing 'A*' where
5275/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5276/// not OK. For the return type, the opposite is not OK.
5277bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5278 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005279 const ObjCObjectPointerType *RHSOPT,
5280 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005281 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005282 return true;
5283
5284 if (LHSOPT->isObjCBuiltinType()) {
5285 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5286 }
5287
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005288 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005289 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5290 QualType(RHSOPT,0),
5291 false);
5292
5293 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5294 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5295 if (LHS && RHS) { // We have 2 user-defined types.
5296 if (LHS != RHS) {
5297 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005298 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005299 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005300 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005301 }
5302 else
5303 return true;
5304 }
5305 return false;
5306}
5307
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005308/// getIntersectionOfProtocols - This routine finds the intersection of set
5309/// of protocols inherited from two distinct objective-c pointer objects.
5310/// It is used to build composite qualifier list of the composite type of
5311/// the conditional expression involving two objective-c pointer objects.
5312static
5313void getIntersectionOfProtocols(ASTContext &Context,
5314 const ObjCObjectPointerType *LHSOPT,
5315 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005316 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005317
John McCall8b07ec22010-05-15 11:32:37 +00005318 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5319 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5320 assert(LHS->getInterface() && "LHS must have an interface base");
5321 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005322
5323 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5324 unsigned LHSNumProtocols = LHS->getNumProtocols();
5325 if (LHSNumProtocols > 0)
5326 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5327 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005328 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005329 Context.CollectInheritedProtocols(LHS->getInterface(),
5330 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005331 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5332 LHSInheritedProtocols.end());
5333 }
5334
5335 unsigned RHSNumProtocols = RHS->getNumProtocols();
5336 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005337 ObjCProtocolDecl **RHSProtocols =
5338 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005339 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5340 if (InheritedProtocolSet.count(RHSProtocols[i]))
5341 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00005342 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005343 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005344 Context.CollectInheritedProtocols(RHS->getInterface(),
5345 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005346 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5347 RHSInheritedProtocols.begin(),
5348 E = RHSInheritedProtocols.end(); I != E; ++I)
5349 if (InheritedProtocolSet.count((*I)))
5350 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005351 }
5352}
5353
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005354/// areCommonBaseCompatible - Returns common base class of the two classes if
5355/// one found. Note that this is O'2 algorithm. But it will be called as the
5356/// last type comparison in a ?-exp of ObjC pointer types before a
5357/// warning is issued. So, its invokation is extremely rare.
5358QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005359 const ObjCObjectPointerType *Lptr,
5360 const ObjCObjectPointerType *Rptr) {
5361 const ObjCObjectType *LHS = Lptr->getObjectType();
5362 const ObjCObjectType *RHS = Rptr->getObjectType();
5363 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5364 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005365 if (!LDecl || !RDecl || (LDecl == RDecl))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005366 return QualType();
5367
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005368 do {
John McCall8b07ec22010-05-15 11:32:37 +00005369 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005370 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005371 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00005372 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5373
5374 QualType Result = QualType(LHS, 0);
5375 if (!Protocols.empty())
5376 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5377 Result = getObjCObjectPointerType(Result);
5378 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005379 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005380 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005381
5382 return QualType();
5383}
5384
John McCall8b07ec22010-05-15 11:32:37 +00005385bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5386 const ObjCObjectType *RHS) {
5387 assert(LHS->getInterface() && "LHS is not an interface type");
5388 assert(RHS->getInterface() && "RHS is not an interface type");
5389
Chris Lattner49af6a42008-04-07 06:51:04 +00005390 // Verify that the base decls are compatible: the RHS must be a subclass of
5391 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005392 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005393 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005394
Chris Lattner49af6a42008-04-07 06:51:04 +00005395 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5396 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005397 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005398 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005399
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005400 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5401 // more detailed analysis is required.
5402 if (RHS->getNumProtocols() == 0) {
5403 // OK, if LHS is a superclass of RHS *and*
5404 // this superclass is assignment compatible with LHS.
5405 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005406 bool IsSuperClass =
5407 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5408 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005409 // OK if conversion of LHS to SuperClass results in narrowing of types
5410 // ; i.e., SuperClass may implement at least one of the protocols
5411 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5412 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5413 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005414 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005415 // If super class has no protocols, it is not a match.
5416 if (SuperClassInheritedProtocols.empty())
5417 return false;
5418
5419 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5420 LHSPE = LHS->qual_end();
5421 LHSPI != LHSPE; LHSPI++) {
5422 bool SuperImplementsProtocol = false;
5423 ObjCProtocolDecl *LHSProto = (*LHSPI);
5424
5425 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5426 SuperClassInheritedProtocols.begin(),
5427 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5428 ObjCProtocolDecl *SuperClassProto = (*I);
5429 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5430 SuperImplementsProtocol = true;
5431 break;
5432 }
5433 }
5434 if (!SuperImplementsProtocol)
5435 return false;
5436 }
5437 return true;
5438 }
5439 return false;
5440 }
Mike Stump11289f42009-09-09 15:08:12 +00005441
John McCall8b07ec22010-05-15 11:32:37 +00005442 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5443 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005444 LHSPI != LHSPE; LHSPI++) {
5445 bool RHSImplementsProtocol = false;
5446
5447 // If the RHS doesn't implement the protocol on the left, the types
5448 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005449 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5450 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005451 RHSPI != RHSPE; RHSPI++) {
5452 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005453 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005454 break;
5455 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005456 }
5457 // FIXME: For better diagnostics, consider passing back the protocol name.
5458 if (!RHSImplementsProtocol)
5459 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005460 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005461 // The RHS implements all protocols listed on the LHS.
5462 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005463}
5464
Steve Naroffb7605152009-02-12 17:52:19 +00005465bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5466 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005467 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5468 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005469
Steve Naroff7cae42b2009-07-10 23:34:53 +00005470 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005471 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005472
5473 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5474 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005475}
5476
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005477bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5478 return canAssignObjCInterfaces(
5479 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5480 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5481}
5482
Mike Stump11289f42009-09-09 15:08:12 +00005483/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005484/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005485/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005486/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005487bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5488 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00005489 if (getLangOptions().CPlusPlus)
5490 return hasSameType(LHS, RHS);
5491
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005492 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005493}
5494
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005495bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00005496 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005497}
5498
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005499bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5500 return !mergeTypes(LHS, RHS, true).isNull();
5501}
5502
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005503/// mergeTransparentUnionType - if T is a transparent union type and a member
5504/// of T is compatible with SubType, return the merged type, else return
5505/// QualType()
5506QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5507 bool OfBlockPointer,
5508 bool Unqualified) {
5509 if (const RecordType *UT = T->getAsUnionType()) {
5510 RecordDecl *UD = UT->getDecl();
5511 if (UD->hasAttr<TransparentUnionAttr>()) {
5512 for (RecordDecl::field_iterator it = UD->field_begin(),
5513 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005514 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005515 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5516 if (!MT.isNull())
5517 return MT;
5518 }
5519 }
5520 }
5521
5522 return QualType();
5523}
5524
5525/// mergeFunctionArgumentTypes - merge two types which appear as function
5526/// argument types
5527QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5528 bool OfBlockPointer,
5529 bool Unqualified) {
5530 // GNU extension: two types are compatible if they appear as a function
5531 // argument, one of the types is a transparent union type and the other
5532 // type is compatible with a union member
5533 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5534 Unqualified);
5535 if (!lmerge.isNull())
5536 return lmerge;
5537
5538 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5539 Unqualified);
5540 if (!rmerge.isNull())
5541 return rmerge;
5542
5543 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5544}
5545
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005546QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005547 bool OfBlockPointer,
5548 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005549 const FunctionType *lbase = lhs->getAs<FunctionType>();
5550 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005551 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5552 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005553 bool allLTypes = true;
5554 bool allRTypes = true;
5555
5556 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005557 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00005558 if (OfBlockPointer) {
5559 QualType RHS = rbase->getResultType();
5560 QualType LHS = lbase->getResultType();
5561 bool UnqualifiedResult = Unqualified;
5562 if (!UnqualifiedResult)
5563 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005564 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00005565 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005566 else
John McCall8c6b56f2010-12-15 01:06:38 +00005567 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5568 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005569 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005570
5571 if (Unqualified)
5572 retType = retType.getUnqualifiedType();
5573
5574 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5575 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5576 if (Unqualified) {
5577 LRetType = LRetType.getUnqualifiedType();
5578 RRetType = RRetType.getUnqualifiedType();
5579 }
5580
5581 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005582 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005583 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005584 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005585
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005586 // FIXME: double check this
5587 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5588 // rbase->getRegParmAttr() != 0 &&
5589 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005590 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5591 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005592
Douglas Gregor8c940862010-01-18 17:14:39 +00005593 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005594 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005595 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005596
John McCall8c6b56f2010-12-15 01:06:38 +00005597 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00005598 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5599 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00005600 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5601 return QualType();
5602
John McCall31168b02011-06-15 23:02:42 +00005603 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5604 return QualType();
5605
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005606 // functypes which return are preferred over those that do not.
5607 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5608 allLTypes = false;
5609 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5610 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005611 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5612 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00005613
John McCall31168b02011-06-15 23:02:42 +00005614 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00005615
Eli Friedman47f77112008-08-22 00:56:42 +00005616 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005617 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5618 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005619 unsigned lproto_nargs = lproto->getNumArgs();
5620 unsigned rproto_nargs = rproto->getNumArgs();
5621
5622 // Compatible functions must have the same number of arguments
5623 if (lproto_nargs != rproto_nargs)
5624 return QualType();
5625
5626 // Variadic and non-variadic functions aren't compatible
5627 if (lproto->isVariadic() != rproto->isVariadic())
5628 return QualType();
5629
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005630 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5631 return QualType();
5632
Fariborz Jahanian97676972011-09-28 21:52:05 +00005633 if (LangOpts.ObjCAutoRefCount &&
5634 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5635 return QualType();
5636
Eli Friedman47f77112008-08-22 00:56:42 +00005637 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005638 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00005639 for (unsigned i = 0; i < lproto_nargs; i++) {
5640 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5641 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005642 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5643 OfBlockPointer,
5644 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005645 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005646
5647 if (Unqualified)
5648 argtype = argtype.getUnqualifiedType();
5649
Eli Friedman47f77112008-08-22 00:56:42 +00005650 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005651 if (Unqualified) {
5652 largtype = largtype.getUnqualifiedType();
5653 rargtype = rargtype.getUnqualifiedType();
5654 }
5655
Chris Lattner465fa322008-10-05 17:34:18 +00005656 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5657 allLTypes = false;
5658 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5659 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005660 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00005661
Eli Friedman47f77112008-08-22 00:56:42 +00005662 if (allLTypes) return lhs;
5663 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005664
5665 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5666 EPI.ExtInfo = einfo;
5667 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005668 }
5669
5670 if (lproto) allRTypes = false;
5671 if (rproto) allLTypes = false;
5672
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005673 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005674 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005675 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005676 if (proto->isVariadic()) return QualType();
5677 // Check that the types are compatible with the types that
5678 // would result from default argument promotions (C99 6.7.5.3p15).
5679 // The only types actually affected are promotable integer
5680 // types and floats, which would be passed as a different
5681 // type depending on whether the prototype is visible.
5682 unsigned proto_nargs = proto->getNumArgs();
5683 for (unsigned i = 0; i < proto_nargs; ++i) {
5684 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005685
5686 // Look at the promotion type of enum types, since that is the type used
5687 // to pass enum values.
5688 if (const EnumType *Enum = argTy->getAs<EnumType>())
5689 argTy = Enum->getDecl()->getPromotionType();
5690
Eli Friedman47f77112008-08-22 00:56:42 +00005691 if (argTy->isPromotableIntegerType() ||
5692 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5693 return QualType();
5694 }
5695
5696 if (allLTypes) return lhs;
5697 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005698
5699 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5700 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005701 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005702 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005703 }
5704
5705 if (allLTypes) return lhs;
5706 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005707 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005708}
5709
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005710QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005711 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005712 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005713 // C++ [expr]: If an expression initially has the type "reference to T", the
5714 // type is adjusted to "T" prior to any further analysis, the expression
5715 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005716 // expression is an lvalue unless the reference is an rvalue reference and
5717 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005718 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5719 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005720
5721 if (Unqualified) {
5722 LHS = LHS.getUnqualifiedType();
5723 RHS = RHS.getUnqualifiedType();
5724 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005725
Eli Friedman47f77112008-08-22 00:56:42 +00005726 QualType LHSCan = getCanonicalType(LHS),
5727 RHSCan = getCanonicalType(RHS);
5728
5729 // If two types are identical, they are compatible.
5730 if (LHSCan == RHSCan)
5731 return LHS;
5732
John McCall8ccfcb52009-09-24 19:53:00 +00005733 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005734 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5735 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005736 if (LQuals != RQuals) {
5737 // If any of these qualifiers are different, we have a type
5738 // mismatch.
5739 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00005740 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5741 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00005742 return QualType();
5743
5744 // Exactly one GC qualifier difference is allowed: __strong is
5745 // okay if the other type has no GC qualifier but is an Objective
5746 // C object pointer (i.e. implicitly strong by default). We fix
5747 // this by pretending that the unqualified type was actually
5748 // qualified __strong.
5749 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5750 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5751 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5752
5753 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5754 return QualType();
5755
5756 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5757 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5758 }
5759 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5760 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5761 }
Eli Friedman47f77112008-08-22 00:56:42 +00005762 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005763 }
5764
5765 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005766
Eli Friedmandcca6332009-06-01 01:22:52 +00005767 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5768 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005769
Chris Lattnerfd652912008-01-14 05:45:46 +00005770 // We want to consider the two function types to be the same for these
5771 // comparisons, just force one to the other.
5772 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5773 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005774
5775 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005776 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5777 LHSClass = Type::ConstantArray;
5778 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5779 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005780
John McCall8b07ec22010-05-15 11:32:37 +00005781 // ObjCInterfaces are just specialized ObjCObjects.
5782 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5783 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5784
Nate Begemance4d7fc2008-04-18 23:10:10 +00005785 // Canonicalize ExtVector -> Vector.
5786 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5787 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005788
Chris Lattner95554662008-04-07 05:43:21 +00005789 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005790 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005791 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005792 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005793 // Compatibility is based on the underlying type, not the promotion
5794 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005795 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005796 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5797 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005798 }
John McCall9dd450b2009-09-21 23:43:11 +00005799 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005800 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5801 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005802 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005803
Eli Friedman47f77112008-08-22 00:56:42 +00005804 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005805 }
Eli Friedman47f77112008-08-22 00:56:42 +00005806
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005807 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005808 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005809#define TYPE(Class, Base)
5810#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005811#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005812#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5813#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5814#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00005815 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005816
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005817 case Type::LValueReference:
5818 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005819 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00005820 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005821
John McCall8b07ec22010-05-15 11:32:37 +00005822 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005823 case Type::IncompleteArray:
5824 case Type::VariableArray:
5825 case Type::FunctionProto:
5826 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00005827 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005828
Chris Lattnerfd652912008-01-14 05:45:46 +00005829 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005830 {
5831 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005832 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5833 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005834 if (Unqualified) {
5835 LHSPointee = LHSPointee.getUnqualifiedType();
5836 RHSPointee = RHSPointee.getUnqualifiedType();
5837 }
5838 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5839 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005840 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005841 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005842 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005843 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005844 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005845 return getPointerType(ResultType);
5846 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005847 case Type::BlockPointer:
5848 {
5849 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005850 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5851 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005852 if (Unqualified) {
5853 LHSPointee = LHSPointee.getUnqualifiedType();
5854 RHSPointee = RHSPointee.getUnqualifiedType();
5855 }
5856 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5857 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005858 if (ResultType.isNull()) return QualType();
5859 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5860 return LHS;
5861 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5862 return RHS;
5863 return getBlockPointerType(ResultType);
5864 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00005865 case Type::Atomic:
5866 {
5867 // Merge two pointer types, while trying to preserve typedef info
5868 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
5869 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
5870 if (Unqualified) {
5871 LHSValue = LHSValue.getUnqualifiedType();
5872 RHSValue = RHSValue.getUnqualifiedType();
5873 }
5874 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
5875 Unqualified);
5876 if (ResultType.isNull()) return QualType();
5877 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
5878 return LHS;
5879 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
5880 return RHS;
5881 return getAtomicType(ResultType);
5882 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005883 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00005884 {
5885 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5886 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5887 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5888 return QualType();
5889
5890 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5891 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005892 if (Unqualified) {
5893 LHSElem = LHSElem.getUnqualifiedType();
5894 RHSElem = RHSElem.getUnqualifiedType();
5895 }
5896
5897 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005898 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00005899 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5900 return LHS;
5901 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5902 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00005903 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5904 ArrayType::ArraySizeModifier(), 0);
5905 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5906 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005907 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5908 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00005909 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5910 return LHS;
5911 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5912 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005913 if (LVAT) {
5914 // FIXME: This isn't correct! But tricky to implement because
5915 // the array's size has to be the size of LHS, but the type
5916 // has to be different.
5917 return LHS;
5918 }
5919 if (RVAT) {
5920 // FIXME: This isn't correct! But tricky to implement because
5921 // the array's size has to be the size of RHS, but the type
5922 // has to be different.
5923 return RHS;
5924 }
Eli Friedman3e62c212008-08-22 01:48:21 +00005925 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5926 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00005927 return getIncompleteArrayType(ResultType,
5928 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005929 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005930 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005931 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005932 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005933 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00005934 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00005935 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005936 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00005937 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00005938 case Type::Complex:
5939 // Distinct complex types are incompatible.
5940 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005941 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00005942 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00005943 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5944 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00005945 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00005946 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00005947 case Type::ObjCObject: {
5948 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00005949 // FIXME: This should be type compatibility, e.g. whether
5950 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00005951 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5952 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5953 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00005954 return LHS;
5955
Eli Friedman47f77112008-08-22 00:56:42 +00005956 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00005957 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005958 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005959 if (OfBlockPointer) {
5960 if (canAssignObjCInterfacesInBlockPointer(
5961 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005962 RHS->getAs<ObjCObjectPointerType>(),
5963 BlockReturnType))
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005964 return LHS;
5965 return QualType();
5966 }
John McCall9dd450b2009-09-21 23:43:11 +00005967 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5968 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005969 return LHS;
5970
Steve Naroffc68cfcf2008-12-10 22:14:21 +00005971 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005972 }
Steve Naroff32e44c02007-10-15 20:41:53 +00005973 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005974
5975 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005976}
Ted Kremenekfc581a92007-10-31 17:10:13 +00005977
Fariborz Jahanian97676972011-09-28 21:52:05 +00005978bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
5979 const FunctionProtoType *FromFunctionType,
5980 const FunctionProtoType *ToFunctionType) {
5981 if (FromFunctionType->hasAnyConsumedArgs() !=
5982 ToFunctionType->hasAnyConsumedArgs())
5983 return false;
5984 FunctionProtoType::ExtProtoInfo FromEPI =
5985 FromFunctionType->getExtProtoInfo();
5986 FunctionProtoType::ExtProtoInfo ToEPI =
5987 ToFunctionType->getExtProtoInfo();
5988 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
5989 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
5990 ArgIdx != NumArgs; ++ArgIdx) {
5991 if (FromEPI.ConsumedArguments[ArgIdx] !=
5992 ToEPI.ConsumedArguments[ArgIdx])
5993 return false;
5994 }
5995 return true;
5996}
5997
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005998/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5999/// 'RHS' attributes and returns the merged version; including for function
6000/// return types.
6001QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6002 QualType LHSCan = getCanonicalType(LHS),
6003 RHSCan = getCanonicalType(RHS);
6004 // If two types are identical, they are compatible.
6005 if (LHSCan == RHSCan)
6006 return LHS;
6007 if (RHSCan->isFunctionType()) {
6008 if (!LHSCan->isFunctionType())
6009 return QualType();
6010 QualType OldReturnType =
6011 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6012 QualType NewReturnType =
6013 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6014 QualType ResReturnType =
6015 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6016 if (ResReturnType.isNull())
6017 return QualType();
6018 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6019 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6020 // In either case, use OldReturnType to build the new function type.
6021 const FunctionType *F = LHS->getAs<FunctionType>();
6022 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006023 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6024 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006025 QualType ResultType
6026 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006027 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006028 return ResultType;
6029 }
6030 }
6031 return QualType();
6032 }
6033
6034 // If the qualifiers are different, the types can still be merged.
6035 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6036 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6037 if (LQuals != RQuals) {
6038 // If any of these qualifiers are different, we have a type mismatch.
6039 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6040 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6041 return QualType();
6042
6043 // Exactly one GC qualifier difference is allowed: __strong is
6044 // okay if the other type has no GC qualifier but is an Objective
6045 // C object pointer (i.e. implicitly strong by default). We fix
6046 // this by pretending that the unqualified type was actually
6047 // qualified __strong.
6048 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6049 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6050 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6051
6052 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6053 return QualType();
6054
6055 if (GC_L == Qualifiers::Strong)
6056 return LHS;
6057 if (GC_R == Qualifiers::Strong)
6058 return RHS;
6059 return QualType();
6060 }
6061
6062 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6063 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6064 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6065 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6066 if (ResQT == LHSBaseQT)
6067 return LHS;
6068 if (ResQT == RHSBaseQT)
6069 return RHS;
6070 }
6071 return QualType();
6072}
6073
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006074//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006075// Integer Predicates
6076//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006077
Jay Foad39c79802011-01-12 09:06:06 +00006078unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006079 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006080 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006081 if (T->isBooleanType())
6082 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006083 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006084 return (unsigned)getTypeSize(T);
6085}
6086
6087QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006088 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006089
6090 // Turn <4 x signed int> -> <4 x unsigned int>
6091 if (const VectorType *VTy = T->getAs<VectorType>())
6092 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006093 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006094
6095 // For enums, we return the unsigned version of the base type.
6096 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006097 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006098
6099 const BuiltinType *BTy = T->getAs<BuiltinType>();
6100 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006101 switch (BTy->getKind()) {
6102 case BuiltinType::Char_S:
6103 case BuiltinType::SChar:
6104 return UnsignedCharTy;
6105 case BuiltinType::Short:
6106 return UnsignedShortTy;
6107 case BuiltinType::Int:
6108 return UnsignedIntTy;
6109 case BuiltinType::Long:
6110 return UnsignedLongTy;
6111 case BuiltinType::LongLong:
6112 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006113 case BuiltinType::Int128:
6114 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006115 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006116 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006117 }
6118}
6119
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006120ASTMutationListener::~ASTMutationListener() { }
6121
Chris Lattnerecd79c62009-06-14 00:45:47 +00006122
6123//===----------------------------------------------------------------------===//
6124// Builtin Type Computation
6125//===----------------------------------------------------------------------===//
6126
6127/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006128/// pointer over the consumed characters. This returns the resultant type. If
6129/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6130/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6131/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006132///
6133/// RequiresICE is filled in on return to indicate whether the value is required
6134/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006135static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006136 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006137 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006138 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006139 // Modifiers.
6140 int HowLong = 0;
6141 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006142 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006143
Chris Lattnerdc226c22010-10-01 22:42:38 +00006144 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006145 bool Done = false;
6146 while (!Done) {
6147 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006148 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006149 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006150 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006151 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006152 case 'S':
6153 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6154 assert(!Signed && "Can't use 'S' modifier multiple times!");
6155 Signed = true;
6156 break;
6157 case 'U':
6158 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6159 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6160 Unsigned = true;
6161 break;
6162 case 'L':
6163 assert(HowLong <= 2 && "Can't have LLLL modifier");
6164 ++HowLong;
6165 break;
6166 }
6167 }
6168
6169 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006170
Chris Lattnerecd79c62009-06-14 00:45:47 +00006171 // Read the base type.
6172 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006173 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006174 case 'v':
6175 assert(HowLong == 0 && !Signed && !Unsigned &&
6176 "Bad modifiers used with 'v'!");
6177 Type = Context.VoidTy;
6178 break;
6179 case 'f':
6180 assert(HowLong == 0 && !Signed && !Unsigned &&
6181 "Bad modifiers used with 'f'!");
6182 Type = Context.FloatTy;
6183 break;
6184 case 'd':
6185 assert(HowLong < 2 && !Signed && !Unsigned &&
6186 "Bad modifiers used with 'd'!");
6187 if (HowLong)
6188 Type = Context.LongDoubleTy;
6189 else
6190 Type = Context.DoubleTy;
6191 break;
6192 case 's':
6193 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6194 if (Unsigned)
6195 Type = Context.UnsignedShortTy;
6196 else
6197 Type = Context.ShortTy;
6198 break;
6199 case 'i':
6200 if (HowLong == 3)
6201 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6202 else if (HowLong == 2)
6203 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6204 else if (HowLong == 1)
6205 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6206 else
6207 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6208 break;
6209 case 'c':
6210 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6211 if (Signed)
6212 Type = Context.SignedCharTy;
6213 else if (Unsigned)
6214 Type = Context.UnsignedCharTy;
6215 else
6216 Type = Context.CharTy;
6217 break;
6218 case 'b': // boolean
6219 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6220 Type = Context.BoolTy;
6221 break;
6222 case 'z': // size_t.
6223 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6224 Type = Context.getSizeType();
6225 break;
6226 case 'F':
6227 Type = Context.getCFConstantStringType();
6228 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006229 case 'G':
6230 Type = Context.getObjCIdType();
6231 break;
6232 case 'H':
6233 Type = Context.getObjCSelType();
6234 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006235 case 'a':
6236 Type = Context.getBuiltinVaListType();
6237 assert(!Type.isNull() && "builtin va list type not initialized!");
6238 break;
6239 case 'A':
6240 // This is a "reference" to a va_list; however, what exactly
6241 // this means depends on how va_list is defined. There are two
6242 // different kinds of va_list: ones passed by value, and ones
6243 // passed by reference. An example of a by-value va_list is
6244 // x86, where va_list is a char*. An example of by-ref va_list
6245 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6246 // we want this argument to be a char*&; for x86-64, we want
6247 // it to be a __va_list_tag*.
6248 Type = Context.getBuiltinVaListType();
6249 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006250 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006251 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006252 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006253 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006254 break;
6255 case 'V': {
6256 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006257 unsigned NumElements = strtoul(Str, &End, 10);
6258 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006259 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006260
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006261 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6262 RequiresICE, false);
6263 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006264
6265 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006266 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006267 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006268 break;
6269 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006270 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006271 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6272 false);
6273 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006274 Type = Context.getComplexType(ElementType);
6275 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00006276 }
6277 case 'Y' : {
6278 Type = Context.getPointerDiffType();
6279 break;
6280 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006281 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006282 Type = Context.getFILEType();
6283 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006284 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006285 return QualType();
6286 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006287 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006288 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006289 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006290 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006291 else
6292 Type = Context.getjmp_bufType();
6293
Mike Stump2adb4da2009-07-28 23:47:15 +00006294 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006295 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006296 return QualType();
6297 }
6298 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006299 }
Mike Stump11289f42009-09-09 15:08:12 +00006300
Chris Lattnerdc226c22010-10-01 22:42:38 +00006301 // If there are modifiers and if we're allowed to parse them, go for it.
6302 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006303 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006304 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006305 default: Done = true; --Str; break;
6306 case '*':
6307 case '&': {
6308 // Both pointers and references can have their pointee types
6309 // qualified with an address space.
6310 char *End;
6311 unsigned AddrSpace = strtoul(Str, &End, 10);
6312 if (End != Str && AddrSpace != 0) {
6313 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6314 Str = End;
6315 }
6316 if (c == '*')
6317 Type = Context.getPointerType(Type);
6318 else
6319 Type = Context.getLValueReferenceType(Type);
6320 break;
6321 }
6322 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6323 case 'C':
6324 Type = Type.withConst();
6325 break;
6326 case 'D':
6327 Type = Context.getVolatileType(Type);
6328 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006329 }
6330 }
Chris Lattner84733392010-10-01 07:13:18 +00006331
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006332 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006333 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006334
Chris Lattnerecd79c62009-06-14 00:45:47 +00006335 return Type;
6336}
6337
6338/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006339QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006340 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006341 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006342 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006343
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006344 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006345
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006346 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006347 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006348 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6349 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006350 if (Error != GE_None)
6351 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006352
6353 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6354
Chris Lattnerecd79c62009-06-14 00:45:47 +00006355 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006356 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006357 if (Error != GE_None)
6358 return QualType();
6359
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006360 // If this argument is required to be an IntegerConstantExpression and the
6361 // caller cares, fill in the bitmask we return.
6362 if (RequiresICE && IntegerConstantArgs)
6363 *IntegerConstantArgs |= 1 << ArgTypes.size();
6364
Chris Lattnerecd79c62009-06-14 00:45:47 +00006365 // Do array -> pointer decay. The builtin should use the decayed type.
6366 if (Ty->isArrayType())
6367 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006368
Chris Lattnerecd79c62009-06-14 00:45:47 +00006369 ArgTypes.push_back(Ty);
6370 }
6371
6372 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6373 "'.' should only occur at end of builtin type list!");
6374
John McCall991eb4b2010-12-21 00:44:39 +00006375 FunctionType::ExtInfo EI;
6376 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6377
6378 bool Variadic = (TypeStr[0] == '.');
6379
6380 // We really shouldn't be making a no-proto type here, especially in C++.
6381 if (ArgTypes.empty() && Variadic)
6382 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006383
John McCalldb40c7f2010-12-14 08:05:40 +00006384 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006385 EPI.ExtInfo = EI;
6386 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006387
6388 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006389}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006390
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006391GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6392 GVALinkage External = GVA_StrongExternal;
6393
6394 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006395 switch (L) {
6396 case NoLinkage:
6397 case InternalLinkage:
6398 case UniqueExternalLinkage:
6399 return GVA_Internal;
6400
6401 case ExternalLinkage:
6402 switch (FD->getTemplateSpecializationKind()) {
6403 case TSK_Undeclared:
6404 case TSK_ExplicitSpecialization:
6405 External = GVA_StrongExternal;
6406 break;
6407
6408 case TSK_ExplicitInstantiationDefinition:
6409 return GVA_ExplicitTemplateInstantiation;
6410
6411 case TSK_ExplicitInstantiationDeclaration:
6412 case TSK_ImplicitInstantiation:
6413 External = GVA_TemplateInstantiation;
6414 break;
6415 }
6416 }
6417
6418 if (!FD->isInlined())
6419 return External;
6420
6421 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6422 // GNU or C99 inline semantics. Determine whether this symbol should be
6423 // externally visible.
6424 if (FD->isInlineDefinitionExternallyVisible())
6425 return External;
6426
6427 // C99 inline semantics, where the symbol is not externally visible.
6428 return GVA_C99Inline;
6429 }
6430
6431 // C++0x [temp.explicit]p9:
6432 // [ Note: The intent is that an inline function that is the subject of
6433 // an explicit instantiation declaration will still be implicitly
6434 // instantiated when used so that the body can be considered for
6435 // inlining, but that no out-of-line copy of the inline function would be
6436 // generated in the translation unit. -- end note ]
6437 if (FD->getTemplateSpecializationKind()
6438 == TSK_ExplicitInstantiationDeclaration)
6439 return GVA_C99Inline;
6440
6441 return GVA_CXXInline;
6442}
6443
6444GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6445 // If this is a static data member, compute the kind of template
6446 // specialization. Otherwise, this variable is not part of a
6447 // template.
6448 TemplateSpecializationKind TSK = TSK_Undeclared;
6449 if (VD->isStaticDataMember())
6450 TSK = VD->getTemplateSpecializationKind();
6451
6452 Linkage L = VD->getLinkage();
6453 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6454 VD->getType()->getLinkage() == UniqueExternalLinkage)
6455 L = UniqueExternalLinkage;
6456
6457 switch (L) {
6458 case NoLinkage:
6459 case InternalLinkage:
6460 case UniqueExternalLinkage:
6461 return GVA_Internal;
6462
6463 case ExternalLinkage:
6464 switch (TSK) {
6465 case TSK_Undeclared:
6466 case TSK_ExplicitSpecialization:
6467 return GVA_StrongExternal;
6468
6469 case TSK_ExplicitInstantiationDeclaration:
6470 llvm_unreachable("Variable should not be instantiated");
6471 // Fall through to treat this like any other instantiation.
6472
6473 case TSK_ExplicitInstantiationDefinition:
6474 return GVA_ExplicitTemplateInstantiation;
6475
6476 case TSK_ImplicitInstantiation:
6477 return GVA_TemplateInstantiation;
6478 }
6479 }
6480
6481 return GVA_StrongExternal;
6482}
6483
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00006484bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006485 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6486 if (!VD->isFileVarDecl())
6487 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00006488 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006489 return false;
6490
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006491 // Weak references don't produce any output by themselves.
6492 if (D->hasAttr<WeakRefAttr>())
6493 return false;
6494
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006495 // Aliases and used decls are required.
6496 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6497 return true;
6498
6499 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6500 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00006501 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00006502 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006503
6504 // Constructors and destructors are required.
6505 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6506 return true;
6507
6508 // The key function for a class is required.
6509 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6510 const CXXRecordDecl *RD = MD->getParent();
6511 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6512 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6513 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6514 return true;
6515 }
6516 }
6517
6518 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6519
6520 // static, static inline, always_inline, and extern inline functions can
6521 // always be deferred. Normal inline functions can be deferred in C99/C++.
6522 // Implicit template instantiations can also be deferred in C++.
6523 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6524 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6525 return false;
6526 return true;
6527 }
Douglas Gregor87d81242011-09-10 00:22:34 +00006528
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006529 const VarDecl *VD = cast<VarDecl>(D);
6530 assert(VD->isFileVarDecl() && "Expected file scoped var");
6531
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006532 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6533 return false;
6534
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006535 // Structs that have non-trivial constructors or destructors are required.
6536
6537 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00006538 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006539 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6540 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00006541 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6542 RD->hasTrivialCopyConstructor() &&
6543 RD->hasTrivialMoveConstructor() &&
6544 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006545 return true;
6546 }
6547 }
6548
6549 GVALinkage L = GetGVALinkageForVariable(VD);
6550 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6551 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6552 return false;
6553 }
6554
6555 return true;
6556}
Charles Davis53c59df2010-08-16 03:33:14 +00006557
Charles Davis99202b32010-11-09 18:04:24 +00006558CallingConv ASTContext::getDefaultMethodCallConv() {
6559 // Pass through to the C++ ABI object
6560 return ABI->getDefaultMethodCallConv();
6561}
6562
Jay Foad39c79802011-01-12 09:06:06 +00006563bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00006564 // Pass through to the C++ ABI object
6565 return ABI->isNearlyEmpty(RD);
6566}
6567
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006568MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00006569 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006570 case CXXABI_ARM:
6571 case CXXABI_Itanium:
6572 return createItaniumMangleContext(*this, getDiagnostics());
6573 case CXXABI_Microsoft:
6574 return createMicrosoftMangleContext(*this, getDiagnostics());
6575 }
David Blaikie83d382b2011-09-23 05:06:16 +00006576 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006577}
6578
Charles Davis53c59df2010-08-16 03:33:14 +00006579CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006580
6581size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00006582 return ASTRecordLayouts.getMemorySize()
6583 + llvm::capacity_in_bytes(ObjCLayouts)
6584 + llvm::capacity_in_bytes(KeyFunctions)
6585 + llvm::capacity_in_bytes(ObjCImpls)
6586 + llvm::capacity_in_bytes(BlockVarCopyInits)
6587 + llvm::capacity_in_bytes(DeclAttrs)
6588 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6589 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6590 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6591 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6592 + llvm::capacity_in_bytes(OverriddenMethods)
6593 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006594 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00006595 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006596}
Ted Kremenek540017e2011-10-06 05:00:56 +00006597
6598void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6599 ParamIndices[D] = index;
6600}
6601
6602unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6603 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6604 assert(I != ParamIndices.end() &&
6605 "ParmIndices lacks entry set by ParmVarDecl");
6606 return I->second;
6607}