blob: cb4e09bfc9eacbe5377ea5e2a033ca1f3f4c66c5 [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 McCall526ab472011-10-25 17:37:35 +0000464 // Placeholder type for pseudo-objects.
465 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
466
John McCall31996342011-04-07 08:22:57 +0000467 // "any" type; useful for debugger-like clients.
468 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
469
John McCall8a6b59a2011-10-17 18:09:15 +0000470 // Placeholder type for unbridged ARC casts.
471 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
472
Chris Lattner970e54e2006-11-12 00:37:36 +0000473 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000474 FloatComplexTy = getComplexType(FloatTy);
475 DoubleComplexTy = getComplexType(DoubleTy);
476 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000477
Steve Naroff66e9f332007-10-15 14:41:52 +0000478 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000479
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000480 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000481 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
482 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000483 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000484
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000485 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000486
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000487 // void * type
488 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000489
490 // nullptr type (C++0x 2.14.7)
491 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000492
493 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
494 InitBuiltinType(HalfTy, BuiltinType::Half);
Chris Lattner970e54e2006-11-12 00:37:36 +0000495}
496
David Blaikie9c902b52011-09-25 23:23:43 +0000497DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000498 return SourceMgr.getDiagnostics();
499}
500
Douglas Gregor561eceb2010-08-30 16:49:28 +0000501AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
502 AttrVec *&Result = DeclAttrs[D];
503 if (!Result) {
504 void *Mem = Allocate(sizeof(AttrVec));
505 Result = new (Mem) AttrVec;
506 }
507
508 return *Result;
509}
510
511/// \brief Erase the attributes corresponding to the given declaration.
512void ASTContext::eraseDeclAttrs(const Decl *D) {
513 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
514 if (Pos != DeclAttrs.end()) {
515 Pos->second->~AttrVec();
516 DeclAttrs.erase(Pos);
517 }
518}
519
Douglas Gregor86d142a2009-10-08 07:24:58 +0000520MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000521ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000522 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000523 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000524 = InstantiatedFromStaticDataMember.find(Var);
525 if (Pos == InstantiatedFromStaticDataMember.end())
526 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000527
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000528 return Pos->second;
529}
530
Mike Stump11289f42009-09-09 15:08:12 +0000531void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000532ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000533 TemplateSpecializationKind TSK,
534 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000535 assert(Inst->isStaticDataMember() && "Not a static data member");
536 assert(Tmpl->isStaticDataMember() && "Not a static data member");
537 assert(!InstantiatedFromStaticDataMember[Inst] &&
538 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000539 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000540 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000541}
542
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000543FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
544 const FunctionDecl *FD){
545 assert(FD && "Specialization is 0");
546 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000547 = ClassScopeSpecializationPattern.find(FD);
548 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000549 return 0;
550
551 return Pos->second;
552}
553
554void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
555 FunctionDecl *Pattern) {
556 assert(FD && "Specialization is 0");
557 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000558 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000559}
560
John McCalle61f2ba2009-11-18 02:36:19 +0000561NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000562ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000563 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000564 = InstantiatedFromUsingDecl.find(UUD);
565 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000566 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000567
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000568 return Pos->second;
569}
570
571void
John McCallb96ec562009-12-04 22:46:56 +0000572ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
573 assert((isa<UsingDecl>(Pattern) ||
574 isa<UnresolvedUsingValueDecl>(Pattern) ||
575 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
576 "pattern decl is not a using decl");
577 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
578 InstantiatedFromUsingDecl[Inst] = Pattern;
579}
580
581UsingShadowDecl *
582ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
583 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
584 = InstantiatedFromUsingShadowDecl.find(Inst);
585 if (Pos == InstantiatedFromUsingShadowDecl.end())
586 return 0;
587
588 return Pos->second;
589}
590
591void
592ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
593 UsingShadowDecl *Pattern) {
594 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
595 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000596}
597
Anders Carlsson5da84842009-09-01 04:26:58 +0000598FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
599 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
600 = InstantiatedFromUnnamedFieldDecl.find(Field);
601 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
602 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000603
Anders Carlsson5da84842009-09-01 04:26:58 +0000604 return Pos->second;
605}
606
607void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
608 FieldDecl *Tmpl) {
609 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
610 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
611 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
612 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000613
Anders Carlsson5da84842009-09-01 04:26:58 +0000614 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
615}
616
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000617bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
618 const FieldDecl *LastFD) const {
619 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000620 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000621}
622
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000623bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
624 const FieldDecl *LastFD) const {
625 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000626 FD->getBitWidthValue(*this) == 0 &&
627 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000628}
629
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000630bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
631 const FieldDecl *LastFD) const {
632 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000633 FD->getBitWidthValue(*this) &&
634 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000635}
636
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000637bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000638 const FieldDecl *LastFD) const {
639 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000640 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000641}
642
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000643bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000644 const FieldDecl *LastFD) const {
645 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000646 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000647}
648
Douglas Gregor832940b2010-03-02 23:58:15 +0000649ASTContext::overridden_cxx_method_iterator
650ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
651 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
652 = OverriddenMethods.find(Method);
653 if (Pos == OverriddenMethods.end())
654 return 0;
655
656 return Pos->second.begin();
657}
658
659ASTContext::overridden_cxx_method_iterator
660ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
661 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
662 = OverriddenMethods.find(Method);
663 if (Pos == OverriddenMethods.end())
664 return 0;
665
666 return Pos->second.end();
667}
668
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000669unsigned
670ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
671 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
672 = OverriddenMethods.find(Method);
673 if (Pos == OverriddenMethods.end())
674 return 0;
675
676 return Pos->second.size();
677}
678
Douglas Gregor832940b2010-03-02 23:58:15 +0000679void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
680 const CXXMethodDecl *Overridden) {
681 OverriddenMethods[Method].push_back(Overridden);
682}
683
Chris Lattner53cfe802007-07-18 17:52:12 +0000684//===----------------------------------------------------------------------===//
685// Type Sizing and Analysis
686//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000687
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000688/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
689/// scalar floating point type.
690const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000691 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000692 assert(BT && "Not a floating point type!");
693 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000694 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000695 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +0000696 case BuiltinType::Float: return Target->getFloatFormat();
697 case BuiltinType::Double: return Target->getDoubleFormat();
698 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000699 }
700}
701
Ken Dyck160146e2010-01-27 17:10:57 +0000702/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000703/// specified decl. Note that bitfields do not have a valid alignment, so
704/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000705/// If @p RefAsPointee, references are treated like their underlying type
706/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000707CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000708 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +0000709
John McCall94268702010-10-08 18:24:19 +0000710 bool UseAlignAttrOnly = false;
711 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
712 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000713
John McCall94268702010-10-08 18:24:19 +0000714 // __attribute__((aligned)) can increase or decrease alignment
715 // *except* on a struct or struct member, where it only increases
716 // alignment unless 'packed' is also specified.
717 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +0000718 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +0000719 // ignore that possibility; Sema should diagnose it.
720 if (isa<FieldDecl>(D)) {
721 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
722 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
723 } else {
724 UseAlignAttrOnly = true;
725 }
726 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000727 else if (isa<FieldDecl>(D))
728 UseAlignAttrOnly =
729 D->hasAttr<PackedAttr>() ||
730 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000731
John McCall4e819612011-01-20 07:57:12 +0000732 // If we're using the align attribute only, just ignore everything
733 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000734 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000735 // do nothing
736
John McCall94268702010-10-08 18:24:19 +0000737 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000738 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000739 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000740 if (RefAsPointee)
741 T = RT->getPointeeType();
742 else
743 T = getPointerType(RT->getPointeeType());
744 }
745 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000746 // Adjust alignments of declarations with array type by the
747 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +0000748 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000749 const ArrayType *arrayType;
750 if (MinWidth && (arrayType = getAsArrayType(T))) {
751 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000752 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +0000753 else if (isa<ConstantArrayType>(arrayType) &&
754 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000755 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000756
John McCall33ddac02011-01-19 10:06:00 +0000757 // Walk through any array types while we're at it.
758 T = getBaseElementType(arrayType);
759 }
Chad Rosier99ee7822011-07-26 07:03:04 +0000760 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +0000761 }
John McCall4e819612011-01-20 07:57:12 +0000762
763 // Fields can be subject to extra alignment constraints, like if
764 // the field is packed, the struct is packed, or the struct has a
765 // a max-field-alignment constraint (#pragma pack). So calculate
766 // the actual alignment of the field within the struct, and then
767 // (as we're expected to) constrain that by the alignment of the type.
768 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
769 // So calculate the alignment of the field.
770 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
771
772 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000773 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000774
775 // Use the GCD of that and the offset within the record.
776 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
777 if (offset > 0) {
778 // Alignment is always a power of 2, so the GCD will be a power of 2,
779 // which means we get to do this crazy thing instead of Euclid's.
780 uint64_t lowBitOfOffset = offset & (~offset + 1);
781 if (lowBitOfOffset < fieldAlign)
782 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
783 }
784
785 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000786 }
Chris Lattner68061312009-01-24 21:53:27 +0000787 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000788
Ken Dyckcc56c542011-01-15 18:38:59 +0000789 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000790}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000791
John McCall87fe5d52010-05-20 01:18:31 +0000792std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000793ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000794 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000795 return std::make_pair(toCharUnitsFromBits(Info.first),
796 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000797}
798
799std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000800ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000801 return getTypeInfoInChars(T.getTypePtr());
802}
803
Chris Lattner983a8bb2007-07-13 22:13:22 +0000804/// getTypeSize - Return the size of the specified type, in bits. This method
805/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000806///
807/// FIXME: Pointers into different addr spaces could have different sizes and
808/// alignment requirements: getPointerInfo should take an AddrSpace, this
809/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000810std::pair<uint64_t, unsigned>
Jay Foad39c79802011-01-12 09:06:06 +0000811ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000812 uint64_t Width=0;
813 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000814 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000815#define TYPE(Class, Base)
816#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000817#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000818#define DEPENDENT_TYPE(Class, Base) case Type::Class:
819#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +0000820 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000821 break;
822
Chris Lattner355332d2007-07-13 22:27:08 +0000823 case Type::FunctionNoProto:
824 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000825 // GCC extension: alignof(function) = 32 bits
826 Width = 0;
827 Align = 32;
828 break;
829
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000830 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000831 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000832 Width = 0;
833 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
834 break;
835
Steve Naroff5c131802007-08-30 01:06:46 +0000836 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000837 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000838
Chris Lattner37e05872008-03-05 18:54:05 +0000839 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000840 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000841 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +0000842 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000843 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000844 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000845 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000846 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000847 const VectorType *VT = cast<VectorType>(T);
848 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
849 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000850 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000851 // If the alignment is not a power of 2, round up to the next power of 2.
852 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000853 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000854 Align = llvm::NextPowerOf2(Align);
855 Width = llvm::RoundUpToAlignment(Width, Align);
856 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000857 break;
858 }
Chris Lattner647fb222007-07-18 18:26:58 +0000859
Chris Lattner7570e9c2008-03-08 08:52:55 +0000860 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000861 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000862 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000863 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000864 // GCC extension: alignof(void) = 8 bits.
865 Width = 0;
866 Align = 8;
867 break;
868
Chris Lattner6a4f7452007-12-19 19:23:28 +0000869 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000870 Width = Target->getBoolWidth();
871 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000872 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000873 case BuiltinType::Char_S:
874 case BuiltinType::Char_U:
875 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000876 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000877 Width = Target->getCharWidth();
878 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000879 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000880 case BuiltinType::WChar_S:
881 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000882 Width = Target->getWCharWidth();
883 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000884 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000885 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000886 Width = Target->getChar16Width();
887 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000888 break;
889 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000890 Width = Target->getChar32Width();
891 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000892 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000893 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000894 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000895 Width = Target->getShortWidth();
896 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000897 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000898 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000899 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000900 Width = Target->getIntWidth();
901 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000902 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000903 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000904 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000905 Width = Target->getLongWidth();
906 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000907 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000908 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000909 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000910 Width = Target->getLongLongWidth();
911 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000912 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000913 case BuiltinType::Int128:
914 case BuiltinType::UInt128:
915 Width = 128;
916 Align = 128; // int128_t is 128-bit aligned on all targets.
917 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000918 case BuiltinType::Half:
919 Width = Target->getHalfWidth();
920 Align = Target->getHalfAlign();
921 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000922 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000923 Width = Target->getFloatWidth();
924 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000925 break;
926 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000927 Width = Target->getDoubleWidth();
928 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000929 break;
930 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000931 Width = Target->getLongDoubleWidth();
932 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000933 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000934 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000935 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
936 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000937 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000938 case BuiltinType::ObjCId:
939 case BuiltinType::ObjCClass:
940 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000941 Width = Target->getPointerWidth(0);
942 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000943 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000944 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000945 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000946 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000947 Width = Target->getPointerWidth(0);
948 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000949 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000950 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000951 unsigned AS = getTargetAddressSpace(
952 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000953 Width = Target->getPointerWidth(AS);
954 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +0000955 break;
956 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000957 case Type::LValueReference:
958 case Type::RValueReference: {
959 // alignof and sizeof should never enter this code path here, so we go
960 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000961 unsigned AS = getTargetAddressSpace(
962 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000963 Width = Target->getPointerWidth(AS);
964 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000965 break;
966 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000967 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000968 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000969 Width = Target->getPointerWidth(AS);
970 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000971 break;
972 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000973 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000974 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000975 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000976 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000977 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000978 Align = PtrDiffInfo.second;
979 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000980 }
Chris Lattner647fb222007-07-18 18:26:58 +0000981 case Type::Complex: {
982 // Complex types have the same alignment as their elements, but twice the
983 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000984 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000985 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000986 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000987 Align = EltInfo.second;
988 break;
989 }
John McCall8b07ec22010-05-15 11:32:37 +0000990 case Type::ObjCObject:
991 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000992 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000993 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000994 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000995 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000996 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +0000997 break;
998 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000999 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001000 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001001 const TagType *TT = cast<TagType>(T);
1002
1003 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001004 Width = 8;
1005 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001006 break;
1007 }
Mike Stump11289f42009-09-09 15:08:12 +00001008
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001009 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001010 return getTypeInfo(ET->getDecl()->getIntegerType());
1011
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001012 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001013 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001014 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001015 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001016 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001017 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001018
Chris Lattner63d2b362009-10-22 05:17:15 +00001019 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001020 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1021 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001022
Richard Smith30482bc2011-02-20 03:19:35 +00001023 case Type::Auto: {
1024 const AutoType *A = cast<AutoType>(T);
1025 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001026 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001027 }
1028
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001029 case Type::Paren:
1030 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1031
Douglas Gregoref462e62009-04-30 17:32:17 +00001032 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001033 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001034 std::pair<uint64_t, unsigned> Info
1035 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001036 // If the typedef has an aligned attribute on it, it overrides any computed
1037 // alignment we have. This violates the GCC documentation (which says that
1038 // attribute(aligned) can only round up) but matches its implementation.
1039 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1040 Align = AttrAlign;
1041 else
1042 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001043 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001044 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001045 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001046
1047 case Type::TypeOfExpr:
1048 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1049 .getTypePtr());
1050
1051 case Type::TypeOf:
1052 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1053
Anders Carlsson81df7b82009-06-24 19:06:50 +00001054 case Type::Decltype:
1055 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1056 .getTypePtr());
1057
Alexis Hunte852b102011-05-24 22:41:36 +00001058 case Type::UnaryTransform:
1059 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1060
Abramo Bagnara6150c882010-05-11 21:36:43 +00001061 case Type::Elaborated:
1062 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001063
John McCall81904512011-01-06 01:58:22 +00001064 case Type::Attributed:
1065 return getTypeInfo(
1066 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1067
Richard Smith3f1b5d02011-05-05 21:57:07 +00001068 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001069 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001070 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001071 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1072 // A type alias template specialization may refer to a typedef with the
1073 // aligned attribute on it.
1074 if (TST->isTypeAlias())
1075 return getTypeInfo(TST->getAliasedType().getTypePtr());
1076 else
1077 return getTypeInfo(getCanonicalType(T));
1078 }
1079
Eli Friedman0dfb8892011-10-06 23:00:33 +00001080 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001081 std::pair<uint64_t, unsigned> Info
1082 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1083 Width = Info.first;
1084 Align = Info.second;
1085 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1086 llvm::isPowerOf2_64(Width)) {
1087 // We can potentially perform lock-free atomic operations for this
1088 // type; promote the alignment appropriately.
1089 // FIXME: We could potentially promote the width here as well...
1090 // is that worthwhile? (Non-struct atomic types generally have
1091 // power-of-two size anyway, but structs might not. Requires a bit
1092 // of implementation work to make sure we zero out the extra bits.)
1093 Align = static_cast<unsigned>(Width);
1094 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001095 }
1096
Douglas Gregoref462e62009-04-30 17:32:17 +00001097 }
Mike Stump11289f42009-09-09 15:08:12 +00001098
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001099 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001100 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001101}
1102
Ken Dyckcc56c542011-01-15 18:38:59 +00001103/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1104CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1105 return CharUnits::fromQuantity(BitSize / getCharWidth());
1106}
1107
Ken Dyckb0fcc592011-02-11 01:54:29 +00001108/// toBits - Convert a size in characters to a size in characters.
1109int64_t ASTContext::toBits(CharUnits CharSize) const {
1110 return CharSize.getQuantity() * getCharWidth();
1111}
1112
Ken Dyck8c89d592009-12-22 14:23:30 +00001113/// getTypeSizeInChars - Return the size of the specified type, in characters.
1114/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001115CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001116 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001117}
Jay Foad39c79802011-01-12 09:06:06 +00001118CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001119 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001120}
1121
Ken Dycka6046ab2010-01-26 17:25:18 +00001122/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001123/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001124CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001125 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001126}
Jay Foad39c79802011-01-12 09:06:06 +00001127CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001128 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001129}
1130
Chris Lattnera3402cd2009-01-27 18:08:34 +00001131/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1132/// type for the current target in bits. This can be different than the ABI
1133/// alignment in cases where it is beneficial for performance to overalign
1134/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001135unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001136 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001137
1138 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001139 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001140 T = CT->getElementType().getTypePtr();
1141 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1142 T->isSpecificBuiltinType(BuiltinType::LongLong))
1143 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1144
Chris Lattnera3402cd2009-01-27 18:08:34 +00001145 return ABIAlign;
1146}
1147
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001148/// DeepCollectObjCIvars -
1149/// This routine first collects all declared, but not synthesized, ivars in
1150/// super class and then collects all ivars, including those synthesized for
1151/// current class. This routine is used for implementation of current class
1152/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001153///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001154void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1155 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001156 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001157 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1158 DeepCollectObjCIvars(SuperClass, false, Ivars);
1159 if (!leafClass) {
1160 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1161 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +00001162 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001163 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001164 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001165 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001166 Iv= Iv->getNextIvar())
1167 Ivars.push_back(Iv);
1168 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001169}
1170
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001171/// CollectInheritedProtocols - Collect all protocols in current class and
1172/// those inherited by it.
1173void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001174 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001175 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001176 // We can use protocol_iterator here instead of
1177 // all_referenced_protocol_iterator since we are walking all categories.
1178 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1179 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001180 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001181 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001182 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001183 PE = Proto->protocol_end(); P != PE; ++P) {
1184 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001185 CollectInheritedProtocols(*P, Protocols);
1186 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001187 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001188
1189 // Categories of this Interface.
1190 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1191 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1192 CollectInheritedProtocols(CDeclChain, Protocols);
1193 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1194 while (SD) {
1195 CollectInheritedProtocols(SD, Protocols);
1196 SD = SD->getSuperClass();
1197 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001198 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001199 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001200 PE = OC->protocol_end(); P != PE; ++P) {
1201 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001202 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001203 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1204 PE = Proto->protocol_end(); P != PE; ++P)
1205 CollectInheritedProtocols(*P, Protocols);
1206 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001207 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001208 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1209 PE = OP->protocol_end(); P != PE; ++P) {
1210 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001211 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001212 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1213 PE = Proto->protocol_end(); P != PE; ++P)
1214 CollectInheritedProtocols(*P, Protocols);
1215 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001216 }
1217}
1218
Jay Foad39c79802011-01-12 09:06:06 +00001219unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001220 unsigned count = 0;
1221 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001222 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1223 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001224 count += CDecl->ivar_size();
1225
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001226 // Count ivar defined in this class's implementation. This
1227 // includes synthesized ivars.
1228 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001229 count += ImplDecl->ivar_size();
1230
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001231 return count;
1232}
1233
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001234/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1235ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1236 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1237 I = ObjCImpls.find(D);
1238 if (I != ObjCImpls.end())
1239 return cast<ObjCImplementationDecl>(I->second);
1240 return 0;
1241}
1242/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1243ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1244 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1245 I = ObjCImpls.find(D);
1246 if (I != ObjCImpls.end())
1247 return cast<ObjCCategoryImplDecl>(I->second);
1248 return 0;
1249}
1250
1251/// \brief Set the implementation of ObjCInterfaceDecl.
1252void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1253 ObjCImplementationDecl *ImplD) {
1254 assert(IFaceD && ImplD && "Passed null params");
1255 ObjCImpls[IFaceD] = ImplD;
1256}
1257/// \brief Set the implementation of ObjCCategoryDecl.
1258void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1259 ObjCCategoryImplDecl *ImplD) {
1260 assert(CatD && ImplD && "Passed null params");
1261 ObjCImpls[CatD] = ImplD;
1262}
1263
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001264/// \brief Get the copy initialization expression of VarDecl,or NULL if
1265/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001266Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001267 assert(VD && "Passed null params");
1268 assert(VD->hasAttr<BlocksAttr>() &&
1269 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001270 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001271 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001272 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1273}
1274
1275/// \brief Set the copy inialization expression of a block var decl.
1276void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1277 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001278 assert(VD->hasAttr<BlocksAttr>() &&
1279 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001280 BlockVarCopyInits[VD] = Init;
1281}
1282
John McCallbcd03502009-12-07 02:54:59 +00001283/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001284///
John McCallbcd03502009-12-07 02:54:59 +00001285/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001286/// the TypeLoc wrappers.
1287///
1288/// \param T the type that will be the basis for type source info. This type
1289/// should refer to how the declarator was written in source code, not to
1290/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001291TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001292 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001293 if (!DataSize)
1294 DataSize = TypeLoc::getFullDataSizeForType(T);
1295 else
1296 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001297 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001298
John McCallbcd03502009-12-07 02:54:59 +00001299 TypeSourceInfo *TInfo =
1300 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1301 new (TInfo) TypeSourceInfo(T);
1302 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001303}
1304
John McCallbcd03502009-12-07 02:54:59 +00001305TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001306 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001307 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001308 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001309 return DI;
1310}
1311
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001312const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001313ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001314 return getObjCLayout(D, 0);
1315}
1316
1317const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001318ASTContext::getASTObjCImplementationLayout(
1319 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001320 return getObjCLayout(D->getClassInterface(), D);
1321}
1322
Chris Lattner983a8bb2007-07-13 22:13:22 +00001323//===----------------------------------------------------------------------===//
1324// Type creation/memoization methods
1325//===----------------------------------------------------------------------===//
1326
Jay Foad39c79802011-01-12 09:06:06 +00001327QualType
John McCall33ddac02011-01-19 10:06:00 +00001328ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1329 unsigned fastQuals = quals.getFastQualifiers();
1330 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001331
1332 // Check if we've already instantiated this type.
1333 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001334 ExtQuals::Profile(ID, baseType, quals);
1335 void *insertPos = 0;
1336 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1337 assert(eq->getQualifiers() == quals);
1338 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001339 }
1340
John McCall33ddac02011-01-19 10:06:00 +00001341 // If the base type is not canonical, make the appropriate canonical type.
1342 QualType canon;
1343 if (!baseType->isCanonicalUnqualified()) {
1344 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1345 canonSplit.second.addConsistentQualifiers(quals);
1346 canon = getExtQualType(canonSplit.first, canonSplit.second);
1347
1348 // Re-find the insert position.
1349 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1350 }
1351
1352 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1353 ExtQualNodes.InsertNode(eq, insertPos);
1354 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001355}
1356
Jay Foad39c79802011-01-12 09:06:06 +00001357QualType
1358ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001359 QualType CanT = getCanonicalType(T);
1360 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001361 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001362
John McCall8ccfcb52009-09-24 19:53:00 +00001363 // If we are composing extended qualifiers together, merge together
1364 // into one ExtQuals node.
1365 QualifierCollector Quals;
1366 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001367
John McCall8ccfcb52009-09-24 19:53:00 +00001368 // If this type already has an address space specified, it cannot get
1369 // another one.
1370 assert(!Quals.hasAddressSpace() &&
1371 "Type cannot be in multiple addr spaces!");
1372 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001373
John McCall8ccfcb52009-09-24 19:53:00 +00001374 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001375}
1376
Chris Lattnerd60183d2009-02-18 22:53:11 +00001377QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001378 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001379 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001380 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001381 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001382
John McCall53fa7142010-12-24 02:08:15 +00001383 if (const PointerType *ptr = T->getAs<PointerType>()) {
1384 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001385 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001386 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1387 return getPointerType(ResultType);
1388 }
1389 }
Mike Stump11289f42009-09-09 15:08:12 +00001390
John McCall8ccfcb52009-09-24 19:53:00 +00001391 // If we are composing extended qualifiers together, merge together
1392 // into one ExtQuals node.
1393 QualifierCollector Quals;
1394 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001395
John McCall8ccfcb52009-09-24 19:53:00 +00001396 // If this type already has an ObjCGC specified, it cannot get
1397 // another one.
1398 assert(!Quals.hasObjCGCAttr() &&
1399 "Type cannot have multiple ObjCGCs!");
1400 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001401
John McCall8ccfcb52009-09-24 19:53:00 +00001402 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001403}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001404
John McCall4f5019e2010-12-19 02:44:49 +00001405const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1406 FunctionType::ExtInfo Info) {
1407 if (T->getExtInfo() == Info)
1408 return T;
1409
1410 QualType Result;
1411 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1412 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1413 } else {
1414 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1415 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1416 EPI.ExtInfo = Info;
1417 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1418 FPT->getNumArgs(), EPI);
1419 }
1420
1421 return cast<FunctionType>(Result.getTypePtr());
1422}
1423
Chris Lattnerc6395932007-06-22 20:56:16 +00001424/// getComplexType - Return the uniqued reference to the type for a complex
1425/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001426QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001427 // Unique pointers, to guarantee there is only one pointer of a particular
1428 // structure.
1429 llvm::FoldingSetNodeID ID;
1430 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001431
Chris Lattnerc6395932007-06-22 20:56:16 +00001432 void *InsertPos = 0;
1433 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1434 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001435
Chris Lattnerc6395932007-06-22 20:56:16 +00001436 // If the pointee type isn't canonical, this won't be a canonical type either,
1437 // so fill in the canonical type field.
1438 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001439 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001440 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001441
Chris Lattnerc6395932007-06-22 20:56:16 +00001442 // Get the new insert position for the node we care about.
1443 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001444 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001445 }
John McCall90d1c2d2009-09-24 23:30:46 +00001446 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001447 Types.push_back(New);
1448 ComplexTypes.InsertNode(New, InsertPos);
1449 return QualType(New, 0);
1450}
1451
Chris Lattner970e54e2006-11-12 00:37:36 +00001452/// getPointerType - Return the uniqued reference to the type for a pointer to
1453/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001454QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001455 // Unique pointers, to guarantee there is only one pointer of a particular
1456 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001457 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001458 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001459
Chris Lattner67521df2007-01-27 01:29:36 +00001460 void *InsertPos = 0;
1461 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001462 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001463
Chris Lattner7ccecb92006-11-12 08:50:50 +00001464 // If the pointee type isn't canonical, this won't be a canonical type either,
1465 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001466 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001467 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001468 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001469
Chris Lattner67521df2007-01-27 01:29:36 +00001470 // Get the new insert position for the node we care about.
1471 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001472 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001473 }
John McCall90d1c2d2009-09-24 23:30:46 +00001474 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001475 Types.push_back(New);
1476 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001477 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001478}
1479
Mike Stump11289f42009-09-09 15:08:12 +00001480/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001481/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001482QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001483 assert(T->isFunctionType() && "block of function types only");
1484 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001485 // structure.
1486 llvm::FoldingSetNodeID ID;
1487 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001488
Steve Naroffec33ed92008-08-27 16:04:49 +00001489 void *InsertPos = 0;
1490 if (BlockPointerType *PT =
1491 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1492 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001493
1494 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001495 // type either so fill in the canonical type field.
1496 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001497 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001498 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001499
Steve Naroffec33ed92008-08-27 16:04:49 +00001500 // Get the new insert position for the node we care about.
1501 BlockPointerType *NewIP =
1502 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001503 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001504 }
John McCall90d1c2d2009-09-24 23:30:46 +00001505 BlockPointerType *New
1506 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001507 Types.push_back(New);
1508 BlockPointerTypes.InsertNode(New, InsertPos);
1509 return QualType(New, 0);
1510}
1511
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001512/// getLValueReferenceType - Return the uniqued reference to the type for an
1513/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001514QualType
1515ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001516 assert(getCanonicalType(T) != OverloadTy &&
1517 "Unresolved overloaded function type");
1518
Bill Wendling3708c182007-05-27 10:15:43 +00001519 // Unique pointers, to guarantee there is only one pointer of a particular
1520 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001521 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001522 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001523
1524 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001525 if (LValueReferenceType *RT =
1526 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001527 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001528
John McCallfc93cf92009-10-22 22:37:11 +00001529 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1530
Bill Wendling3708c182007-05-27 10:15:43 +00001531 // If the referencee type isn't canonical, this won't be a canonical type
1532 // either, so fill in the canonical type field.
1533 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001534 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1535 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1536 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001537
Bill Wendling3708c182007-05-27 10:15:43 +00001538 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001539 LValueReferenceType *NewIP =
1540 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001541 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001542 }
1543
John McCall90d1c2d2009-09-24 23:30:46 +00001544 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001545 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1546 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001547 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001548 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001549
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001550 return QualType(New, 0);
1551}
1552
1553/// getRValueReferenceType - Return the uniqued reference to the type for an
1554/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001555QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001556 // Unique pointers, to guarantee there is only one pointer of a particular
1557 // structure.
1558 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001559 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001560
1561 void *InsertPos = 0;
1562 if (RValueReferenceType *RT =
1563 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1564 return QualType(RT, 0);
1565
John McCallfc93cf92009-10-22 22:37:11 +00001566 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1567
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001568 // If the referencee type isn't canonical, this won't be a canonical type
1569 // either, so fill in the canonical type field.
1570 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001571 if (InnerRef || !T.isCanonical()) {
1572 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1573 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001574
1575 // Get the new insert position for the node we care about.
1576 RValueReferenceType *NewIP =
1577 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001578 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001579 }
1580
John McCall90d1c2d2009-09-24 23:30:46 +00001581 RValueReferenceType *New
1582 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001583 Types.push_back(New);
1584 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001585 return QualType(New, 0);
1586}
1587
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001588/// getMemberPointerType - Return the uniqued reference to the type for a
1589/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001590QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001591 // Unique pointers, to guarantee there is only one pointer of a particular
1592 // structure.
1593 llvm::FoldingSetNodeID ID;
1594 MemberPointerType::Profile(ID, T, Cls);
1595
1596 void *InsertPos = 0;
1597 if (MemberPointerType *PT =
1598 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1599 return QualType(PT, 0);
1600
1601 // If the pointee or class type isn't canonical, this won't be a canonical
1602 // type either, so fill in the canonical type field.
1603 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001604 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001605 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1606
1607 // Get the new insert position for the node we care about.
1608 MemberPointerType *NewIP =
1609 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001610 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001611 }
John McCall90d1c2d2009-09-24 23:30:46 +00001612 MemberPointerType *New
1613 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001614 Types.push_back(New);
1615 MemberPointerTypes.InsertNode(New, InsertPos);
1616 return QualType(New, 0);
1617}
1618
Mike Stump11289f42009-09-09 15:08:12 +00001619/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001620/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001621QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001622 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001623 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001624 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001625 assert((EltTy->isDependentType() ||
1626 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001627 "Constant array of VLAs is illegal!");
1628
Chris Lattnere2df3f92009-05-13 04:12:56 +00001629 // Convert the array size into a canonical width matching the pointer size for
1630 // the target.
1631 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001632 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001633 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001634
Chris Lattner23b7eb62007-06-15 23:05:46 +00001635 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001636 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001637
Chris Lattner36f8e652007-01-27 08:31:04 +00001638 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001639 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001640 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001641 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001642
John McCall33ddac02011-01-19 10:06:00 +00001643 // If the element type isn't canonical or has qualifiers, this won't
1644 // be a canonical type either, so fill in the canonical type field.
1645 QualType Canon;
1646 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1647 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1648 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001649 ASM, IndexTypeQuals);
John McCall33ddac02011-01-19 10:06:00 +00001650 Canon = getQualifiedType(Canon, canonSplit.second);
1651
Chris Lattner36f8e652007-01-27 08:31:04 +00001652 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001653 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001654 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001655 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001656 }
Mike Stump11289f42009-09-09 15:08:12 +00001657
John McCall90d1c2d2009-09-24 23:30:46 +00001658 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001659 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001660 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001661 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001662 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001663}
1664
John McCall06549462011-01-18 08:40:38 +00001665/// getVariableArrayDecayedType - Turns the given type, which may be
1666/// variably-modified, into the corresponding type with all the known
1667/// sizes replaced with [*].
1668QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1669 // Vastly most common case.
1670 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001671
John McCall06549462011-01-18 08:40:38 +00001672 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001673
John McCall06549462011-01-18 08:40:38 +00001674 SplitQualType split = type.getSplitDesugaredType();
1675 const Type *ty = split.first;
1676 switch (ty->getTypeClass()) {
1677#define TYPE(Class, Base)
1678#define ABSTRACT_TYPE(Class, Base)
1679#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1680#include "clang/AST/TypeNodes.def"
1681 llvm_unreachable("didn't desugar past all non-canonical types?");
1682
1683 // These types should never be variably-modified.
1684 case Type::Builtin:
1685 case Type::Complex:
1686 case Type::Vector:
1687 case Type::ExtVector:
1688 case Type::DependentSizedExtVector:
1689 case Type::ObjCObject:
1690 case Type::ObjCInterface:
1691 case Type::ObjCObjectPointer:
1692 case Type::Record:
1693 case Type::Enum:
1694 case Type::UnresolvedUsing:
1695 case Type::TypeOfExpr:
1696 case Type::TypeOf:
1697 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001698 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001699 case Type::DependentName:
1700 case Type::InjectedClassName:
1701 case Type::TemplateSpecialization:
1702 case Type::DependentTemplateSpecialization:
1703 case Type::TemplateTypeParm:
1704 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001705 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001706 case Type::PackExpansion:
1707 llvm_unreachable("type should never be variably-modified");
1708
1709 // These types can be variably-modified but should never need to
1710 // further decay.
1711 case Type::FunctionNoProto:
1712 case Type::FunctionProto:
1713 case Type::BlockPointer:
1714 case Type::MemberPointer:
1715 return type;
1716
1717 // These types can be variably-modified. All these modifications
1718 // preserve structure except as noted by comments.
1719 // TODO: if we ever care about optimizing VLAs, there are no-op
1720 // optimizations available here.
1721 case Type::Pointer:
1722 result = getPointerType(getVariableArrayDecayedType(
1723 cast<PointerType>(ty)->getPointeeType()));
1724 break;
1725
1726 case Type::LValueReference: {
1727 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1728 result = getLValueReferenceType(
1729 getVariableArrayDecayedType(lv->getPointeeType()),
1730 lv->isSpelledAsLValue());
1731 break;
1732 }
1733
1734 case Type::RValueReference: {
1735 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1736 result = getRValueReferenceType(
1737 getVariableArrayDecayedType(lv->getPointeeType()));
1738 break;
1739 }
1740
Eli Friedman0dfb8892011-10-06 23:00:33 +00001741 case Type::Atomic: {
1742 const AtomicType *at = cast<AtomicType>(ty);
1743 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1744 break;
1745 }
1746
John McCall06549462011-01-18 08:40:38 +00001747 case Type::ConstantArray: {
1748 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1749 result = getConstantArrayType(
1750 getVariableArrayDecayedType(cat->getElementType()),
1751 cat->getSize(),
1752 cat->getSizeModifier(),
1753 cat->getIndexTypeCVRQualifiers());
1754 break;
1755 }
1756
1757 case Type::DependentSizedArray: {
1758 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1759 result = getDependentSizedArrayType(
1760 getVariableArrayDecayedType(dat->getElementType()),
1761 dat->getSizeExpr(),
1762 dat->getSizeModifier(),
1763 dat->getIndexTypeCVRQualifiers(),
1764 dat->getBracketsRange());
1765 break;
1766 }
1767
1768 // Turn incomplete types into [*] types.
1769 case Type::IncompleteArray: {
1770 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1771 result = getVariableArrayType(
1772 getVariableArrayDecayedType(iat->getElementType()),
1773 /*size*/ 0,
1774 ArrayType::Normal,
1775 iat->getIndexTypeCVRQualifiers(),
1776 SourceRange());
1777 break;
1778 }
1779
1780 // Turn VLA types into [*] types.
1781 case Type::VariableArray: {
1782 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1783 result = getVariableArrayType(
1784 getVariableArrayDecayedType(vat->getElementType()),
1785 /*size*/ 0,
1786 ArrayType::Star,
1787 vat->getIndexTypeCVRQualifiers(),
1788 vat->getBracketsRange());
1789 break;
1790 }
1791 }
1792
1793 // Apply the top-level qualifiers from the original.
1794 return getQualifiedType(result, split.second);
1795}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001796
Steve Naroffcadebd02007-08-30 18:14:25 +00001797/// getVariableArrayType - Returns a non-unique reference to the type for a
1798/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001799QualType ASTContext::getVariableArrayType(QualType EltTy,
1800 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001801 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001802 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001803 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001804 // Since we don't unique expressions, it isn't possible to unique VLA's
1805 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001806 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001807
John McCall33ddac02011-01-19 10:06:00 +00001808 // Be sure to pull qualifiers off the element type.
1809 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1810 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1811 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001812 IndexTypeQuals, Brackets);
John McCall33ddac02011-01-19 10:06:00 +00001813 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001814 }
1815
John McCall90d1c2d2009-09-24 23:30:46 +00001816 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001817 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001818
1819 VariableArrayTypes.push_back(New);
1820 Types.push_back(New);
1821 return QualType(New, 0);
1822}
1823
Douglas Gregor4619e432008-12-05 23:32:09 +00001824/// getDependentSizedArrayType - Returns a non-unique reference to
1825/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001826/// type.
John McCall33ddac02011-01-19 10:06:00 +00001827QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1828 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001829 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001830 unsigned elementTypeQuals,
1831 SourceRange brackets) const {
1832 assert((!numElements || numElements->isTypeDependent() ||
1833 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001834 "Size must be type- or value-dependent!");
1835
John McCall33ddac02011-01-19 10:06:00 +00001836 // Dependently-sized array types that do not have a specified number
1837 // of elements will have their sizes deduced from a dependent
1838 // initializer. We do no canonicalization here at all, which is okay
1839 // because they can't be used in most locations.
1840 if (!numElements) {
1841 DependentSizedArrayType *newType
1842 = new (*this, TypeAlignment)
1843 DependentSizedArrayType(*this, elementType, QualType(),
1844 numElements, ASM, elementTypeQuals,
1845 brackets);
1846 Types.push_back(newType);
1847 return QualType(newType, 0);
1848 }
1849
1850 // Otherwise, we actually build a new type every time, but we
1851 // also build a canonical type.
1852
1853 SplitQualType canonElementType = getCanonicalType(elementType).split();
1854
1855 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001856 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001857 DependentSizedArrayType::Profile(ID, *this,
1858 QualType(canonElementType.first, 0),
1859 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001860
John McCall33ddac02011-01-19 10:06:00 +00001861 // Look for an existing type with these properties.
1862 DependentSizedArrayType *canonTy =
1863 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001864
John McCall33ddac02011-01-19 10:06:00 +00001865 // If we don't have one, build one.
1866 if (!canonTy) {
1867 canonTy = new (*this, TypeAlignment)
1868 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1869 QualType(), numElements, ASM, elementTypeQuals,
1870 brackets);
1871 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1872 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001873 }
1874
John McCall33ddac02011-01-19 10:06:00 +00001875 // Apply qualifiers from the element type to the array.
1876 QualType canon = getQualifiedType(QualType(canonTy,0),
1877 canonElementType.second);
Mike Stump11289f42009-09-09 15:08:12 +00001878
John McCall33ddac02011-01-19 10:06:00 +00001879 // If we didn't need extra canonicalization for the element type,
1880 // then just use that as our result.
1881 if (QualType(canonElementType.first, 0) == elementType)
1882 return canon;
1883
1884 // Otherwise, we need to build a type which follows the spelling
1885 // of the element type.
1886 DependentSizedArrayType *sugaredType
1887 = new (*this, TypeAlignment)
1888 DependentSizedArrayType(*this, elementType, canon, numElements,
1889 ASM, elementTypeQuals, brackets);
1890 Types.push_back(sugaredType);
1891 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00001892}
1893
John McCall33ddac02011-01-19 10:06:00 +00001894QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00001895 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001896 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001897 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001898 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001899
John McCall33ddac02011-01-19 10:06:00 +00001900 void *insertPos = 0;
1901 if (IncompleteArrayType *iat =
1902 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1903 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00001904
1905 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00001906 // either, so fill in the canonical type field. We also have to pull
1907 // qualifiers off the element type.
1908 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00001909
John McCall33ddac02011-01-19 10:06:00 +00001910 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1911 SplitQualType canonSplit = getCanonicalType(elementType).split();
1912 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1913 ASM, elementTypeQuals);
1914 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanbd258282008-02-15 18:16:39 +00001915
1916 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00001917 IncompleteArrayType *existing =
1918 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1919 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001920 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001921
John McCall33ddac02011-01-19 10:06:00 +00001922 IncompleteArrayType *newType = new (*this, TypeAlignment)
1923 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001924
John McCall33ddac02011-01-19 10:06:00 +00001925 IncompleteArrayTypes.InsertNode(newType, insertPos);
1926 Types.push_back(newType);
1927 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001928}
1929
Steve Naroff91fcddb2007-07-18 18:00:27 +00001930/// getVectorType - Return the unique reference to a vector type of
1931/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001932QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001933 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00001934 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001935
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001936 // Check if we've already instantiated a vector of this type.
1937 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001938 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001939
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001940 void *InsertPos = 0;
1941 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1942 return QualType(VTP, 0);
1943
1944 // If the element type isn't canonical, this won't be a canonical type either,
1945 // so fill in the canonical type field.
1946 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001947 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001948 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001949
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001950 // Get the new insert position for the node we care about.
1951 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001952 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001953 }
John McCall90d1c2d2009-09-24 23:30:46 +00001954 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001955 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001956 VectorTypes.InsertNode(New, InsertPos);
1957 Types.push_back(New);
1958 return QualType(New, 0);
1959}
1960
Nate Begemance4d7fc2008-04-18 23:10:10 +00001961/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001962/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00001963QualType
1964ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00001965 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00001966
Steve Naroff91fcddb2007-07-18 18:00:27 +00001967 // Check if we've already instantiated a vector of this type.
1968 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001969 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001970 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001971 void *InsertPos = 0;
1972 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1973 return QualType(VTP, 0);
1974
1975 // If the element type isn't canonical, this won't be a canonical type either,
1976 // so fill in the canonical type field.
1977 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001978 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001979 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001980
Steve Naroff91fcddb2007-07-18 18:00:27 +00001981 // Get the new insert position for the node we care about.
1982 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001983 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001984 }
John McCall90d1c2d2009-09-24 23:30:46 +00001985 ExtVectorType *New = new (*this, TypeAlignment)
1986 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001987 VectorTypes.InsertNode(New, InsertPos);
1988 Types.push_back(New);
1989 return QualType(New, 0);
1990}
1991
Jay Foad39c79802011-01-12 09:06:06 +00001992QualType
1993ASTContext::getDependentSizedExtVectorType(QualType vecType,
1994 Expr *SizeExpr,
1995 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00001996 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001997 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001998 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001999
Douglas Gregor352169a2009-07-31 03:54:25 +00002000 void *InsertPos = 0;
2001 DependentSizedExtVectorType *Canon
2002 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2003 DependentSizedExtVectorType *New;
2004 if (Canon) {
2005 // We already have a canonical version of this array type; use it as
2006 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002007 New = new (*this, TypeAlignment)
2008 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2009 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002010 } else {
2011 QualType CanonVecTy = getCanonicalType(vecType);
2012 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002013 New = new (*this, TypeAlignment)
2014 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2015 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002016
2017 DependentSizedExtVectorType *CanonCheck
2018 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2019 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2020 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002021 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2022 } else {
2023 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2024 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002025 New = new (*this, TypeAlignment)
2026 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002027 }
2028 }
Mike Stump11289f42009-09-09 15:08:12 +00002029
Douglas Gregor758a8692009-06-17 21:51:59 +00002030 Types.push_back(New);
2031 return QualType(New, 0);
2032}
2033
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002034/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002035///
Jay Foad39c79802011-01-12 09:06:06 +00002036QualType
2037ASTContext::getFunctionNoProtoType(QualType ResultTy,
2038 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002039 const CallingConv DefaultCC = Info.getCC();
2040 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2041 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002042 // Unique functions, to guarantee there is only one function of a particular
2043 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002044 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002045 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002046
Chris Lattner47955de2007-01-27 08:37:20 +00002047 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002048 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002049 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002050 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002051
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002052 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002053 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002054 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002055 Canonical =
2056 getFunctionNoProtoType(getCanonicalType(ResultTy),
2057 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002058
Chris Lattner47955de2007-01-27 08:37:20 +00002059 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002060 FunctionNoProtoType *NewIP =
2061 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002062 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002063 }
Mike Stump11289f42009-09-09 15:08:12 +00002064
Roman Divacky65b88cd2011-03-01 17:40:53 +00002065 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002066 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002067 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002068 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002069 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002070 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002071}
2072
2073/// getFunctionType - Return a normal function type with a typed argument
2074/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002075QualType
2076ASTContext::getFunctionType(QualType ResultTy,
2077 const QualType *ArgArray, unsigned NumArgs,
2078 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002079 // Unique functions, to guarantee there is only one function of a particular
2080 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002081 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002082 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002083
2084 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002085 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002086 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002087 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002088
2089 // Determine whether the type being created is already canonical or not.
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002090 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002091 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002092 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002093 isCanonical = false;
2094
Roman Divacky65b88cd2011-03-01 17:40:53 +00002095 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2096 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2097 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002098
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002099 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002100 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002101 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002102 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002103 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002104 CanonicalArgs.reserve(NumArgs);
2105 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002106 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002107
John McCalldb40c7f2010-12-14 08:05:40 +00002108 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002109 CanonicalEPI.ExceptionSpecType = EST_None;
2110 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002111 CanonicalEPI.ExtInfo
2112 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2113
Chris Lattner76a00cf2008-04-06 22:59:24 +00002114 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002115 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002116 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002117
Chris Lattnerfd4de792007-01-27 01:15:32 +00002118 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002119 FunctionProtoType *NewIP =
2120 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002121 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002122 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002123
John McCall31168b02011-06-15 23:02:42 +00002124 // FunctionProtoType objects are allocated with extra bytes after
2125 // them for three variable size arrays at the end:
2126 // - parameter types
2127 // - exception types
2128 // - consumed-arguments flags
2129 // Instead of the exception types, there could be a noexcept
2130 // expression.
John McCalldb40c7f2010-12-14 08:05:40 +00002131 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002132 NumArgs * sizeof(QualType);
2133 if (EPI.ExceptionSpecType == EST_Dynamic)
2134 Size += EPI.NumExceptions * sizeof(QualType);
2135 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002136 Size += sizeof(Expr*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002137 }
John McCall31168b02011-06-15 23:02:42 +00002138 if (EPI.ConsumedArguments)
2139 Size += NumArgs * sizeof(bool);
2140
John McCalldb40c7f2010-12-14 08:05:40 +00002141 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002142 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2143 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002144 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002145 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002146 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002147 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002148}
Chris Lattneref51c202006-11-10 07:17:23 +00002149
John McCalle78aac42010-03-10 03:28:59 +00002150#ifndef NDEBUG
2151static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2152 if (!isa<CXXRecordDecl>(D)) return false;
2153 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2154 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2155 return true;
2156 if (RD->getDescribedClassTemplate() &&
2157 !isa<ClassTemplateSpecializationDecl>(RD))
2158 return true;
2159 return false;
2160}
2161#endif
2162
2163/// getInjectedClassNameType - Return the unique reference to the
2164/// injected class name type for the specified templated declaration.
2165QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002166 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002167 assert(NeedsInjectedClassNameType(Decl));
2168 if (Decl->TypeForDecl) {
2169 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00002170 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00002171 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2172 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2173 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2174 } else {
John McCall424cec92011-01-19 06:33:43 +00002175 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002176 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002177 Decl->TypeForDecl = newType;
2178 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002179 }
2180 return QualType(Decl->TypeForDecl, 0);
2181}
2182
Douglas Gregor83a586e2008-04-13 21:07:44 +00002183/// getTypeDeclType - Return the unique reference to the type for the
2184/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002185QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002186 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002187 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002188
Richard Smithdda56e42011-04-15 14:24:37 +00002189 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002190 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002191
John McCall96f0b5f2010-03-10 06:48:02 +00002192 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2193 "Template type parameter types are always available.");
2194
John McCall81e38502010-02-16 03:57:14 +00002195 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002196 assert(!Record->getPreviousDeclaration() &&
2197 "struct/union has previous declaration");
2198 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002199 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002200 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002201 assert(!Enum->getPreviousDeclaration() &&
2202 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002203 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002204 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002205 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002206 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2207 Decl->TypeForDecl = newType;
2208 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002209 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002210 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002211
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002212 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002213}
2214
Chris Lattner32d920b2007-01-26 02:01:53 +00002215/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002216/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002217QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002218ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2219 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002220 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002221
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002222 if (Canonical.isNull())
2223 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002224 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002225 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002226 Decl->TypeForDecl = newType;
2227 Types.push_back(newType);
2228 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002229}
2230
Jay Foad39c79802011-01-12 09:06:06 +00002231QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002232 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2233
2234 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2235 if (PrevDecl->TypeForDecl)
2236 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2237
John McCall424cec92011-01-19 06:33:43 +00002238 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2239 Decl->TypeForDecl = newType;
2240 Types.push_back(newType);
2241 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002242}
2243
Jay Foad39c79802011-01-12 09:06:06 +00002244QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002245 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2246
2247 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2248 if (PrevDecl->TypeForDecl)
2249 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2250
John McCall424cec92011-01-19 06:33:43 +00002251 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2252 Decl->TypeForDecl = newType;
2253 Types.push_back(newType);
2254 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002255}
2256
John McCall81904512011-01-06 01:58:22 +00002257QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2258 QualType modifiedType,
2259 QualType equivalentType) {
2260 llvm::FoldingSetNodeID id;
2261 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2262
2263 void *insertPos = 0;
2264 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2265 if (type) return QualType(type, 0);
2266
2267 QualType canon = getCanonicalType(equivalentType);
2268 type = new (*this, TypeAlignment)
2269 AttributedType(canon, attrKind, modifiedType, equivalentType);
2270
2271 Types.push_back(type);
2272 AttributedTypes.InsertNode(type, insertPos);
2273
2274 return QualType(type, 0);
2275}
2276
2277
John McCallcebee162009-10-18 09:09:24 +00002278/// \brief Retrieve a substitution-result type.
2279QualType
2280ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002281 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002282 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002283 && "replacement types must always be canonical");
2284
2285 llvm::FoldingSetNodeID ID;
2286 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2287 void *InsertPos = 0;
2288 SubstTemplateTypeParmType *SubstParm
2289 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2290
2291 if (!SubstParm) {
2292 SubstParm = new (*this, TypeAlignment)
2293 SubstTemplateTypeParmType(Parm, Replacement);
2294 Types.push_back(SubstParm);
2295 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2296 }
2297
2298 return QualType(SubstParm, 0);
2299}
2300
Douglas Gregorada4b792011-01-14 02:55:32 +00002301/// \brief Retrieve a
2302QualType ASTContext::getSubstTemplateTypeParmPackType(
2303 const TemplateTypeParmType *Parm,
2304 const TemplateArgument &ArgPack) {
2305#ifndef NDEBUG
2306 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2307 PEnd = ArgPack.pack_end();
2308 P != PEnd; ++P) {
2309 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2310 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2311 }
2312#endif
2313
2314 llvm::FoldingSetNodeID ID;
2315 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2316 void *InsertPos = 0;
2317 if (SubstTemplateTypeParmPackType *SubstParm
2318 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2319 return QualType(SubstParm, 0);
2320
2321 QualType Canon;
2322 if (!Parm->isCanonicalUnqualified()) {
2323 Canon = getCanonicalType(QualType(Parm, 0));
2324 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2325 ArgPack);
2326 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2327 }
2328
2329 SubstTemplateTypeParmPackType *SubstParm
2330 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2331 ArgPack);
2332 Types.push_back(SubstParm);
2333 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2334 return QualType(SubstParm, 0);
2335}
2336
Douglas Gregoreff93e02009-02-05 23:33:38 +00002337/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002338/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002339/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002340QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002341 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002342 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002343 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002344 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002345 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002346 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002347 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2348
2349 if (TypeParm)
2350 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002351
Chandler Carruth08836322011-05-01 00:51:33 +00002352 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002353 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002354 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002355
2356 TemplateTypeParmType *TypeCheck
2357 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2358 assert(!TypeCheck && "Template type parameter canonical type broken");
2359 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002360 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002361 TypeParm = new (*this, TypeAlignment)
2362 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002363
2364 Types.push_back(TypeParm);
2365 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2366
2367 return QualType(TypeParm, 0);
2368}
2369
John McCalle78aac42010-03-10 03:28:59 +00002370TypeSourceInfo *
2371ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2372 SourceLocation NameLoc,
2373 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002374 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002375 assert(!Name.getAsDependentTemplateName() &&
2376 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002377 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002378
2379 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2380 TemplateSpecializationTypeLoc TL
2381 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2382 TL.setTemplateNameLoc(NameLoc);
2383 TL.setLAngleLoc(Args.getLAngleLoc());
2384 TL.setRAngleLoc(Args.getRAngleLoc());
2385 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2386 TL.setArgLocInfo(i, Args[i].getLocInfo());
2387 return DI;
2388}
2389
Mike Stump11289f42009-09-09 15:08:12 +00002390QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002391ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002392 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002393 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002394 assert(!Template.getAsDependentTemplateName() &&
2395 "No dependent template names here!");
2396
John McCall6b51f282009-11-23 01:53:49 +00002397 unsigned NumArgs = Args.size();
2398
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002399 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002400 ArgVec.reserve(NumArgs);
2401 for (unsigned i = 0; i != NumArgs; ++i)
2402 ArgVec.push_back(Args[i].getArgument());
2403
John McCall2408e322010-04-27 00:57:59 +00002404 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002405 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002406}
2407
2408QualType
2409ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002410 const TemplateArgument *Args,
2411 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002412 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002413 assert(!Template.getAsDependentTemplateName() &&
2414 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002415 // Look through qualified template names.
2416 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2417 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002418
Richard Smith3f1b5d02011-05-05 21:57:07 +00002419 bool isTypeAlias =
2420 Template.getAsTemplateDecl() &&
2421 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2422
2423 QualType CanonType;
2424 if (!Underlying.isNull())
2425 CanonType = getCanonicalType(Underlying);
2426 else {
2427 assert(!isTypeAlias &&
2428 "Underlying type for template alias must be computed by caller");
2429 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2430 NumArgs);
2431 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002432
Douglas Gregora8e02e72009-07-28 23:00:59 +00002433 // Allocate the (non-canonical) template specialization type, but don't
2434 // try to unique it: these types typically have location information that
2435 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002436 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2437 sizeof(TemplateArgument) * NumArgs +
2438 (isTypeAlias ? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002439 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002440 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00002441 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00002442 Args, NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002443 CanonType,
2444 isTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002445
Douglas Gregor8bf42052009-02-09 18:46:07 +00002446 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002447 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002448}
2449
Mike Stump11289f42009-09-09 15:08:12 +00002450QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002451ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2452 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002453 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002454 assert(!Template.getAsDependentTemplateName() &&
2455 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002456 assert((!Template.getAsTemplateDecl() ||
2457 !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2458 "Underlying type for template alias must be computed by caller");
2459
Douglas Gregore29139c2011-03-03 17:04:51 +00002460 // Look through qualified template names.
2461 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2462 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002463
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002464 // Build the canonical template specialization type.
2465 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002466 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002467 CanonArgs.reserve(NumArgs);
2468 for (unsigned I = 0; I != NumArgs; ++I)
2469 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2470
2471 // Determine whether this canonical template specialization type already
2472 // exists.
2473 llvm::FoldingSetNodeID ID;
2474 TemplateSpecializationType::Profile(ID, CanonTemplate,
2475 CanonArgs.data(), NumArgs, *this);
2476
2477 void *InsertPos = 0;
2478 TemplateSpecializationType *Spec
2479 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2480
2481 if (!Spec) {
2482 // Allocate a new canonical template specialization type.
2483 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2484 sizeof(TemplateArgument) * NumArgs),
2485 TypeAlignment);
2486 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2487 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002488 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002489 Types.push_back(Spec);
2490 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2491 }
2492
2493 assert(Spec->isDependentType() &&
2494 "Non-dependent template-id type must have a canonical type");
2495 return QualType(Spec, 0);
2496}
2497
2498QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002499ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2500 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002501 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002502 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002503 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002504
2505 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002506 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002507 if (T)
2508 return QualType(T, 0);
2509
Douglas Gregorc42075a2010-02-04 18:10:26 +00002510 QualType Canon = NamedType;
2511 if (!Canon.isCanonical()) {
2512 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002513 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2514 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002515 (void)CheckT;
2516 }
2517
Abramo Bagnara6150c882010-05-11 21:36:43 +00002518 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002519 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002520 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002521 return QualType(T, 0);
2522}
2523
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002524QualType
Jay Foad39c79802011-01-12 09:06:06 +00002525ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002526 llvm::FoldingSetNodeID ID;
2527 ParenType::Profile(ID, InnerType);
2528
2529 void *InsertPos = 0;
2530 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2531 if (T)
2532 return QualType(T, 0);
2533
2534 QualType Canon = InnerType;
2535 if (!Canon.isCanonical()) {
2536 Canon = getCanonicalType(InnerType);
2537 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2538 assert(!CheckT && "Paren canonical type broken");
2539 (void)CheckT;
2540 }
2541
2542 T = new (*this) ParenType(InnerType, Canon);
2543 Types.push_back(T);
2544 ParenTypes.InsertNode(T, InsertPos);
2545 return QualType(T, 0);
2546}
2547
Douglas Gregor02085352010-03-31 20:19:30 +00002548QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2549 NestedNameSpecifier *NNS,
2550 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002551 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002552 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2553
2554 if (Canon.isNull()) {
2555 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002556 ElaboratedTypeKeyword CanonKeyword = Keyword;
2557 if (Keyword == ETK_None)
2558 CanonKeyword = ETK_Typename;
2559
2560 if (CanonNNS != NNS || CanonKeyword != Keyword)
2561 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002562 }
2563
2564 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002565 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002566
2567 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002568 DependentNameType *T
2569 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002570 if (T)
2571 return QualType(T, 0);
2572
Douglas Gregor02085352010-03-31 20:19:30 +00002573 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002574 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002575 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002576 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002577}
2578
Mike Stump11289f42009-09-09 15:08:12 +00002579QualType
John McCallc392f372010-06-11 00:33:02 +00002580ASTContext::getDependentTemplateSpecializationType(
2581 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002582 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002583 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002584 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002585 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002586 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002587 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2588 ArgCopy.push_back(Args[I].getArgument());
2589 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2590 ArgCopy.size(),
2591 ArgCopy.data());
2592}
2593
2594QualType
2595ASTContext::getDependentTemplateSpecializationType(
2596 ElaboratedTypeKeyword Keyword,
2597 NestedNameSpecifier *NNS,
2598 const IdentifierInfo *Name,
2599 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002600 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002601 assert((!NNS || NNS->isDependent()) &&
2602 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002603
Douglas Gregorc42075a2010-02-04 18:10:26 +00002604 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002605 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2606 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002607
2608 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002609 DependentTemplateSpecializationType *T
2610 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002611 if (T)
2612 return QualType(T, 0);
2613
John McCallc392f372010-06-11 00:33:02 +00002614 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002615
John McCallc392f372010-06-11 00:33:02 +00002616 ElaboratedTypeKeyword CanonKeyword = Keyword;
2617 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2618
2619 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002620 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002621 for (unsigned I = 0; I != NumArgs; ++I) {
2622 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2623 if (!CanonArgs[I].structurallyEquals(Args[I]))
2624 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002625 }
2626
John McCallc392f372010-06-11 00:33:02 +00002627 QualType Canon;
2628 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2629 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2630 Name, NumArgs,
2631 CanonArgs.data());
2632
2633 // Find the insert position again.
2634 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2635 }
2636
2637 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2638 sizeof(TemplateArgument) * NumArgs),
2639 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002640 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002641 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002642 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002643 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002644 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002645}
2646
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002647QualType ASTContext::getPackExpansionType(QualType Pattern,
2648 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002649 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002650 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002651
2652 assert(Pattern->containsUnexpandedParameterPack() &&
2653 "Pack expansions must expand one or more parameter packs");
2654 void *InsertPos = 0;
2655 PackExpansionType *T
2656 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2657 if (T)
2658 return QualType(T, 0);
2659
2660 QualType Canon;
2661 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002662 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002663
2664 // Find the insert position again.
2665 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2666 }
2667
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002668 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002669 Types.push_back(T);
2670 PackExpansionTypes.InsertNode(T, InsertPos);
2671 return QualType(T, 0);
2672}
2673
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002674/// CmpProtocolNames - Comparison predicate for sorting protocols
2675/// alphabetically.
2676static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2677 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002678 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002679}
2680
John McCall8b07ec22010-05-15 11:32:37 +00002681static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002682 unsigned NumProtocols) {
2683 if (NumProtocols == 0) return true;
2684
2685 for (unsigned i = 1; i != NumProtocols; ++i)
2686 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2687 return false;
2688 return true;
2689}
2690
2691static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002692 unsigned &NumProtocols) {
2693 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002694
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002695 // Sort protocols, keyed by name.
2696 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2697
2698 // Remove duplicates.
2699 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2700 NumProtocols = ProtocolsEnd-Protocols;
2701}
2702
John McCall8b07ec22010-05-15 11:32:37 +00002703QualType ASTContext::getObjCObjectType(QualType BaseType,
2704 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002705 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002706 // If the base type is an interface and there aren't any protocols
2707 // to add, then the interface type will do just fine.
2708 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2709 return BaseType;
2710
2711 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002712 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002713 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002714 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002715 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2716 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002717
John McCall8b07ec22010-05-15 11:32:37 +00002718 // Build the canonical type, which has the canonical base type and
2719 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002720 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002721 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2722 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2723 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002724 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002725 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002726 unsigned UniqueCount = NumProtocols;
2727
John McCallfc93cf92009-10-22 22:37:11 +00002728 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002729 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2730 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002731 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002732 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2733 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002734 }
2735
2736 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002737 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2738 }
2739
2740 unsigned Size = sizeof(ObjCObjectTypeImpl);
2741 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2742 void *Mem = Allocate(Size, TypeAlignment);
2743 ObjCObjectTypeImpl *T =
2744 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2745
2746 Types.push_back(T);
2747 ObjCObjectTypes.InsertNode(T, InsertPos);
2748 return QualType(T, 0);
2749}
2750
2751/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2752/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002753QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002754 llvm::FoldingSetNodeID ID;
2755 ObjCObjectPointerType::Profile(ID, ObjectT);
2756
2757 void *InsertPos = 0;
2758 if (ObjCObjectPointerType *QT =
2759 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2760 return QualType(QT, 0);
2761
2762 // Find the canonical object type.
2763 QualType Canonical;
2764 if (!ObjectT.isCanonical()) {
2765 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2766
2767 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002768 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2769 }
2770
Douglas Gregorf85bee62010-02-08 22:59:26 +00002771 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002772 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2773 ObjCObjectPointerType *QType =
2774 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002775
Steve Narofffb4330f2009-06-17 22:40:22 +00002776 Types.push_back(QType);
2777 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002778 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002779}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002780
Douglas Gregor1c283312010-08-11 12:19:30 +00002781/// getObjCInterfaceType - Return the unique reference to the type for the
2782/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad39c79802011-01-12 09:06:06 +00002783QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002784 if (Decl->TypeForDecl)
2785 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002786
Douglas Gregor1c283312010-08-11 12:19:30 +00002787 // FIXME: redeclarations?
2788 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2789 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2790 Decl->TypeForDecl = T;
2791 Types.push_back(T);
2792 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002793}
2794
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002795/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2796/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002797/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002798/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002799/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002800QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002801 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002802 if (tofExpr->isTypeDependent()) {
2803 llvm::FoldingSetNodeID ID;
2804 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002805
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002806 void *InsertPos = 0;
2807 DependentTypeOfExprType *Canon
2808 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2809 if (Canon) {
2810 // We already have a "canonical" version of an identical, dependent
2811 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002812 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002813 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002814 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002815 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002816 Canon
2817 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002818 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2819 toe = Canon;
2820 }
2821 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002822 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002823 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002824 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002825 Types.push_back(toe);
2826 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002827}
2828
Steve Naroffa773cd52007-08-01 18:02:17 +00002829/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2830/// TypeOfType AST's. The only motivation to unique these nodes would be
2831/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002832/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002833/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002834QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002835 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002836 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002837 Types.push_back(tot);
2838 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002839}
2840
Anders Carlssonad6bd352009-06-24 21:24:56 +00002841/// getDecltypeForExpr - Given an expr, will return the decltype for that
2842/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad39c79802011-01-12 09:06:06 +00002843static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002844 if (e->isTypeDependent())
2845 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002846
Anders Carlssonad6bd352009-06-24 21:24:56 +00002847 // If e is an id expression or a class member access, decltype(e) is defined
2848 // as the type of the entity named by e.
2849 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2850 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2851 return VD->getType();
2852 }
2853 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2854 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2855 return FD->getType();
2856 }
2857 // If e is a function call or an invocation of an overloaded operator,
2858 // (parentheses around e are ignored), decltype(e) is defined as the
2859 // return type of that function.
2860 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2861 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002862
Anders Carlssonad6bd352009-06-24 21:24:56 +00002863 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002864
2865 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002866 // defined as T&, otherwise decltype(e) is defined as T.
John McCall086a4642010-11-24 05:12:34 +00002867 if (e->isLValue())
Anders Carlssonad6bd352009-06-24 21:24:56 +00002868 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002869
Anders Carlssonad6bd352009-06-24 21:24:56 +00002870 return T;
2871}
2872
Anders Carlsson81df7b82009-06-24 19:06:50 +00002873/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2874/// DecltypeType AST's. The only motivation to unique these nodes would be
2875/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002876/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002877/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002878QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002879 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00002880
2881 // C++0x [temp.type]p2:
2882 // If an expression e involves a template parameter, decltype(e) denotes a
2883 // unique dependent type. Two such decltype-specifiers refer to the same
2884 // type only if their expressions are equivalent (14.5.6.1).
2885 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002886 llvm::FoldingSetNodeID ID;
2887 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002888
Douglas Gregora21f6c32009-07-30 23:36:40 +00002889 void *InsertPos = 0;
2890 DependentDecltypeType *Canon
2891 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2892 if (Canon) {
2893 // We already have a "canonical" version of an equivalent, dependent
2894 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002895 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002896 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002897 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002898 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002899 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002900 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2901 dt = Canon;
2902 }
2903 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002904 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002905 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002906 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002907 Types.push_back(dt);
2908 return QualType(dt, 0);
2909}
2910
Alexis Hunte852b102011-05-24 22:41:36 +00002911/// getUnaryTransformationType - We don't unique these, since the memory
2912/// savings are minimal and these are rare.
2913QualType ASTContext::getUnaryTransformType(QualType BaseType,
2914 QualType UnderlyingType,
2915 UnaryTransformType::UTTKind Kind)
2916 const {
2917 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00002918 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2919 Kind,
2920 UnderlyingType->isDependentType() ?
2921 QualType() : UnderlyingType);
Alexis Hunte852b102011-05-24 22:41:36 +00002922 Types.push_back(Ty);
2923 return QualType(Ty, 0);
2924}
2925
Richard Smithb2bc2e62011-02-21 20:05:19 +00002926/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00002927QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00002928 void *InsertPos = 0;
2929 if (!DeducedType.isNull()) {
2930 // Look in the folding set for an existing type.
2931 llvm::FoldingSetNodeID ID;
2932 AutoType::Profile(ID, DeducedType);
2933 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2934 return QualType(AT, 0);
2935 }
2936
2937 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2938 Types.push_back(AT);
2939 if (InsertPos)
2940 AutoTypes.InsertNode(AT, InsertPos);
2941 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00002942}
2943
Eli Friedman0dfb8892011-10-06 23:00:33 +00002944/// getAtomicType - Return the uniqued reference to the atomic type for
2945/// the given value type.
2946QualType ASTContext::getAtomicType(QualType T) const {
2947 // Unique pointers, to guarantee there is only one pointer of a particular
2948 // structure.
2949 llvm::FoldingSetNodeID ID;
2950 AtomicType::Profile(ID, T);
2951
2952 void *InsertPos = 0;
2953 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
2954 return QualType(AT, 0);
2955
2956 // If the atomic value type isn't canonical, this won't be a canonical type
2957 // either, so fill in the canonical type field.
2958 QualType Canonical;
2959 if (!T.isCanonical()) {
2960 Canonical = getAtomicType(getCanonicalType(T));
2961
2962 // Get the new insert position for the node we care about.
2963 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
2964 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2965 }
2966 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
2967 Types.push_back(New);
2968 AtomicTypes.InsertNode(New, InsertPos);
2969 return QualType(New, 0);
2970}
2971
Richard Smith02e85f32011-04-14 22:09:26 +00002972/// getAutoDeductType - Get type pattern for deducing against 'auto'.
2973QualType ASTContext::getAutoDeductType() const {
2974 if (AutoDeductTy.isNull())
2975 AutoDeductTy = getAutoType(QualType());
2976 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
2977 return AutoDeductTy;
2978}
2979
2980/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
2981QualType ASTContext::getAutoRRefDeductType() const {
2982 if (AutoRRefDeductTy.isNull())
2983 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
2984 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
2985 return AutoRRefDeductTy;
2986}
2987
Chris Lattnerfb072462007-01-23 05:45:31 +00002988/// getTagDeclType - Return the unique reference to the type for the
2989/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00002990QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002991 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002992 // FIXME: What is the design on getTagDeclType when it requires casting
2993 // away const? mutable?
2994 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002995}
2996
Mike Stump11289f42009-09-09 15:08:12 +00002997/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2998/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2999/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003000CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003001 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003002}
Chris Lattnerfb072462007-01-23 05:45:31 +00003003
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003004/// getSignedWCharType - Return the type of "signed wchar_t".
3005/// Used when in C++, as a GCC extension.
3006QualType ASTContext::getSignedWCharType() const {
3007 // FIXME: derive from "Target" ?
3008 return WCharTy;
3009}
3010
3011/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3012/// Used when in C++, as a GCC extension.
3013QualType ASTContext::getUnsignedWCharType() const {
3014 // FIXME: derive from "Target" ?
3015 return UnsignedIntTy;
3016}
3017
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003018/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
3019/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3020QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003021 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003022}
3023
Chris Lattnera21ad802008-04-02 05:18:44 +00003024//===----------------------------------------------------------------------===//
3025// Type Operators
3026//===----------------------------------------------------------------------===//
3027
Jay Foad39c79802011-01-12 09:06:06 +00003028CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003029 // Push qualifiers into arrays, and then discard any remaining
3030 // qualifiers.
3031 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003032 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003033 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003034 QualType Result;
3035 if (isa<ArrayType>(Ty)) {
3036 Result = getArrayDecayedType(QualType(Ty,0));
3037 } else if (isa<FunctionType>(Ty)) {
3038 Result = getPointerType(QualType(Ty, 0));
3039 } else {
3040 Result = QualType(Ty, 0);
3041 }
3042
3043 return CanQualType::CreateUnsafe(Result);
3044}
3045
John McCall6c9dd522011-01-18 07:41:22 +00003046QualType ASTContext::getUnqualifiedArrayType(QualType type,
3047 Qualifiers &quals) {
3048 SplitQualType splitType = type.getSplitUnqualifiedType();
3049
3050 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3051 // the unqualified desugared type and then drops it on the floor.
3052 // We then have to strip that sugar back off with
3053 // getUnqualifiedDesugaredType(), which is silly.
3054 const ArrayType *AT =
3055 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
3056
3057 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003058 if (!AT) {
John McCall6c9dd522011-01-18 07:41:22 +00003059 quals = splitType.second;
3060 return QualType(splitType.first, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003061 }
3062
John McCall6c9dd522011-01-18 07:41:22 +00003063 // Otherwise, recurse on the array's element type.
3064 QualType elementType = AT->getElementType();
3065 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3066
3067 // If that didn't change the element type, AT has no qualifiers, so we
3068 // can just use the results in splitType.
3069 if (elementType == unqualElementType) {
3070 assert(quals.empty()); // from the recursive call
3071 quals = splitType.second;
3072 return QualType(splitType.first, 0);
3073 }
3074
3075 // Otherwise, add in the qualifiers from the outermost type, then
3076 // build the type back up.
3077 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003078
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003079 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003080 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003081 CAT->getSizeModifier(), 0);
3082 }
3083
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003084 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003085 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003086 }
3087
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003088 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003089 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003090 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003091 VAT->getSizeModifier(),
3092 VAT->getIndexTypeCVRQualifiers(),
3093 VAT->getBracketsRange());
3094 }
3095
3096 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003097 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003098 DSAT->getSizeModifier(), 0,
3099 SourceRange());
3100}
3101
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003102/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3103/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3104/// they point to and return true. If T1 and T2 aren't pointer types
3105/// or pointer-to-member types, or if they are not similar at this
3106/// level, returns false and leaves T1 and T2 unchanged. Top-level
3107/// qualifiers on T1 and T2 are ignored. This function will typically
3108/// be called in a loop that successively "unwraps" pointer and
3109/// pointer-to-member types to compare them at each level.
3110bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3111 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3112 *T2PtrType = T2->getAs<PointerType>();
3113 if (T1PtrType && T2PtrType) {
3114 T1 = T1PtrType->getPointeeType();
3115 T2 = T2PtrType->getPointeeType();
3116 return true;
3117 }
3118
3119 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3120 *T2MPType = T2->getAs<MemberPointerType>();
3121 if (T1MPType && T2MPType &&
3122 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3123 QualType(T2MPType->getClass(), 0))) {
3124 T1 = T1MPType->getPointeeType();
3125 T2 = T2MPType->getPointeeType();
3126 return true;
3127 }
3128
3129 if (getLangOptions().ObjC1) {
3130 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3131 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3132 if (T1OPType && T2OPType) {
3133 T1 = T1OPType->getPointeeType();
3134 T2 = T2OPType->getPointeeType();
3135 return true;
3136 }
3137 }
3138
3139 // FIXME: Block pointers, too?
3140
3141 return false;
3142}
3143
Jay Foad39c79802011-01-12 09:06:06 +00003144DeclarationNameInfo
3145ASTContext::getNameForTemplate(TemplateName Name,
3146 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003147 switch (Name.getKind()) {
3148 case TemplateName::QualifiedTemplate:
3149 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003150 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003151 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3152 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003153
John McCalld9dfe3a2011-06-30 08:33:18 +00003154 case TemplateName::OverloadedTemplate: {
3155 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3156 // DNInfo work in progress: CHECKME: what about DNLoc?
3157 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3158 }
3159
3160 case TemplateName::DependentTemplate: {
3161 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003162 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003163 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003164 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3165 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003166 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003167 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3168 // DNInfo work in progress: FIXME: source locations?
3169 DeclarationNameLoc DNLoc;
3170 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3171 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3172 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003173 }
3174 }
3175
John McCalld9dfe3a2011-06-30 08:33:18 +00003176 case TemplateName::SubstTemplateTemplateParm: {
3177 SubstTemplateTemplateParmStorage *subst
3178 = Name.getAsSubstTemplateTemplateParm();
3179 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3180 NameLoc);
3181 }
3182
3183 case TemplateName::SubstTemplateTemplateParmPack: {
3184 SubstTemplateTemplateParmPackStorage *subst
3185 = Name.getAsSubstTemplateTemplateParmPack();
3186 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3187 NameLoc);
3188 }
3189 }
3190
3191 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003192}
3193
Jay Foad39c79802011-01-12 09:06:06 +00003194TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003195 switch (Name.getKind()) {
3196 case TemplateName::QualifiedTemplate:
3197 case TemplateName::Template: {
3198 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003199 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003200 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003201 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3202
3203 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003204 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003205 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003206
John McCalld9dfe3a2011-06-30 08:33:18 +00003207 case TemplateName::OverloadedTemplate:
3208 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003209
John McCalld9dfe3a2011-06-30 08:33:18 +00003210 case TemplateName::DependentTemplate: {
3211 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3212 assert(DTN && "Non-dependent template names must refer to template decls.");
3213 return DTN->CanonicalTemplateName;
3214 }
3215
3216 case TemplateName::SubstTemplateTemplateParm: {
3217 SubstTemplateTemplateParmStorage *subst
3218 = Name.getAsSubstTemplateTemplateParm();
3219 return getCanonicalTemplateName(subst->getReplacement());
3220 }
3221
3222 case TemplateName::SubstTemplateTemplateParmPack: {
3223 SubstTemplateTemplateParmPackStorage *subst
3224 = Name.getAsSubstTemplateTemplateParmPack();
3225 TemplateTemplateParmDecl *canonParameter
3226 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3227 TemplateArgument canonArgPack
3228 = getCanonicalTemplateArgument(subst->getArgumentPack());
3229 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3230 }
3231 }
3232
3233 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003234}
3235
Douglas Gregoradee3e32009-11-11 23:06:43 +00003236bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3237 X = getCanonicalTemplateName(X);
3238 Y = getCanonicalTemplateName(Y);
3239 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3240}
3241
Mike Stump11289f42009-09-09 15:08:12 +00003242TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003243ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003244 switch (Arg.getKind()) {
3245 case TemplateArgument::Null:
3246 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003247
Douglas Gregora8e02e72009-07-28 23:00:59 +00003248 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003249 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003250
Douglas Gregora8e02e72009-07-28 23:00:59 +00003251 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00003252 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003253
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003254 case TemplateArgument::Template:
3255 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003256
3257 case TemplateArgument::TemplateExpansion:
3258 return TemplateArgument(getCanonicalTemplateName(
3259 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003260 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003261
Douglas Gregora8e02e72009-07-28 23:00:59 +00003262 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00003263 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003264 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003265
Douglas Gregora8e02e72009-07-28 23:00:59 +00003266 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003267 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003268
Douglas Gregora8e02e72009-07-28 23:00:59 +00003269 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003270 if (Arg.pack_size() == 0)
3271 return Arg;
3272
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003273 TemplateArgument *CanonArgs
3274 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003275 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003276 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003277 AEnd = Arg.pack_end();
3278 A != AEnd; (void)++A, ++Idx)
3279 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003280
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003281 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003282 }
3283 }
3284
3285 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003286 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003287}
3288
Douglas Gregor333489b2009-03-27 23:10:48 +00003289NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003290ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003291 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003292 return 0;
3293
3294 switch (NNS->getKind()) {
3295 case NestedNameSpecifier::Identifier:
3296 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003297 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003298 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3299 NNS->getAsIdentifier());
3300
3301 case NestedNameSpecifier::Namespace:
3302 // A namespace is canonical; build a nested-name-specifier with
3303 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003304 return NestedNameSpecifier::Create(*this, 0,
3305 NNS->getAsNamespace()->getOriginalNamespace());
3306
3307 case NestedNameSpecifier::NamespaceAlias:
3308 // A namespace is canonical; build a nested-name-specifier with
3309 // this namespace and no prefix.
3310 return NestedNameSpecifier::Create(*this, 0,
3311 NNS->getAsNamespaceAlias()->getNamespace()
3312 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003313
3314 case NestedNameSpecifier::TypeSpec:
3315 case NestedNameSpecifier::TypeSpecWithTemplate: {
3316 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003317
3318 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3319 // break it apart into its prefix and identifier, then reconsititute those
3320 // as the canonical nested-name-specifier. This is required to canonicalize
3321 // a dependent nested-name-specifier involving typedefs of dependent-name
3322 // types, e.g.,
3323 // typedef typename T::type T1;
3324 // typedef typename T1::type T2;
3325 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3326 NestedNameSpecifier *Prefix
3327 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3328 return NestedNameSpecifier::Create(*this, Prefix,
3329 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3330 }
3331
Douglas Gregorcc10cbf2010-11-04 00:14:23 +00003332 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor3ade5702010-11-04 00:09:33 +00003333 if (const DependentTemplateSpecializationType *DTST
3334 = T->getAs<DependentTemplateSpecializationType>()) {
3335 NestedNameSpecifier *Prefix
3336 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregor6e068012011-02-28 00:04:36 +00003337
3338 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3339 Prefix, DTST->getIdentifier(),
3340 DTST->getNumArgs(),
3341 DTST->getArgs());
Douglas Gregor3ade5702010-11-04 00:09:33 +00003342 T = getCanonicalType(T);
3343 }
3344
John McCall33ddac02011-01-19 10:06:00 +00003345 return NestedNameSpecifier::Create(*this, 0, false,
3346 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003347 }
3348
3349 case NestedNameSpecifier::Global:
3350 // The global specifier is canonical and unique.
3351 return NNS;
3352 }
3353
3354 // Required to silence a GCC warning
3355 return 0;
3356}
3357
Chris Lattner7adf0762008-08-04 07:31:14 +00003358
Jay Foad39c79802011-01-12 09:06:06 +00003359const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003360 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003361 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003362 // Handle the common positive case fast.
3363 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3364 return AT;
3365 }
Mike Stump11289f42009-09-09 15:08:12 +00003366
John McCall8ccfcb52009-09-24 19:53:00 +00003367 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003368 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003369 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003370
John McCall8ccfcb52009-09-24 19:53:00 +00003371 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003372 // implements C99 6.7.3p8: "If the specification of an array type includes
3373 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003374
Chris Lattner7adf0762008-08-04 07:31:14 +00003375 // If we get here, we either have type qualifiers on the type, or we have
3376 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003377 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003378
John McCall33ddac02011-01-19 10:06:00 +00003379 SplitQualType split = T.getSplitDesugaredType();
3380 Qualifiers qs = split.second;
Mike Stump11289f42009-09-09 15:08:12 +00003381
Chris Lattner7adf0762008-08-04 07:31:14 +00003382 // If we have a simple case, just return now.
John McCall33ddac02011-01-19 10:06:00 +00003383 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3384 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003385 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003386
Chris Lattner7adf0762008-08-04 07:31:14 +00003387 // Otherwise, we have an array and we have qualifiers on it. Push the
3388 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003389 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003390
Chris Lattner7adf0762008-08-04 07:31:14 +00003391 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3392 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3393 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003394 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003395 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3396 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3397 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003398 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003399
Mike Stump11289f42009-09-09 15:08:12 +00003400 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003401 = dyn_cast<DependentSizedArrayType>(ATy))
3402 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003403 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003404 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003405 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003406 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003407 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003408
Chris Lattner7adf0762008-08-04 07:31:14 +00003409 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003410 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003411 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003412 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003413 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003414 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003415}
3416
Douglas Gregor84280642011-07-12 04:42:08 +00003417QualType ASTContext::getAdjustedParameterType(QualType T) {
3418 // C99 6.7.5.3p7:
3419 // A declaration of a parameter as "array of type" shall be
3420 // adjusted to "qualified pointer to type", where the type
3421 // qualifiers (if any) are those specified within the [ and ] of
3422 // the array type derivation.
3423 if (T->isArrayType())
3424 return getArrayDecayedType(T);
3425
3426 // C99 6.7.5.3p8:
3427 // A declaration of a parameter as "function returning type"
3428 // shall be adjusted to "pointer to function returning type", as
3429 // in 6.3.2.1.
3430 if (T->isFunctionType())
3431 return getPointerType(T);
3432
3433 return T;
3434}
3435
3436QualType ASTContext::getSignatureParameterType(QualType T) {
3437 T = getVariableArrayDecayedType(T);
3438 T = getAdjustedParameterType(T);
3439 return T.getUnqualifiedType();
3440}
3441
Chris Lattnera21ad802008-04-02 05:18:44 +00003442/// getArrayDecayedType - Return the properly qualified result of decaying the
3443/// specified array type to a pointer. This operation is non-trivial when
3444/// handling typedefs etc. The canonical type of "T" must be an array type,
3445/// this returns a pointer to a properly qualified element of the array.
3446///
3447/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003448QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003449 // Get the element type with 'getAsArrayType' so that we don't lose any
3450 // typedefs in the element type of the array. This also handles propagation
3451 // of type qualifiers from the array type into the element type if present
3452 // (C99 6.7.3p8).
3453 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3454 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003455
Chris Lattner7adf0762008-08-04 07:31:14 +00003456 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003457
3458 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003459 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003460}
3461
John McCall33ddac02011-01-19 10:06:00 +00003462QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3463 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003464}
3465
John McCall33ddac02011-01-19 10:06:00 +00003466QualType ASTContext::getBaseElementType(QualType type) const {
3467 Qualifiers qs;
3468 while (true) {
3469 SplitQualType split = type.getSplitDesugaredType();
3470 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3471 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003472
John McCall33ddac02011-01-19 10:06:00 +00003473 type = array->getElementType();
3474 qs.addConsistentQualifiers(split.second);
3475 }
Mike Stump11289f42009-09-09 15:08:12 +00003476
John McCall33ddac02011-01-19 10:06:00 +00003477 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003478}
3479
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003480/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003481uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003482ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3483 uint64_t ElementCount = 1;
3484 do {
3485 ElementCount *= CA->getSize().getZExtValue();
3486 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3487 } while (CA);
3488 return ElementCount;
3489}
3490
Steve Naroff0af91202007-04-27 21:51:21 +00003491/// getFloatingRank - Return a relative rank for floating point types.
3492/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003493static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003494 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003495 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003496
John McCall9dd450b2009-09-21 23:43:11 +00003497 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3498 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003499 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003500 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003501 case BuiltinType::Float: return FloatRank;
3502 case BuiltinType::Double: return DoubleRank;
3503 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003504 }
3505}
3506
Mike Stump11289f42009-09-09 15:08:12 +00003507/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3508/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003509/// 'typeDomain' is a real floating point or complex type.
3510/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003511QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3512 QualType Domain) const {
3513 FloatingRank EltRank = getFloatingRank(Size);
3514 if (Domain->isComplexType()) {
3515 switch (EltRank) {
David Blaikie83d382b2011-09-23 05:06:16 +00003516 default: llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00003517 case FloatRank: return FloatComplexTy;
3518 case DoubleRank: return DoubleComplexTy;
3519 case LongDoubleRank: return LongDoubleComplexTy;
3520 }
Steve Naroff0af91202007-04-27 21:51:21 +00003521 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003522
3523 assert(Domain->isRealFloatingType() && "Unknown domain!");
3524 switch (EltRank) {
David Blaikie83d382b2011-09-23 05:06:16 +00003525 default: llvm_unreachable("getFloatingRank(): illegal value for rank");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003526 case FloatRank: return FloatTy;
3527 case DoubleRank: return DoubleTy;
3528 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003529 }
Steve Naroffe4718892007-04-27 18:30:00 +00003530}
3531
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003532/// getFloatingTypeOrder - Compare the rank of the two specified floating
3533/// point types, ignoring the domain of the type (i.e. 'double' ==
3534/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003535/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003536int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003537 FloatingRank LHSR = getFloatingRank(LHS);
3538 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003539
Chris Lattnerb90739d2008-04-06 23:38:49 +00003540 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003541 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003542 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003543 return 1;
3544 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003545}
3546
Chris Lattner76a00cf2008-04-06 22:59:24 +00003547/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3548/// routine will assert if passed a built-in type that isn't an integer or enum,
3549/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003550unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003551 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003552
Chris Lattner76a00cf2008-04-06 22:59:24 +00003553 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003554 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003555 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003556 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003557 case BuiltinType::Char_S:
3558 case BuiltinType::Char_U:
3559 case BuiltinType::SChar:
3560 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003561 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003562 case BuiltinType::Short:
3563 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003564 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003565 case BuiltinType::Int:
3566 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003567 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003568 case BuiltinType::Long:
3569 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003570 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003571 case BuiltinType::LongLong:
3572 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003573 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003574 case BuiltinType::Int128:
3575 case BuiltinType::UInt128:
3576 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003577 }
3578}
3579
Eli Friedman629ffb92009-08-20 04:21:42 +00003580/// \brief Whether this is a promotable bitfield reference according
3581/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3582///
3583/// \returns the type this bit-field will promote to, or NULL if no
3584/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003585QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003586 if (E->isTypeDependent() || E->isValueDependent())
3587 return QualType();
3588
Eli Friedman629ffb92009-08-20 04:21:42 +00003589 FieldDecl *Field = E->getBitField();
3590 if (!Field)
3591 return QualType();
3592
3593 QualType FT = Field->getType();
3594
Richard Smithcaf33902011-10-10 18:28:20 +00003595 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00003596 uint64_t IntSize = getTypeSize(IntTy);
3597 // GCC extension compatibility: if the bit-field size is less than or equal
3598 // to the size of int, it gets promoted no matter what its type is.
3599 // For instance, unsigned long bf : 4 gets promoted to signed int.
3600 if (BitWidth < IntSize)
3601 return IntTy;
3602
3603 if (BitWidth == IntSize)
3604 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3605
3606 // Types bigger than int are not subject to promotions, and therefore act
3607 // like the base type.
3608 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3609 // is ridiculous.
3610 return QualType();
3611}
3612
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003613/// getPromotedIntegerType - Returns the type that Promotable will
3614/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3615/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003616QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003617 assert(!Promotable.isNull());
3618 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003619 if (const EnumType *ET = Promotable->getAs<EnumType>())
3620 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00003621
3622 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3623 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3624 // (3.9.1) can be converted to a prvalue of the first of the following
3625 // types that can represent all the values of its underlying type:
3626 // int, unsigned int, long int, unsigned long int, long long int, or
3627 // unsigned long long int [...]
3628 // FIXME: Is there some better way to compute this?
3629 if (BT->getKind() == BuiltinType::WChar_S ||
3630 BT->getKind() == BuiltinType::WChar_U ||
3631 BT->getKind() == BuiltinType::Char16 ||
3632 BT->getKind() == BuiltinType::Char32) {
3633 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3634 uint64_t FromSize = getTypeSize(BT);
3635 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3636 LongLongTy, UnsignedLongLongTy };
3637 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3638 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3639 if (FromSize < ToSize ||
3640 (FromSize == ToSize &&
3641 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3642 return PromoteTypes[Idx];
3643 }
3644 llvm_unreachable("char type should fit into long long");
3645 }
3646 }
3647
3648 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003649 if (Promotable->isSignedIntegerType())
3650 return IntTy;
3651 uint64_t PromotableSize = getTypeSize(Promotable);
3652 uint64_t IntSize = getTypeSize(IntTy);
3653 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3654 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3655}
3656
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003657/// \brief Recurses in pointer/array types until it finds an objc retainable
3658/// type and returns its ownership.
3659Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3660 while (!T.isNull()) {
3661 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3662 return T.getObjCLifetime();
3663 if (T->isArrayType())
3664 T = getBaseElementType(T);
3665 else if (const PointerType *PT = T->getAs<PointerType>())
3666 T = PT->getPointeeType();
3667 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003668 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003669 else
3670 break;
3671 }
3672
3673 return Qualifiers::OCL_None;
3674}
3675
Mike Stump11289f42009-09-09 15:08:12 +00003676/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003677/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003678/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003679int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003680 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3681 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003682 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003683
Chris Lattner76a00cf2008-04-06 22:59:24 +00003684 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3685 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003686
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003687 unsigned LHSRank = getIntegerRank(LHSC);
3688 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003689
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003690 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3691 if (LHSRank == RHSRank) return 0;
3692 return LHSRank > RHSRank ? 1 : -1;
3693 }
Mike Stump11289f42009-09-09 15:08:12 +00003694
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003695 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3696 if (LHSUnsigned) {
3697 // If the unsigned [LHS] type is larger, return it.
3698 if (LHSRank >= RHSRank)
3699 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003700
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003701 // If the signed type can represent all values of the unsigned type, it
3702 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003703 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003704 return -1;
3705 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003706
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003707 // If the unsigned [RHS] type is larger, return it.
3708 if (RHSRank >= LHSRank)
3709 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003710
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003711 // If the signed type can represent all values of the unsigned type, it
3712 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003713 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003714 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003715}
Anders Carlsson98f07902007-08-17 05:31:46 +00003716
Anders Carlsson6d417272009-11-14 21:45:58 +00003717static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003718CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3719 DeclContext *DC, IdentifierInfo *Id) {
3720 SourceLocation Loc;
Anders Carlsson6d417272009-11-14 21:45:58 +00003721 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003722 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003723 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003724 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003725}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003726
Mike Stump11289f42009-09-09 15:08:12 +00003727// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003728QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003729 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003730 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003731 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003732 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003733 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003734
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003735 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003736
Anders Carlsson98f07902007-08-17 05:31:46 +00003737 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003738 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003739 // int flags;
3740 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003741 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003742 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003743 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003744 FieldTypes[3] = LongTy;
3745
Anders Carlsson98f07902007-08-17 05:31:46 +00003746 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003747 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003748 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003749 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003750 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003751 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003752 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003753 /*Mutable=*/false,
3754 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003755 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003756 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003757 }
3758
Douglas Gregord5058122010-02-11 01:19:42 +00003759 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003760 }
Mike Stump11289f42009-09-09 15:08:12 +00003761
Anders Carlsson98f07902007-08-17 05:31:46 +00003762 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003763}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003764
Douglas Gregor512b0772009-04-23 22:29:11 +00003765void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003766 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003767 assert(Rec && "Invalid CFConstantStringType");
3768 CFConstantStringTypeDecl = Rec->getDecl();
3769}
3770
Jay Foad39c79802011-01-12 09:06:06 +00003771QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003772 if (BlockDescriptorType)
3773 return getTagDeclType(BlockDescriptorType);
3774
3775 RecordDecl *T;
3776 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003777 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003778 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003779 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003780
3781 QualType FieldTypes[] = {
3782 UnsignedLongTy,
3783 UnsignedLongTy,
3784 };
3785
3786 const char *FieldNames[] = {
3787 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003788 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003789 };
3790
3791 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003792 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003793 SourceLocation(),
3794 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003795 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003796 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003797 /*Mutable=*/false,
3798 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003799 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003800 T->addDecl(Field);
3801 }
3802
Douglas Gregord5058122010-02-11 01:19:42 +00003803 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003804
3805 BlockDescriptorType = T;
3806
3807 return getTagDeclType(BlockDescriptorType);
3808}
3809
Jay Foad39c79802011-01-12 09:06:06 +00003810QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003811 if (BlockDescriptorExtendedType)
3812 return getTagDeclType(BlockDescriptorExtendedType);
3813
3814 RecordDecl *T;
3815 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003816 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003817 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003818 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003819
3820 QualType FieldTypes[] = {
3821 UnsignedLongTy,
3822 UnsignedLongTy,
3823 getPointerType(VoidPtrTy),
3824 getPointerType(VoidPtrTy)
3825 };
3826
3827 const char *FieldNames[] = {
3828 "reserved",
3829 "Size",
3830 "CopyFuncPtr",
3831 "DestroyFuncPtr"
3832 };
3833
3834 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003835 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003836 SourceLocation(),
3837 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003838 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003839 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003840 /*Mutable=*/false,
3841 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003842 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003843 T->addDecl(Field);
3844 }
3845
Douglas Gregord5058122010-02-11 01:19:42 +00003846 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003847
3848 BlockDescriptorExtendedType = T;
3849
3850 return getTagDeclType(BlockDescriptorExtendedType);
3851}
3852
Jay Foad39c79802011-01-12 09:06:06 +00003853bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00003854 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00003855 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003856 if (getLangOptions().CPlusPlus) {
3857 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3858 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00003859 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003860
3861 }
3862 }
Mike Stump94967902009-10-21 18:16:27 +00003863 return false;
3864}
3865
Jay Foad39c79802011-01-12 09:06:06 +00003866QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003867ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003868 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003869 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003870 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003871 // unsigned int __flags;
3872 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003873 // void *__copy_helper; // as needed
3874 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003875 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003876 // } *
3877
Mike Stump94967902009-10-21 18:16:27 +00003878 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3879
3880 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003881 llvm::SmallString<36> Name;
3882 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3883 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003884 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003885 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003886 T->startDefinition();
3887 QualType Int32Ty = IntTy;
3888 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3889 QualType FieldTypes[] = {
3890 getPointerType(VoidPtrTy),
3891 getPointerType(getTagDeclType(T)),
3892 Int32Ty,
3893 Int32Ty,
3894 getPointerType(VoidPtrTy),
3895 getPointerType(VoidPtrTy),
3896 Ty
3897 };
3898
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003899 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003900 "__isa",
3901 "__forwarding",
3902 "__flags",
3903 "__size",
3904 "__copy_helper",
3905 "__destroy_helper",
3906 DeclName,
3907 };
3908
3909 for (size_t i = 0; i < 7; ++i) {
3910 if (!HasCopyAndDispose && i >=4 && i <= 5)
3911 continue;
3912 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003913 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00003914 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003915 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003916 /*BitWidth=*/0, /*Mutable=*/false,
3917 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003918 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003919 T->addDecl(Field);
3920 }
3921
Douglas Gregord5058122010-02-11 01:19:42 +00003922 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003923
3924 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003925}
3926
Douglas Gregorbab8a962011-09-08 01:46:34 +00003927TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
3928 if (!ObjCInstanceTypeDecl)
3929 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
3930 getTranslationUnitDecl(),
3931 SourceLocation(),
3932 SourceLocation(),
3933 &Idents.get("instancetype"),
3934 getTrivialTypeSourceInfo(getObjCIdType()));
3935 return ObjCInstanceTypeDecl;
3936}
3937
Anders Carlsson18acd442007-10-29 06:33:42 +00003938// This returns true if a type has been typedefed to BOOL:
3939// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003940static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003941 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003942 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3943 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003944
Anders Carlssond8499822007-10-29 05:01:08 +00003945 return false;
3946}
3947
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003948/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003949/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00003950CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00003951 if (!type->isIncompleteArrayType() && type->isIncompleteType())
3952 return CharUnits::Zero();
3953
Ken Dyck40775002010-01-11 17:06:35 +00003954 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003955
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003956 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003957 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003958 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003959 // Treat arrays as pointers, since that's how they're passed in.
3960 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003961 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003962 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003963}
3964
3965static inline
3966std::string charUnitsToString(const CharUnits &CU) {
3967 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003968}
3969
John McCall351762c2011-02-07 10:33:21 +00003970/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003971/// declaration.
John McCall351762c2011-02-07 10:33:21 +00003972std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3973 std::string S;
3974
David Chisnall950a9512009-11-17 19:33:30 +00003975 const BlockDecl *Decl = Expr->getBlockDecl();
3976 QualType BlockTy =
3977 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3978 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003979 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003980 // Compute size of all parameters.
3981 // Start with computing size of a pointer in number of bytes.
3982 // FIXME: There might(should) be a better way of doing this computation!
3983 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003984 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3985 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003986 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003987 E = Decl->param_end(); PI != E; ++PI) {
3988 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003989 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003990 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003991 ParmOffset += sz;
3992 }
3993 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003994 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003995 // Block pointer and offset.
3996 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00003997
3998 // Argument types.
3999 ParmOffset = PtrSize;
4000 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4001 Decl->param_end(); PI != E; ++PI) {
4002 ParmVarDecl *PVDecl = *PI;
4003 QualType PType = PVDecl->getOriginalType();
4004 if (const ArrayType *AT =
4005 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4006 // Use array's original type only if it has known number of
4007 // elements.
4008 if (!isa<ConstantArrayType>(AT))
4009 PType = PVDecl->getType();
4010 } else if (PType->isFunctionType())
4011 PType = PVDecl->getType();
4012 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004013 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004014 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004015 }
John McCall351762c2011-02-07 10:33:21 +00004016
4017 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004018}
4019
Douglas Gregora9d84932011-05-27 01:19:52 +00004020bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004021 std::string& S) {
4022 // Encode result type.
4023 getObjCEncodingForType(Decl->getResultType(), S);
4024 CharUnits ParmOffset;
4025 // Compute size of all parameters.
4026 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4027 E = Decl->param_end(); PI != E; ++PI) {
4028 QualType PType = (*PI)->getType();
4029 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004030 if (sz.isZero())
4031 return true;
4032
David Chisnall50e4eba2010-12-30 14:05:53 +00004033 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004034 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004035 ParmOffset += sz;
4036 }
4037 S += charUnitsToString(ParmOffset);
4038 ParmOffset = CharUnits::Zero();
4039
4040 // Argument types.
4041 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4042 E = Decl->param_end(); PI != E; ++PI) {
4043 ParmVarDecl *PVDecl = *PI;
4044 QualType PType = PVDecl->getOriginalType();
4045 if (const ArrayType *AT =
4046 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4047 // Use array's original type only if it has known number of
4048 // elements.
4049 if (!isa<ConstantArrayType>(AT))
4050 PType = PVDecl->getType();
4051 } else if (PType->isFunctionType())
4052 PType = PVDecl->getType();
4053 getObjCEncodingForType(PType, S);
4054 S += charUnitsToString(ParmOffset);
4055 ParmOffset += getObjCEncodingTypeSize(PType);
4056 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004057
4058 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004059}
4060
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004061/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004062/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004063bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00004064 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004065 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004066 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004067 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004068 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004069 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004070 // Compute size of all parameters.
4071 // Start with computing size of a pointer in number of bytes.
4072 // FIXME: There might(should) be a better way of doing this computation!
4073 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004074 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004075 // The first two arguments (self and _cmd) are pointers; account for
4076 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004077 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004078 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004079 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004080 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004081 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004082 if (sz.isZero())
4083 return true;
4084
Ken Dyck40775002010-01-11 17:06:35 +00004085 assert (sz.isPositive() &&
4086 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004087 ParmOffset += sz;
4088 }
Ken Dyck40775002010-01-11 17:06:35 +00004089 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004090 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004091 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004092
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004093 // Argument types.
4094 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004095 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004096 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004097 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004098 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004099 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004100 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4101 // Use array's original type only if it has known number of
4102 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004103 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004104 PType = PVDecl->getType();
4105 } else if (PType->isFunctionType())
4106 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004107 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004108 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004109 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004110 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004111 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004112 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004113 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004114
4115 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004116}
4117
Daniel Dunbar4932b362008-08-28 04:38:10 +00004118/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004119/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004120/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4121/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004122/// Property attributes are stored as a comma-delimited C string. The simple
4123/// attributes readonly and bycopy are encoded as single characters. The
4124/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4125/// encoded as single characters, followed by an identifier. Property types
4126/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004127/// these attributes are defined by the following enumeration:
4128/// @code
4129/// enum PropertyAttributes {
4130/// kPropertyReadOnly = 'R', // property is read-only.
4131/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4132/// kPropertyByref = '&', // property is a reference to the value last assigned
4133/// kPropertyDynamic = 'D', // property is dynamic
4134/// kPropertyGetter = 'G', // followed by getter selector name
4135/// kPropertySetter = 'S', // followed by setter selector name
4136/// kPropertyInstanceVariable = 'V' // followed by instance variable name
4137/// kPropertyType = 't' // followed by old-style type encoding.
4138/// kPropertyWeak = 'W' // 'weak' property
4139/// kPropertyStrong = 'P' // property GC'able
4140/// kPropertyNonAtomic = 'N' // property non-atomic
4141/// };
4142/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004143void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004144 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004145 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004146 // Collect information from the property implementation decl(s).
4147 bool Dynamic = false;
4148 ObjCPropertyImplDecl *SynthesizePID = 0;
4149
4150 // FIXME: Duplicated code due to poor abstraction.
4151 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004152 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004153 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4154 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004155 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004156 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004157 ObjCPropertyImplDecl *PID = *i;
4158 if (PID->getPropertyDecl() == PD) {
4159 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4160 Dynamic = true;
4161 } else {
4162 SynthesizePID = PID;
4163 }
4164 }
4165 }
4166 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004167 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004168 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004169 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004170 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004171 ObjCPropertyImplDecl *PID = *i;
4172 if (PID->getPropertyDecl() == PD) {
4173 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4174 Dynamic = true;
4175 } else {
4176 SynthesizePID = PID;
4177 }
4178 }
Mike Stump11289f42009-09-09 15:08:12 +00004179 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004180 }
4181 }
4182
4183 // FIXME: This is not very efficient.
4184 S = "T";
4185
4186 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004187 // GCC has some special rules regarding encoding of properties which
4188 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004189 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004190 true /* outermost type */,
4191 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004192
4193 if (PD->isReadOnly()) {
4194 S += ",R";
4195 } else {
4196 switch (PD->getSetterKind()) {
4197 case ObjCPropertyDecl::Assign: break;
4198 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004199 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004200 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004201 }
4202 }
4203
4204 // It really isn't clear at all what this means, since properties
4205 // are "dynamic by default".
4206 if (Dynamic)
4207 S += ",D";
4208
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004209 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4210 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004211
Daniel Dunbar4932b362008-08-28 04:38:10 +00004212 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4213 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004214 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004215 }
4216
4217 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4218 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004219 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004220 }
4221
4222 if (SynthesizePID) {
4223 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4224 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004225 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004226 }
4227
4228 // FIXME: OBJCGC: weak & strong
4229}
4230
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004231/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004232/// Another legacy compatibility encoding: 32-bit longs are encoded as
4233/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004234/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4235///
4236void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004237 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004238 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004239 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004240 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004241 else
Jay Foad39c79802011-01-12 09:06:06 +00004242 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004243 PointeeTy = IntTy;
4244 }
4245 }
4246}
4247
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004248void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004249 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004250 // We follow the behavior of gcc, expanding structures which are
4251 // directly pointed to, and expanding embedded structures. Note that
4252 // these rules are sufficient to prevent recursive encoding of the
4253 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004254 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004255 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004256}
4257
David Chisnallb190a2c2010-06-04 01:10:52 +00004258static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4259 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004260 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004261 case BuiltinType::Void: return 'v';
4262 case BuiltinType::Bool: return 'B';
4263 case BuiltinType::Char_U:
4264 case BuiltinType::UChar: return 'C';
4265 case BuiltinType::UShort: return 'S';
4266 case BuiltinType::UInt: return 'I';
4267 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004268 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004269 case BuiltinType::UInt128: return 'T';
4270 case BuiltinType::ULongLong: return 'Q';
4271 case BuiltinType::Char_S:
4272 case BuiltinType::SChar: return 'c';
4273 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004274 case BuiltinType::WChar_S:
4275 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004276 case BuiltinType::Int: return 'i';
4277 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004278 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004279 case BuiltinType::LongLong: return 'q';
4280 case BuiltinType::Int128: return 't';
4281 case BuiltinType::Float: return 'f';
4282 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004283 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004284 }
4285}
4286
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004287static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4288 EnumDecl *Enum = ET->getDecl();
4289
4290 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4291 if (!Enum->isFixed())
4292 return 'i';
4293
4294 // The encoding of a fixed enum type matches its fixed underlying type.
4295 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4296}
4297
Jay Foad39c79802011-01-12 09:06:06 +00004298static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004299 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004300 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004301 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004302 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4303 // The GNU runtime requires more information; bitfields are encoded as b,
4304 // then the offset (in bits) of the first element, then the type of the
4305 // bitfield, then the size in bits. For example, in this structure:
4306 //
4307 // struct
4308 // {
4309 // int integer;
4310 // int flags:2;
4311 // };
4312 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4313 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4314 // information is not especially sensible, but we're stuck with it for
4315 // compatibility with GCC, although providing it breaks anything that
4316 // actually uses runtime introspection and wants to work on both runtimes...
4317 if (!Ctx->getLangOptions().NeXTRuntime) {
4318 const RecordDecl *RD = FD->getParent();
4319 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004320 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004321 if (const EnumType *ET = T->getAs<EnumType>())
4322 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004323 else
Jay Foad39c79802011-01-12 09:06:06 +00004324 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004325 }
Richard Smithcaf33902011-10-10 18:28:20 +00004326 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004327}
4328
Daniel Dunbar07d07852009-10-18 21:17:35 +00004329// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004330void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4331 bool ExpandPointedToStructures,
4332 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004333 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004334 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004335 bool EncodingProperty,
4336 bool StructField) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004337 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004338 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004339 return EncodeBitField(this, S, T, FD);
4340 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004341 return;
4342 }
Mike Stump11289f42009-09-09 15:08:12 +00004343
John McCall9dd450b2009-09-21 23:43:11 +00004344 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004345 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004346 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004347 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004348 return;
4349 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004350
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004351 // encoding for pointer or r3eference types.
4352 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004353 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004354 if (PT->isObjCSelType()) {
4355 S += ':';
4356 return;
4357 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004358 PointeeTy = PT->getPointeeType();
4359 }
4360 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4361 PointeeTy = RT->getPointeeType();
4362 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004363 bool isReadOnly = false;
4364 // For historical/compatibility reasons, the read-only qualifier of the
4365 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4366 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004367 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004368 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004369 if (OutermostType && T.isConstQualified()) {
4370 isReadOnly = true;
4371 S += 'r';
4372 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004373 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004374 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004375 while (P->getAs<PointerType>())
4376 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004377 if (P.isConstQualified()) {
4378 isReadOnly = true;
4379 S += 'r';
4380 }
4381 }
4382 if (isReadOnly) {
4383 // Another legacy compatibility encoding. Some ObjC qualifier and type
4384 // combinations need to be rearranged.
4385 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004386 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004387 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004388 }
Mike Stump11289f42009-09-09 15:08:12 +00004389
Anders Carlssond8499822007-10-29 05:01:08 +00004390 if (PointeeTy->isCharType()) {
4391 // char pointer types should be encoded as '*' unless it is a
4392 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004393 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004394 S += '*';
4395 return;
4396 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004397 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004398 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4399 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4400 S += '#';
4401 return;
4402 }
4403 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4404 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4405 S += '@';
4406 return;
4407 }
4408 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004409 }
Anders Carlssond8499822007-10-29 05:01:08 +00004410 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004411 getLegacyIntegralTypeEncoding(PointeeTy);
4412
Mike Stump11289f42009-09-09 15:08:12 +00004413 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004414 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004415 return;
4416 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004417
Chris Lattnere7cabb92009-07-13 00:10:46 +00004418 if (const ArrayType *AT =
4419 // Ignore type qualifiers etc.
4420 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004421 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004422 // Incomplete arrays are encoded as a pointer to the array element.
4423 S += '^';
4424
Mike Stump11289f42009-09-09 15:08:12 +00004425 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004426 false, ExpandStructures, FD);
4427 } else {
4428 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004429
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004430 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4431 if (getTypeSize(CAT->getElementType()) == 0)
4432 S += '0';
4433 else
4434 S += llvm::utostr(CAT->getSize().getZExtValue());
4435 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004436 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004437 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4438 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004439 S += '0';
4440 }
Mike Stump11289f42009-09-09 15:08:12 +00004441
4442 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004443 false, ExpandStructures, FD);
4444 S += ']';
4445 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004446 return;
4447 }
Mike Stump11289f42009-09-09 15:08:12 +00004448
John McCall9dd450b2009-09-21 23:43:11 +00004449 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004450 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004451 return;
4452 }
Mike Stump11289f42009-09-09 15:08:12 +00004453
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004454 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004455 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004456 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004457 // Anonymous structures print as '?'
4458 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4459 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004460 if (ClassTemplateSpecializationDecl *Spec
4461 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4462 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4463 std::string TemplateArgsStr
4464 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004465 TemplateArgs.data(),
4466 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004467 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004468
4469 S += TemplateArgsStr;
4470 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004471 } else {
4472 S += '?';
4473 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004474 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004475 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004476 if (!RDecl->isUnion()) {
4477 getObjCEncodingForStructureImpl(RDecl, S, FD);
4478 } else {
4479 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4480 FieldEnd = RDecl->field_end();
4481 Field != FieldEnd; ++Field) {
4482 if (FD) {
4483 S += '"';
4484 S += Field->getNameAsString();
4485 S += '"';
4486 }
Mike Stump11289f42009-09-09 15:08:12 +00004487
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004488 // Special case bit-fields.
4489 if (Field->isBitField()) {
4490 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4491 (*Field));
4492 } else {
4493 QualType qt = Field->getType();
4494 getLegacyIntegralTypeEncoding(qt);
4495 getObjCEncodingForTypeImpl(qt, S, false, true,
4496 FD, /*OutermostType*/false,
4497 /*EncodingProperty*/false,
4498 /*StructField*/true);
4499 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004500 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004501 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004502 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004503 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004504 return;
4505 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004506
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004507 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004508 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004509 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004510 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004511 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004512 return;
4513 }
Mike Stump11289f42009-09-09 15:08:12 +00004514
Chris Lattnere7cabb92009-07-13 00:10:46 +00004515 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004516 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00004517 return;
4518 }
Mike Stump11289f42009-09-09 15:08:12 +00004519
John McCall8b07ec22010-05-15 11:32:37 +00004520 // Ignore protocol qualifiers when mangling at this level.
4521 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4522 T = OT->getBaseType();
4523
John McCall8ccfcb52009-09-24 19:53:00 +00004524 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004525 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004526 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004527 S += '{';
4528 const IdentifierInfo *II = OI->getIdentifier();
4529 S += II->getName();
4530 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004531 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004532 DeepCollectObjCIvars(OI, true, Ivars);
4533 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004534 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004535 if (Field->isBitField())
4536 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004537 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004538 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004539 }
4540 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004541 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004542 }
Mike Stump11289f42009-09-09 15:08:12 +00004543
John McCall9dd450b2009-09-21 23:43:11 +00004544 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004545 if (OPT->isObjCIdType()) {
4546 S += '@';
4547 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004548 }
Mike Stump11289f42009-09-09 15:08:12 +00004549
Steve Narofff0c86112009-10-28 22:03:49 +00004550 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4551 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4552 // Since this is a binary compatibility issue, need to consult with runtime
4553 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004554 S += '#';
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 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004559 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004560 ExpandPointedToStructures,
4561 ExpandStructures, FD);
4562 if (FD || EncodingProperty) {
4563 // Note that we do extended encoding of protocol qualifer list
4564 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004565 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004566 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4567 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004568 S += '<';
4569 S += (*I)->getNameAsString();
4570 S += '>';
4571 }
4572 S += '"';
4573 }
4574 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004575 }
Mike Stump11289f42009-09-09 15:08:12 +00004576
Chris Lattnere7cabb92009-07-13 00:10:46 +00004577 QualType PointeeTy = OPT->getPointeeType();
4578 if (!EncodingProperty &&
4579 isa<TypedefType>(PointeeTy.getTypePtr())) {
4580 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004581 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004582 // {...};
4583 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004584 getObjCEncodingForTypeImpl(PointeeTy, S,
4585 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004586 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004587 return;
4588 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004589
4590 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00004591 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004592 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004593 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004594 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4595 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004596 S += '<';
4597 S += (*I)->getNameAsString();
4598 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004599 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004600 S += '"';
4601 }
4602 return;
4603 }
Mike Stump11289f42009-09-09 15:08:12 +00004604
John McCalla9e6e8d2010-05-17 23:56:34 +00004605 // gcc just blithely ignores member pointers.
4606 // TODO: maybe there should be a mangling for these
4607 if (T->getAs<MemberPointerType>())
4608 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004609
4610 if (T->isVectorType()) {
4611 // This matches gcc's encoding, even though technically it is
4612 // insufficient.
4613 // FIXME. We should do a better job than gcc.
4614 return;
4615 }
4616
David Blaikie83d382b2011-09-23 05:06:16 +00004617 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004618}
4619
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004620void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4621 std::string &S,
4622 const FieldDecl *FD,
4623 bool includeVBases) const {
4624 assert(RDecl && "Expected non-null RecordDecl");
4625 assert(!RDecl->isUnion() && "Should not be called for unions");
4626 if (!RDecl->getDefinition())
4627 return;
4628
4629 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4630 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4631 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4632
4633 if (CXXRec) {
4634 for (CXXRecordDecl::base_class_iterator
4635 BI = CXXRec->bases_begin(),
4636 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4637 if (!BI->isVirtual()) {
4638 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004639 if (base->isEmpty())
4640 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004641 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4642 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4643 std::make_pair(offs, base));
4644 }
4645 }
4646 }
4647
4648 unsigned i = 0;
4649 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4650 FieldEnd = RDecl->field_end();
4651 Field != FieldEnd; ++Field, ++i) {
4652 uint64_t offs = layout.getFieldOffset(i);
4653 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4654 std::make_pair(offs, *Field));
4655 }
4656
4657 if (CXXRec && includeVBases) {
4658 for (CXXRecordDecl::base_class_iterator
4659 BI = CXXRec->vbases_begin(),
4660 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4661 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004662 if (base->isEmpty())
4663 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004664 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00004665 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4666 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4667 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004668 }
4669 }
4670
4671 CharUnits size;
4672 if (CXXRec) {
4673 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4674 } else {
4675 size = layout.getSize();
4676 }
4677
4678 uint64_t CurOffs = 0;
4679 std::multimap<uint64_t, NamedDecl *>::iterator
4680 CurLayObj = FieldOrBaseOffsets.begin();
4681
Argyrios Kyrtzidisc7e50c52011-08-22 16:03:14 +00004682 if ((CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) ||
4683 (CurLayObj == FieldOrBaseOffsets.end() &&
4684 CXXRec && CXXRec->isDynamicClass())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004685 assert(CXXRec && CXXRec->isDynamicClass() &&
4686 "Offset 0 was empty but no VTable ?");
4687 if (FD) {
4688 S += "\"_vptr$";
4689 std::string recname = CXXRec->getNameAsString();
4690 if (recname.empty()) recname = "?";
4691 S += recname;
4692 S += '"';
4693 }
4694 S += "^^?";
4695 CurOffs += getTypeSize(VoidPtrTy);
4696 }
4697
4698 if (!RDecl->hasFlexibleArrayMember()) {
4699 // Mark the end of the structure.
4700 uint64_t offs = toBits(size);
4701 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4702 std::make_pair(offs, (NamedDecl*)0));
4703 }
4704
4705 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4706 assert(CurOffs <= CurLayObj->first);
4707
4708 if (CurOffs < CurLayObj->first) {
4709 uint64_t padding = CurLayObj->first - CurOffs;
4710 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4711 // packing/alignment of members is different that normal, in which case
4712 // the encoding will be out-of-sync with the real layout.
4713 // If the runtime switches to just consider the size of types without
4714 // taking into account alignment, we could make padding explicit in the
4715 // encoding (e.g. using arrays of chars). The encoding strings would be
4716 // longer then though.
4717 CurOffs += padding;
4718 }
4719
4720 NamedDecl *dcl = CurLayObj->second;
4721 if (dcl == 0)
4722 break; // reached end of structure.
4723
4724 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4725 // We expand the bases without their virtual bases since those are going
4726 // in the initial structure. Note that this differs from gcc which
4727 // expands virtual bases each time one is encountered in the hierarchy,
4728 // making the encoding type bigger than it really is.
4729 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004730 assert(!base->isEmpty());
4731 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004732 } else {
4733 FieldDecl *field = cast<FieldDecl>(dcl);
4734 if (FD) {
4735 S += '"';
4736 S += field->getNameAsString();
4737 S += '"';
4738 }
4739
4740 if (field->isBitField()) {
4741 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00004742 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004743 } else {
4744 QualType qt = field->getType();
4745 getLegacyIntegralTypeEncoding(qt);
4746 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4747 /*OutermostType*/false,
4748 /*EncodingProperty*/false,
4749 /*StructField*/true);
4750 CurOffs += getTypeSize(field->getType());
4751 }
4752 }
4753 }
4754}
4755
Mike Stump11289f42009-09-09 15:08:12 +00004756void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004757 std::string& S) const {
4758 if (QT & Decl::OBJC_TQ_In)
4759 S += 'n';
4760 if (QT & Decl::OBJC_TQ_Inout)
4761 S += 'N';
4762 if (QT & Decl::OBJC_TQ_Out)
4763 S += 'o';
4764 if (QT & Decl::OBJC_TQ_Bycopy)
4765 S += 'O';
4766 if (QT & Decl::OBJC_TQ_Byref)
4767 S += 'R';
4768 if (QT & Decl::OBJC_TQ_Oneway)
4769 S += 'V';
4770}
4771
Chris Lattnere7cabb92009-07-13 00:10:46 +00004772void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004773 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004774
Anders Carlsson87c149b2007-10-11 01:00:40 +00004775 BuiltinVaListType = T;
4776}
4777
Douglas Gregor3ea72692011-08-12 05:46:01 +00004778TypedefDecl *ASTContext::getObjCIdDecl() const {
4779 if (!ObjCIdDecl) {
4780 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4781 T = getObjCObjectPointerType(T);
4782 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4783 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4784 getTranslationUnitDecl(),
4785 SourceLocation(), SourceLocation(),
4786 &Idents.get("id"), IdInfo);
4787 }
4788
4789 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00004790}
4791
Douglas Gregor52e02802011-08-12 06:17:30 +00004792TypedefDecl *ASTContext::getObjCSelDecl() const {
4793 if (!ObjCSelDecl) {
4794 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4795 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4796 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4797 getTranslationUnitDecl(),
4798 SourceLocation(), SourceLocation(),
4799 &Idents.get("SEL"), SelInfo);
4800 }
4801 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004802}
4803
Chris Lattnere7cabb92009-07-13 00:10:46 +00004804void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004805 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004806}
4807
Douglas Gregor0a586182011-08-12 05:59:41 +00004808TypedefDecl *ASTContext::getObjCClassDecl() const {
4809 if (!ObjCClassDecl) {
4810 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4811 T = getObjCObjectPointerType(T);
4812 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4813 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4814 getTranslationUnitDecl(),
4815 SourceLocation(), SourceLocation(),
4816 &Idents.get("Class"), ClassInfo);
4817 }
4818
4819 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004820}
4821
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004822void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004823 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004824 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004825
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004826 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004827}
4828
John McCalld28ae272009-12-02 08:04:21 +00004829/// \brief Retrieve the template name that corresponds to a non-empty
4830/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004831TemplateName
4832ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4833 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004834 unsigned size = End - Begin;
4835 assert(size > 1 && "set is not overloaded!");
4836
4837 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4838 size * sizeof(FunctionTemplateDecl*));
4839 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4840
4841 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004842 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004843 NamedDecl *D = *I;
4844 assert(isa<FunctionTemplateDecl>(D) ||
4845 (isa<UsingShadowDecl>(D) &&
4846 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4847 *Storage++ = D;
4848 }
4849
4850 return TemplateName(OT);
4851}
4852
Douglas Gregordc572a32009-03-30 22:58:21 +00004853/// \brief Retrieve the template name that represents a qualified
4854/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004855TemplateName
4856ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4857 bool TemplateKeyword,
4858 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00004859 assert(NNS && "Missing nested-name-specifier in qualified template name");
4860
Douglas Gregorc42075a2010-02-04 18:10:26 +00004861 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004862 llvm::FoldingSetNodeID ID;
4863 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4864
4865 void *InsertPos = 0;
4866 QualifiedTemplateName *QTN =
4867 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4868 if (!QTN) {
4869 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4870 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4871 }
4872
4873 return TemplateName(QTN);
4874}
4875
4876/// \brief Retrieve the template name that represents a dependent
4877/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004878TemplateName
4879ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4880 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004881 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004882 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004883
4884 llvm::FoldingSetNodeID ID;
4885 DependentTemplateName::Profile(ID, NNS, Name);
4886
4887 void *InsertPos = 0;
4888 DependentTemplateName *QTN =
4889 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4890
4891 if (QTN)
4892 return TemplateName(QTN);
4893
4894 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4895 if (CanonNNS == NNS) {
4896 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4897 } else {
4898 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4899 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004900 DependentTemplateName *CheckQTN =
4901 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4902 assert(!CheckQTN && "Dependent type name canonicalization broken");
4903 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004904 }
4905
4906 DependentTemplateNames.InsertNode(QTN, InsertPos);
4907 return TemplateName(QTN);
4908}
4909
Douglas Gregor71395fa2009-11-04 00:56:37 +00004910/// \brief Retrieve the template name that represents a dependent
4911/// template name such as \c MetaFun::template operator+.
4912TemplateName
4913ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00004914 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00004915 assert((!NNS || NNS->isDependent()) &&
4916 "Nested name specifier must be dependent");
4917
4918 llvm::FoldingSetNodeID ID;
4919 DependentTemplateName::Profile(ID, NNS, Operator);
4920
4921 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004922 DependentTemplateName *QTN
4923 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004924
4925 if (QTN)
4926 return TemplateName(QTN);
4927
4928 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4929 if (CanonNNS == NNS) {
4930 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4931 } else {
4932 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4933 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004934
4935 DependentTemplateName *CheckQTN
4936 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4937 assert(!CheckQTN && "Dependent template name canonicalization broken");
4938 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004939 }
4940
4941 DependentTemplateNames.InsertNode(QTN, InsertPos);
4942 return TemplateName(QTN);
4943}
4944
Douglas Gregor5590be02011-01-15 06:45:20 +00004945TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00004946ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
4947 TemplateName replacement) const {
4948 llvm::FoldingSetNodeID ID;
4949 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
4950
4951 void *insertPos = 0;
4952 SubstTemplateTemplateParmStorage *subst
4953 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
4954
4955 if (!subst) {
4956 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
4957 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
4958 }
4959
4960 return TemplateName(subst);
4961}
4962
4963TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00004964ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4965 const TemplateArgument &ArgPack) const {
4966 ASTContext &Self = const_cast<ASTContext &>(*this);
4967 llvm::FoldingSetNodeID ID;
4968 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4969
4970 void *InsertPos = 0;
4971 SubstTemplateTemplateParmPackStorage *Subst
4972 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4973
4974 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00004975 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00004976 ArgPack.pack_size(),
4977 ArgPack.pack_begin());
4978 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4979 }
4980
4981 return TemplateName(Subst);
4982}
4983
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004984/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004985/// TargetInfo, produce the corresponding type. The unsigned @p Type
4986/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004987CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004988 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004989 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004990 case TargetInfo::SignedShort: return ShortTy;
4991 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4992 case TargetInfo::SignedInt: return IntTy;
4993 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4994 case TargetInfo::SignedLong: return LongTy;
4995 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4996 case TargetInfo::SignedLongLong: return LongLongTy;
4997 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4998 }
4999
David Blaikie83d382b2011-09-23 05:06:16 +00005000 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005001}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005002
5003//===----------------------------------------------------------------------===//
5004// Type Predicates.
5005//===----------------------------------------------------------------------===//
5006
Fariborz Jahanian96207692009-02-18 21:49:28 +00005007/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5008/// garbage collection attribute.
5009///
John McCall553d45a2011-01-12 00:34:59 +00005010Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
Douglas Gregor79a91412011-09-13 17:21:33 +00005011 if (getLangOptions().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005012 return Qualifiers::GCNone;
5013
5014 assert(getLangOptions().ObjC1);
5015 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5016
5017 // Default behaviour under objective-C's gc is for ObjC pointers
5018 // (or pointers to them) be treated as though they were declared
5019 // as __strong.
5020 if (GCAttrs == Qualifiers::GCNone) {
5021 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5022 return Qualifiers::Strong;
5023 else if (Ty->isPointerType())
5024 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5025 } else {
5026 // It's not valid to set GC attributes on anything that isn't a
5027 // pointer.
5028#ifndef NDEBUG
5029 QualType CT = Ty->getCanonicalTypeInternal();
5030 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5031 CT = AT->getElementType();
5032 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5033#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005034 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005035 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005036}
5037
Chris Lattner49af6a42008-04-07 06:51:04 +00005038//===----------------------------------------------------------------------===//
5039// Type Compatibility Testing
5040//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005041
Mike Stump11289f42009-09-09 15:08:12 +00005042/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005043/// compatible.
5044static bool areCompatVectorTypes(const VectorType *LHS,
5045 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005046 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005047 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005048 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005049}
5050
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005051bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5052 QualType SecondVec) {
5053 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5054 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5055
5056 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5057 return true;
5058
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005059 // Treat Neon vector types and most AltiVec vector types as if they are the
5060 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005061 const VectorType *First = FirstVec->getAs<VectorType>();
5062 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005063 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005064 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005065 First->getVectorKind() != VectorType::AltiVecPixel &&
5066 First->getVectorKind() != VectorType::AltiVecBool &&
5067 Second->getVectorKind() != VectorType::AltiVecPixel &&
5068 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005069 return true;
5070
5071 return false;
5072}
5073
Steve Naroff8e6aee52009-07-23 01:01:38 +00005074//===----------------------------------------------------------------------===//
5075// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5076//===----------------------------------------------------------------------===//
5077
5078/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5079/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005080bool
5081ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5082 ObjCProtocolDecl *rProto) const {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005083 if (lProto == rProto)
5084 return true;
5085 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5086 E = rProto->protocol_end(); PI != E; ++PI)
5087 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5088 return true;
5089 return false;
5090}
5091
Steve Naroff8e6aee52009-07-23 01:01:38 +00005092/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5093/// return true if lhs's protocols conform to rhs's protocol; false
5094/// otherwise.
5095bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5096 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5097 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5098 return false;
5099}
5100
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005101/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5102/// Class<p1, ...>.
5103bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5104 QualType rhs) {
5105 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5106 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5107 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5108
5109 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5110 E = lhsQID->qual_end(); I != E; ++I) {
5111 bool match = false;
5112 ObjCProtocolDecl *lhsProto = *I;
5113 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5114 E = rhsOPT->qual_end(); J != E; ++J) {
5115 ObjCProtocolDecl *rhsProto = *J;
5116 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5117 match = true;
5118 break;
5119 }
5120 }
5121 if (!match)
5122 return false;
5123 }
5124 return true;
5125}
5126
Steve Naroff8e6aee52009-07-23 01:01:38 +00005127/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5128/// ObjCQualifiedIDType.
5129bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5130 bool compare) {
5131 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005132 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005133 lhs->isObjCIdType() || lhs->isObjCClassType())
5134 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005135 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005136 rhs->isObjCIdType() || rhs->isObjCClassType())
5137 return true;
5138
5139 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005140 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005141
Steve Naroff8e6aee52009-07-23 01:01:38 +00005142 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005143
Steve Naroff8e6aee52009-07-23 01:01:38 +00005144 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005145 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005146 // make sure we check the class hierarchy.
5147 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5148 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5149 E = lhsQID->qual_end(); I != E; ++I) {
5150 // when comparing an id<P> on lhs with a static type on rhs,
5151 // see if static class implements all of id's protocols, directly or
5152 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005153 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005154 return false;
5155 }
5156 }
5157 // If there are no qualifiers and no interface, we have an 'id'.
5158 return true;
5159 }
Mike Stump11289f42009-09-09 15:08:12 +00005160 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005161 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5162 E = lhsQID->qual_end(); I != E; ++I) {
5163 ObjCProtocolDecl *lhsProto = *I;
5164 bool match = false;
5165
5166 // when comparing an id<P> on lhs with a static type on rhs,
5167 // see if static class implements all of id's protocols, directly or
5168 // through its super class and categories.
5169 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5170 E = rhsOPT->qual_end(); J != E; ++J) {
5171 ObjCProtocolDecl *rhsProto = *J;
5172 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5173 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5174 match = true;
5175 break;
5176 }
5177 }
Mike Stump11289f42009-09-09 15:08:12 +00005178 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005179 // make sure we check the class hierarchy.
5180 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5181 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5182 E = lhsQID->qual_end(); I != E; ++I) {
5183 // when comparing an id<P> on lhs with a static type on rhs,
5184 // see if static class implements all of id's protocols, directly or
5185 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005186 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005187 match = true;
5188 break;
5189 }
5190 }
5191 }
5192 if (!match)
5193 return false;
5194 }
Mike Stump11289f42009-09-09 15:08:12 +00005195
Steve Naroff8e6aee52009-07-23 01:01:38 +00005196 return true;
5197 }
Mike Stump11289f42009-09-09 15:08:12 +00005198
Steve Naroff8e6aee52009-07-23 01:01:38 +00005199 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5200 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5201
Mike Stump11289f42009-09-09 15:08:12 +00005202 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005203 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005204 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005205 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5206 E = lhsOPT->qual_end(); I != E; ++I) {
5207 ObjCProtocolDecl *lhsProto = *I;
5208 bool match = false;
5209
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005210 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005211 // see if static class implements all of id's protocols, directly or
5212 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005213 // First, lhs protocols in the qualifier list must be found, direct
5214 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005215 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5216 E = rhsQID->qual_end(); J != E; ++J) {
5217 ObjCProtocolDecl *rhsProto = *J;
5218 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5219 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5220 match = true;
5221 break;
5222 }
5223 }
5224 if (!match)
5225 return false;
5226 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005227
5228 // Static class's protocols, or its super class or category protocols
5229 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5230 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5231 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5232 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5233 // This is rather dubious but matches gcc's behavior. If lhs has
5234 // no type qualifier and its class has no static protocol(s)
5235 // assume that it is mismatch.
5236 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5237 return false;
5238 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5239 LHSInheritedProtocols.begin(),
5240 E = LHSInheritedProtocols.end(); I != E; ++I) {
5241 bool match = false;
5242 ObjCProtocolDecl *lhsProto = (*I);
5243 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5244 E = rhsQID->qual_end(); J != E; ++J) {
5245 ObjCProtocolDecl *rhsProto = *J;
5246 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5247 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5248 match = true;
5249 break;
5250 }
5251 }
5252 if (!match)
5253 return false;
5254 }
5255 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005256 return true;
5257 }
5258 return false;
5259}
5260
Eli Friedman47f77112008-08-22 00:56:42 +00005261/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005262/// compatible for assignment from RHS to LHS. This handles validation of any
5263/// protocol qualifiers on the LHS or RHS.
5264///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005265bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5266 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005267 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5268 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5269
Steve Naroff1329fa02009-07-15 18:40:39 +00005270 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005271 if (LHS->isObjCUnqualifiedIdOrClass() ||
5272 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005273 return true;
5274
John McCall8b07ec22010-05-15 11:32:37 +00005275 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005276 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5277 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005278 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005279
5280 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5281 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5282 QualType(RHSOPT,0));
5283
John McCall8b07ec22010-05-15 11:32:37 +00005284 // If we have 2 user-defined types, fall into that path.
5285 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005286 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005287
Steve Naroff8e6aee52009-07-23 01:01:38 +00005288 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005289}
5290
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005291/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005292/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005293/// arguments in block literals. When passed as arguments, passing 'A*' where
5294/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5295/// not OK. For the return type, the opposite is not OK.
5296bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5297 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005298 const ObjCObjectPointerType *RHSOPT,
5299 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005300 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005301 return true;
5302
5303 if (LHSOPT->isObjCBuiltinType()) {
5304 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5305 }
5306
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005307 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005308 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5309 QualType(RHSOPT,0),
5310 false);
5311
5312 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5313 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5314 if (LHS && RHS) { // We have 2 user-defined types.
5315 if (LHS != RHS) {
5316 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005317 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005318 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005319 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005320 }
5321 else
5322 return true;
5323 }
5324 return false;
5325}
5326
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005327/// getIntersectionOfProtocols - This routine finds the intersection of set
5328/// of protocols inherited from two distinct objective-c pointer objects.
5329/// It is used to build composite qualifier list of the composite type of
5330/// the conditional expression involving two objective-c pointer objects.
5331static
5332void getIntersectionOfProtocols(ASTContext &Context,
5333 const ObjCObjectPointerType *LHSOPT,
5334 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005335 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005336
John McCall8b07ec22010-05-15 11:32:37 +00005337 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5338 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5339 assert(LHS->getInterface() && "LHS must have an interface base");
5340 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005341
5342 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5343 unsigned LHSNumProtocols = LHS->getNumProtocols();
5344 if (LHSNumProtocols > 0)
5345 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5346 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005347 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005348 Context.CollectInheritedProtocols(LHS->getInterface(),
5349 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005350 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5351 LHSInheritedProtocols.end());
5352 }
5353
5354 unsigned RHSNumProtocols = RHS->getNumProtocols();
5355 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005356 ObjCProtocolDecl **RHSProtocols =
5357 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005358 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5359 if (InheritedProtocolSet.count(RHSProtocols[i]))
5360 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00005361 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005362 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005363 Context.CollectInheritedProtocols(RHS->getInterface(),
5364 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005365 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5366 RHSInheritedProtocols.begin(),
5367 E = RHSInheritedProtocols.end(); I != E; ++I)
5368 if (InheritedProtocolSet.count((*I)))
5369 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005370 }
5371}
5372
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005373/// areCommonBaseCompatible - Returns common base class of the two classes if
5374/// one found. Note that this is O'2 algorithm. But it will be called as the
5375/// last type comparison in a ?-exp of ObjC pointer types before a
5376/// warning is issued. So, its invokation is extremely rare.
5377QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005378 const ObjCObjectPointerType *Lptr,
5379 const ObjCObjectPointerType *Rptr) {
5380 const ObjCObjectType *LHS = Lptr->getObjectType();
5381 const ObjCObjectType *RHS = Rptr->getObjectType();
5382 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5383 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005384 if (!LDecl || !RDecl || (LDecl == RDecl))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005385 return QualType();
5386
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005387 do {
John McCall8b07ec22010-05-15 11:32:37 +00005388 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005389 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005390 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00005391 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5392
5393 QualType Result = QualType(LHS, 0);
5394 if (!Protocols.empty())
5395 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5396 Result = getObjCObjectPointerType(Result);
5397 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005398 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005399 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005400
5401 return QualType();
5402}
5403
John McCall8b07ec22010-05-15 11:32:37 +00005404bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5405 const ObjCObjectType *RHS) {
5406 assert(LHS->getInterface() && "LHS is not an interface type");
5407 assert(RHS->getInterface() && "RHS is not an interface type");
5408
Chris Lattner49af6a42008-04-07 06:51:04 +00005409 // Verify that the base decls are compatible: the RHS must be a subclass of
5410 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005411 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005412 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005413
Chris Lattner49af6a42008-04-07 06:51:04 +00005414 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5415 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005416 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005417 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005418
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005419 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5420 // more detailed analysis is required.
5421 if (RHS->getNumProtocols() == 0) {
5422 // OK, if LHS is a superclass of RHS *and*
5423 // this superclass is assignment compatible with LHS.
5424 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005425 bool IsSuperClass =
5426 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5427 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005428 // OK if conversion of LHS to SuperClass results in narrowing of types
5429 // ; i.e., SuperClass may implement at least one of the protocols
5430 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5431 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5432 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005433 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005434 // If super class has no protocols, it is not a match.
5435 if (SuperClassInheritedProtocols.empty())
5436 return false;
5437
5438 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5439 LHSPE = LHS->qual_end();
5440 LHSPI != LHSPE; LHSPI++) {
5441 bool SuperImplementsProtocol = false;
5442 ObjCProtocolDecl *LHSProto = (*LHSPI);
5443
5444 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5445 SuperClassInheritedProtocols.begin(),
5446 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5447 ObjCProtocolDecl *SuperClassProto = (*I);
5448 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5449 SuperImplementsProtocol = true;
5450 break;
5451 }
5452 }
5453 if (!SuperImplementsProtocol)
5454 return false;
5455 }
5456 return true;
5457 }
5458 return false;
5459 }
Mike Stump11289f42009-09-09 15:08:12 +00005460
John McCall8b07ec22010-05-15 11:32:37 +00005461 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5462 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005463 LHSPI != LHSPE; LHSPI++) {
5464 bool RHSImplementsProtocol = false;
5465
5466 // If the RHS doesn't implement the protocol on the left, the types
5467 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005468 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5469 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005470 RHSPI != RHSPE; RHSPI++) {
5471 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005472 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005473 break;
5474 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005475 }
5476 // FIXME: For better diagnostics, consider passing back the protocol name.
5477 if (!RHSImplementsProtocol)
5478 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005479 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005480 // The RHS implements all protocols listed on the LHS.
5481 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005482}
5483
Steve Naroffb7605152009-02-12 17:52:19 +00005484bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5485 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005486 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5487 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005488
Steve Naroff7cae42b2009-07-10 23:34:53 +00005489 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005490 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005491
5492 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5493 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005494}
5495
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005496bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5497 return canAssignObjCInterfaces(
5498 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5499 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5500}
5501
Mike Stump11289f42009-09-09 15:08:12 +00005502/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005503/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005504/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005505/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005506bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5507 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00005508 if (getLangOptions().CPlusPlus)
5509 return hasSameType(LHS, RHS);
5510
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005511 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005512}
5513
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005514bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00005515 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005516}
5517
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005518bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5519 return !mergeTypes(LHS, RHS, true).isNull();
5520}
5521
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005522/// mergeTransparentUnionType - if T is a transparent union type and a member
5523/// of T is compatible with SubType, return the merged type, else return
5524/// QualType()
5525QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5526 bool OfBlockPointer,
5527 bool Unqualified) {
5528 if (const RecordType *UT = T->getAsUnionType()) {
5529 RecordDecl *UD = UT->getDecl();
5530 if (UD->hasAttr<TransparentUnionAttr>()) {
5531 for (RecordDecl::field_iterator it = UD->field_begin(),
5532 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005533 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005534 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5535 if (!MT.isNull())
5536 return MT;
5537 }
5538 }
5539 }
5540
5541 return QualType();
5542}
5543
5544/// mergeFunctionArgumentTypes - merge two types which appear as function
5545/// argument types
5546QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5547 bool OfBlockPointer,
5548 bool Unqualified) {
5549 // GNU extension: two types are compatible if they appear as a function
5550 // argument, one of the types is a transparent union type and the other
5551 // type is compatible with a union member
5552 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5553 Unqualified);
5554 if (!lmerge.isNull())
5555 return lmerge;
5556
5557 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5558 Unqualified);
5559 if (!rmerge.isNull())
5560 return rmerge;
5561
5562 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5563}
5564
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005565QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005566 bool OfBlockPointer,
5567 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005568 const FunctionType *lbase = lhs->getAs<FunctionType>();
5569 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005570 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5571 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005572 bool allLTypes = true;
5573 bool allRTypes = true;
5574
5575 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005576 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00005577 if (OfBlockPointer) {
5578 QualType RHS = rbase->getResultType();
5579 QualType LHS = lbase->getResultType();
5580 bool UnqualifiedResult = Unqualified;
5581 if (!UnqualifiedResult)
5582 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005583 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00005584 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005585 else
John McCall8c6b56f2010-12-15 01:06:38 +00005586 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5587 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005588 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005589
5590 if (Unqualified)
5591 retType = retType.getUnqualifiedType();
5592
5593 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5594 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5595 if (Unqualified) {
5596 LRetType = LRetType.getUnqualifiedType();
5597 RRetType = RRetType.getUnqualifiedType();
5598 }
5599
5600 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005601 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005602 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005603 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005604
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005605 // FIXME: double check this
5606 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5607 // rbase->getRegParmAttr() != 0 &&
5608 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005609 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5610 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005611
Douglas Gregor8c940862010-01-18 17:14:39 +00005612 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005613 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005614 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005615
John McCall8c6b56f2010-12-15 01:06:38 +00005616 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00005617 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5618 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00005619 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5620 return QualType();
5621
John McCall31168b02011-06-15 23:02:42 +00005622 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5623 return QualType();
5624
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005625 // functypes which return are preferred over those that do not.
5626 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5627 allLTypes = false;
5628 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5629 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005630 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5631 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00005632
John McCall31168b02011-06-15 23:02:42 +00005633 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00005634
Eli Friedman47f77112008-08-22 00:56:42 +00005635 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005636 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5637 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005638 unsigned lproto_nargs = lproto->getNumArgs();
5639 unsigned rproto_nargs = rproto->getNumArgs();
5640
5641 // Compatible functions must have the same number of arguments
5642 if (lproto_nargs != rproto_nargs)
5643 return QualType();
5644
5645 // Variadic and non-variadic functions aren't compatible
5646 if (lproto->isVariadic() != rproto->isVariadic())
5647 return QualType();
5648
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005649 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5650 return QualType();
5651
Fariborz Jahanian97676972011-09-28 21:52:05 +00005652 if (LangOpts.ObjCAutoRefCount &&
5653 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5654 return QualType();
5655
Eli Friedman47f77112008-08-22 00:56:42 +00005656 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005657 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00005658 for (unsigned i = 0; i < lproto_nargs; i++) {
5659 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5660 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005661 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5662 OfBlockPointer,
5663 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005664 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005665
5666 if (Unqualified)
5667 argtype = argtype.getUnqualifiedType();
5668
Eli Friedman47f77112008-08-22 00:56:42 +00005669 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005670 if (Unqualified) {
5671 largtype = largtype.getUnqualifiedType();
5672 rargtype = rargtype.getUnqualifiedType();
5673 }
5674
Chris Lattner465fa322008-10-05 17:34:18 +00005675 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5676 allLTypes = false;
5677 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5678 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005679 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00005680
Eli Friedman47f77112008-08-22 00:56:42 +00005681 if (allLTypes) return lhs;
5682 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005683
5684 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5685 EPI.ExtInfo = einfo;
5686 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005687 }
5688
5689 if (lproto) allRTypes = false;
5690 if (rproto) allLTypes = false;
5691
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005692 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005693 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005694 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005695 if (proto->isVariadic()) return QualType();
5696 // Check that the types are compatible with the types that
5697 // would result from default argument promotions (C99 6.7.5.3p15).
5698 // The only types actually affected are promotable integer
5699 // types and floats, which would be passed as a different
5700 // type depending on whether the prototype is visible.
5701 unsigned proto_nargs = proto->getNumArgs();
5702 for (unsigned i = 0; i < proto_nargs; ++i) {
5703 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005704
5705 // Look at the promotion type of enum types, since that is the type used
5706 // to pass enum values.
5707 if (const EnumType *Enum = argTy->getAs<EnumType>())
5708 argTy = Enum->getDecl()->getPromotionType();
5709
Eli Friedman47f77112008-08-22 00:56:42 +00005710 if (argTy->isPromotableIntegerType() ||
5711 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5712 return QualType();
5713 }
5714
5715 if (allLTypes) return lhs;
5716 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005717
5718 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5719 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005720 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005721 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005722 }
5723
5724 if (allLTypes) return lhs;
5725 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005726 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005727}
5728
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005729QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005730 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005731 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005732 // C++ [expr]: If an expression initially has the type "reference to T", the
5733 // type is adjusted to "T" prior to any further analysis, the expression
5734 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005735 // expression is an lvalue unless the reference is an rvalue reference and
5736 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005737 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5738 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005739
5740 if (Unqualified) {
5741 LHS = LHS.getUnqualifiedType();
5742 RHS = RHS.getUnqualifiedType();
5743 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005744
Eli Friedman47f77112008-08-22 00:56:42 +00005745 QualType LHSCan = getCanonicalType(LHS),
5746 RHSCan = getCanonicalType(RHS);
5747
5748 // If two types are identical, they are compatible.
5749 if (LHSCan == RHSCan)
5750 return LHS;
5751
John McCall8ccfcb52009-09-24 19:53:00 +00005752 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005753 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5754 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005755 if (LQuals != RQuals) {
5756 // If any of these qualifiers are different, we have a type
5757 // mismatch.
5758 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00005759 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5760 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00005761 return QualType();
5762
5763 // Exactly one GC qualifier difference is allowed: __strong is
5764 // okay if the other type has no GC qualifier but is an Objective
5765 // C object pointer (i.e. implicitly strong by default). We fix
5766 // this by pretending that the unqualified type was actually
5767 // qualified __strong.
5768 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5769 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5770 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5771
5772 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5773 return QualType();
5774
5775 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5776 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5777 }
5778 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5779 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5780 }
Eli Friedman47f77112008-08-22 00:56:42 +00005781 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005782 }
5783
5784 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005785
Eli Friedmandcca6332009-06-01 01:22:52 +00005786 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5787 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005788
Chris Lattnerfd652912008-01-14 05:45:46 +00005789 // We want to consider the two function types to be the same for these
5790 // comparisons, just force one to the other.
5791 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5792 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005793
5794 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005795 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5796 LHSClass = Type::ConstantArray;
5797 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5798 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005799
John McCall8b07ec22010-05-15 11:32:37 +00005800 // ObjCInterfaces are just specialized ObjCObjects.
5801 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5802 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5803
Nate Begemance4d7fc2008-04-18 23:10:10 +00005804 // Canonicalize ExtVector -> Vector.
5805 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5806 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005807
Chris Lattner95554662008-04-07 05:43:21 +00005808 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005809 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005810 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005811 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005812 // Compatibility is based on the underlying type, not the promotion
5813 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005814 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005815 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5816 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005817 }
John McCall9dd450b2009-09-21 23:43:11 +00005818 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005819 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5820 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005821 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005822
Eli Friedman47f77112008-08-22 00:56:42 +00005823 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005824 }
Eli Friedman47f77112008-08-22 00:56:42 +00005825
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005826 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005827 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005828#define TYPE(Class, Base)
5829#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005830#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005831#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5832#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5833#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00005834 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005835
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005836 case Type::LValueReference:
5837 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005838 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00005839 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005840
John McCall8b07ec22010-05-15 11:32:37 +00005841 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005842 case Type::IncompleteArray:
5843 case Type::VariableArray:
5844 case Type::FunctionProto:
5845 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00005846 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005847
Chris Lattnerfd652912008-01-14 05:45:46 +00005848 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005849 {
5850 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005851 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5852 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005853 if (Unqualified) {
5854 LHSPointee = LHSPointee.getUnqualifiedType();
5855 RHSPointee = RHSPointee.getUnqualifiedType();
5856 }
5857 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5858 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005859 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005860 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005861 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005862 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005863 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005864 return getPointerType(ResultType);
5865 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005866 case Type::BlockPointer:
5867 {
5868 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005869 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5870 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005871 if (Unqualified) {
5872 LHSPointee = LHSPointee.getUnqualifiedType();
5873 RHSPointee = RHSPointee.getUnqualifiedType();
5874 }
5875 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5876 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005877 if (ResultType.isNull()) return QualType();
5878 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5879 return LHS;
5880 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5881 return RHS;
5882 return getBlockPointerType(ResultType);
5883 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00005884 case Type::Atomic:
5885 {
5886 // Merge two pointer types, while trying to preserve typedef info
5887 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
5888 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
5889 if (Unqualified) {
5890 LHSValue = LHSValue.getUnqualifiedType();
5891 RHSValue = RHSValue.getUnqualifiedType();
5892 }
5893 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
5894 Unqualified);
5895 if (ResultType.isNull()) return QualType();
5896 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
5897 return LHS;
5898 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
5899 return RHS;
5900 return getAtomicType(ResultType);
5901 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005902 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00005903 {
5904 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5905 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5906 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5907 return QualType();
5908
5909 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5910 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005911 if (Unqualified) {
5912 LHSElem = LHSElem.getUnqualifiedType();
5913 RHSElem = RHSElem.getUnqualifiedType();
5914 }
5915
5916 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005917 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00005918 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5919 return LHS;
5920 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5921 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00005922 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5923 ArrayType::ArraySizeModifier(), 0);
5924 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5925 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005926 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5927 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00005928 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5929 return LHS;
5930 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5931 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005932 if (LVAT) {
5933 // FIXME: This isn't correct! But tricky to implement because
5934 // the array's size has to be the size of LHS, but the type
5935 // has to be different.
5936 return LHS;
5937 }
5938 if (RVAT) {
5939 // FIXME: This isn't correct! But tricky to implement because
5940 // the array's size has to be the size of RHS, but the type
5941 // has to be different.
5942 return RHS;
5943 }
Eli Friedman3e62c212008-08-22 01:48:21 +00005944 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5945 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00005946 return getIncompleteArrayType(ResultType,
5947 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005948 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005949 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005950 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005951 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005952 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00005953 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00005954 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005955 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00005956 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00005957 case Type::Complex:
5958 // Distinct complex types are incompatible.
5959 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005960 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00005961 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00005962 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5963 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00005964 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00005965 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00005966 case Type::ObjCObject: {
5967 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00005968 // FIXME: This should be type compatibility, e.g. whether
5969 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00005970 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5971 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5972 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00005973 return LHS;
5974
Eli Friedman47f77112008-08-22 00:56:42 +00005975 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00005976 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005977 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005978 if (OfBlockPointer) {
5979 if (canAssignObjCInterfacesInBlockPointer(
5980 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005981 RHS->getAs<ObjCObjectPointerType>(),
5982 BlockReturnType))
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005983 return LHS;
5984 return QualType();
5985 }
John McCall9dd450b2009-09-21 23:43:11 +00005986 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5987 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005988 return LHS;
5989
Steve Naroffc68cfcf2008-12-10 22:14:21 +00005990 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005991 }
Steve Naroff32e44c02007-10-15 20:41:53 +00005992 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005993
5994 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005995}
Ted Kremenekfc581a92007-10-31 17:10:13 +00005996
Fariborz Jahanian97676972011-09-28 21:52:05 +00005997bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
5998 const FunctionProtoType *FromFunctionType,
5999 const FunctionProtoType *ToFunctionType) {
6000 if (FromFunctionType->hasAnyConsumedArgs() !=
6001 ToFunctionType->hasAnyConsumedArgs())
6002 return false;
6003 FunctionProtoType::ExtProtoInfo FromEPI =
6004 FromFunctionType->getExtProtoInfo();
6005 FunctionProtoType::ExtProtoInfo ToEPI =
6006 ToFunctionType->getExtProtoInfo();
6007 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6008 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6009 ArgIdx != NumArgs; ++ArgIdx) {
6010 if (FromEPI.ConsumedArguments[ArgIdx] !=
6011 ToEPI.ConsumedArguments[ArgIdx])
6012 return false;
6013 }
6014 return true;
6015}
6016
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006017/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6018/// 'RHS' attributes and returns the merged version; including for function
6019/// return types.
6020QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6021 QualType LHSCan = getCanonicalType(LHS),
6022 RHSCan = getCanonicalType(RHS);
6023 // If two types are identical, they are compatible.
6024 if (LHSCan == RHSCan)
6025 return LHS;
6026 if (RHSCan->isFunctionType()) {
6027 if (!LHSCan->isFunctionType())
6028 return QualType();
6029 QualType OldReturnType =
6030 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6031 QualType NewReturnType =
6032 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6033 QualType ResReturnType =
6034 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6035 if (ResReturnType.isNull())
6036 return QualType();
6037 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6038 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6039 // In either case, use OldReturnType to build the new function type.
6040 const FunctionType *F = LHS->getAs<FunctionType>();
6041 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006042 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6043 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006044 QualType ResultType
6045 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006046 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006047 return ResultType;
6048 }
6049 }
6050 return QualType();
6051 }
6052
6053 // If the qualifiers are different, the types can still be merged.
6054 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6055 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6056 if (LQuals != RQuals) {
6057 // If any of these qualifiers are different, we have a type mismatch.
6058 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6059 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6060 return QualType();
6061
6062 // Exactly one GC qualifier difference is allowed: __strong is
6063 // okay if the other type has no GC qualifier but is an Objective
6064 // C object pointer (i.e. implicitly strong by default). We fix
6065 // this by pretending that the unqualified type was actually
6066 // qualified __strong.
6067 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6068 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6069 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6070
6071 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6072 return QualType();
6073
6074 if (GC_L == Qualifiers::Strong)
6075 return LHS;
6076 if (GC_R == Qualifiers::Strong)
6077 return RHS;
6078 return QualType();
6079 }
6080
6081 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6082 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6083 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6084 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6085 if (ResQT == LHSBaseQT)
6086 return LHS;
6087 if (ResQT == RHSBaseQT)
6088 return RHS;
6089 }
6090 return QualType();
6091}
6092
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006093//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006094// Integer Predicates
6095//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006096
Jay Foad39c79802011-01-12 09:06:06 +00006097unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006098 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006099 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006100 if (T->isBooleanType())
6101 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006102 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006103 return (unsigned)getTypeSize(T);
6104}
6105
6106QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006107 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006108
6109 // Turn <4 x signed int> -> <4 x unsigned int>
6110 if (const VectorType *VTy = T->getAs<VectorType>())
6111 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006112 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006113
6114 // For enums, we return the unsigned version of the base type.
6115 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006116 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006117
6118 const BuiltinType *BTy = T->getAs<BuiltinType>();
6119 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006120 switch (BTy->getKind()) {
6121 case BuiltinType::Char_S:
6122 case BuiltinType::SChar:
6123 return UnsignedCharTy;
6124 case BuiltinType::Short:
6125 return UnsignedShortTy;
6126 case BuiltinType::Int:
6127 return UnsignedIntTy;
6128 case BuiltinType::Long:
6129 return UnsignedLongTy;
6130 case BuiltinType::LongLong:
6131 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006132 case BuiltinType::Int128:
6133 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006134 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006135 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006136 }
6137}
6138
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006139ASTMutationListener::~ASTMutationListener() { }
6140
Chris Lattnerecd79c62009-06-14 00:45:47 +00006141
6142//===----------------------------------------------------------------------===//
6143// Builtin Type Computation
6144//===----------------------------------------------------------------------===//
6145
6146/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006147/// pointer over the consumed characters. This returns the resultant type. If
6148/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6149/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6150/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006151///
6152/// RequiresICE is filled in on return to indicate whether the value is required
6153/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006154static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006155 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006156 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006157 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006158 // Modifiers.
6159 int HowLong = 0;
6160 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006161 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006162
Chris Lattnerdc226c22010-10-01 22:42:38 +00006163 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006164 bool Done = false;
6165 while (!Done) {
6166 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006167 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006168 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006169 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006170 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006171 case 'S':
6172 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6173 assert(!Signed && "Can't use 'S' modifier multiple times!");
6174 Signed = true;
6175 break;
6176 case 'U':
6177 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6178 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6179 Unsigned = true;
6180 break;
6181 case 'L':
6182 assert(HowLong <= 2 && "Can't have LLLL modifier");
6183 ++HowLong;
6184 break;
6185 }
6186 }
6187
6188 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006189
Chris Lattnerecd79c62009-06-14 00:45:47 +00006190 // Read the base type.
6191 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006192 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006193 case 'v':
6194 assert(HowLong == 0 && !Signed && !Unsigned &&
6195 "Bad modifiers used with 'v'!");
6196 Type = Context.VoidTy;
6197 break;
6198 case 'f':
6199 assert(HowLong == 0 && !Signed && !Unsigned &&
6200 "Bad modifiers used with 'f'!");
6201 Type = Context.FloatTy;
6202 break;
6203 case 'd':
6204 assert(HowLong < 2 && !Signed && !Unsigned &&
6205 "Bad modifiers used with 'd'!");
6206 if (HowLong)
6207 Type = Context.LongDoubleTy;
6208 else
6209 Type = Context.DoubleTy;
6210 break;
6211 case 's':
6212 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6213 if (Unsigned)
6214 Type = Context.UnsignedShortTy;
6215 else
6216 Type = Context.ShortTy;
6217 break;
6218 case 'i':
6219 if (HowLong == 3)
6220 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6221 else if (HowLong == 2)
6222 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6223 else if (HowLong == 1)
6224 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6225 else
6226 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6227 break;
6228 case 'c':
6229 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6230 if (Signed)
6231 Type = Context.SignedCharTy;
6232 else if (Unsigned)
6233 Type = Context.UnsignedCharTy;
6234 else
6235 Type = Context.CharTy;
6236 break;
6237 case 'b': // boolean
6238 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6239 Type = Context.BoolTy;
6240 break;
6241 case 'z': // size_t.
6242 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6243 Type = Context.getSizeType();
6244 break;
6245 case 'F':
6246 Type = Context.getCFConstantStringType();
6247 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006248 case 'G':
6249 Type = Context.getObjCIdType();
6250 break;
6251 case 'H':
6252 Type = Context.getObjCSelType();
6253 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006254 case 'a':
6255 Type = Context.getBuiltinVaListType();
6256 assert(!Type.isNull() && "builtin va list type not initialized!");
6257 break;
6258 case 'A':
6259 // This is a "reference" to a va_list; however, what exactly
6260 // this means depends on how va_list is defined. There are two
6261 // different kinds of va_list: ones passed by value, and ones
6262 // passed by reference. An example of a by-value va_list is
6263 // x86, where va_list is a char*. An example of by-ref va_list
6264 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6265 // we want this argument to be a char*&; for x86-64, we want
6266 // it to be a __va_list_tag*.
6267 Type = Context.getBuiltinVaListType();
6268 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006269 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006270 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006271 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006272 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006273 break;
6274 case 'V': {
6275 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006276 unsigned NumElements = strtoul(Str, &End, 10);
6277 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006278 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006279
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006280 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6281 RequiresICE, false);
6282 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006283
6284 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006285 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006286 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006287 break;
6288 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006289 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006290 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6291 false);
6292 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006293 Type = Context.getComplexType(ElementType);
6294 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00006295 }
6296 case 'Y' : {
6297 Type = Context.getPointerDiffType();
6298 break;
6299 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006300 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006301 Type = Context.getFILEType();
6302 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006303 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006304 return QualType();
6305 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006306 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006307 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006308 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006309 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006310 else
6311 Type = Context.getjmp_bufType();
6312
Mike Stump2adb4da2009-07-28 23:47:15 +00006313 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006314 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006315 return QualType();
6316 }
6317 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006318 }
Mike Stump11289f42009-09-09 15:08:12 +00006319
Chris Lattnerdc226c22010-10-01 22:42:38 +00006320 // If there are modifiers and if we're allowed to parse them, go for it.
6321 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006322 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006323 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006324 default: Done = true; --Str; break;
6325 case '*':
6326 case '&': {
6327 // Both pointers and references can have their pointee types
6328 // qualified with an address space.
6329 char *End;
6330 unsigned AddrSpace = strtoul(Str, &End, 10);
6331 if (End != Str && AddrSpace != 0) {
6332 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6333 Str = End;
6334 }
6335 if (c == '*')
6336 Type = Context.getPointerType(Type);
6337 else
6338 Type = Context.getLValueReferenceType(Type);
6339 break;
6340 }
6341 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6342 case 'C':
6343 Type = Type.withConst();
6344 break;
6345 case 'D':
6346 Type = Context.getVolatileType(Type);
6347 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006348 }
6349 }
Chris Lattner84733392010-10-01 07:13:18 +00006350
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006351 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006352 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006353
Chris Lattnerecd79c62009-06-14 00:45:47 +00006354 return Type;
6355}
6356
6357/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006358QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006359 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006360 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006361 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006362
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006363 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006364
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006365 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006366 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006367 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6368 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006369 if (Error != GE_None)
6370 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006371
6372 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6373
Chris Lattnerecd79c62009-06-14 00:45:47 +00006374 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006375 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006376 if (Error != GE_None)
6377 return QualType();
6378
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006379 // If this argument is required to be an IntegerConstantExpression and the
6380 // caller cares, fill in the bitmask we return.
6381 if (RequiresICE && IntegerConstantArgs)
6382 *IntegerConstantArgs |= 1 << ArgTypes.size();
6383
Chris Lattnerecd79c62009-06-14 00:45:47 +00006384 // Do array -> pointer decay. The builtin should use the decayed type.
6385 if (Ty->isArrayType())
6386 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006387
Chris Lattnerecd79c62009-06-14 00:45:47 +00006388 ArgTypes.push_back(Ty);
6389 }
6390
6391 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6392 "'.' should only occur at end of builtin type list!");
6393
John McCall991eb4b2010-12-21 00:44:39 +00006394 FunctionType::ExtInfo EI;
6395 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6396
6397 bool Variadic = (TypeStr[0] == '.');
6398
6399 // We really shouldn't be making a no-proto type here, especially in C++.
6400 if (ArgTypes.empty() && Variadic)
6401 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006402
John McCalldb40c7f2010-12-14 08:05:40 +00006403 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006404 EPI.ExtInfo = EI;
6405 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006406
6407 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006408}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006409
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006410GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6411 GVALinkage External = GVA_StrongExternal;
6412
6413 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006414 switch (L) {
6415 case NoLinkage:
6416 case InternalLinkage:
6417 case UniqueExternalLinkage:
6418 return GVA_Internal;
6419
6420 case ExternalLinkage:
6421 switch (FD->getTemplateSpecializationKind()) {
6422 case TSK_Undeclared:
6423 case TSK_ExplicitSpecialization:
6424 External = GVA_StrongExternal;
6425 break;
6426
6427 case TSK_ExplicitInstantiationDefinition:
6428 return GVA_ExplicitTemplateInstantiation;
6429
6430 case TSK_ExplicitInstantiationDeclaration:
6431 case TSK_ImplicitInstantiation:
6432 External = GVA_TemplateInstantiation;
6433 break;
6434 }
6435 }
6436
6437 if (!FD->isInlined())
6438 return External;
6439
6440 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6441 // GNU or C99 inline semantics. Determine whether this symbol should be
6442 // externally visible.
6443 if (FD->isInlineDefinitionExternallyVisible())
6444 return External;
6445
6446 // C99 inline semantics, where the symbol is not externally visible.
6447 return GVA_C99Inline;
6448 }
6449
6450 // C++0x [temp.explicit]p9:
6451 // [ Note: The intent is that an inline function that is the subject of
6452 // an explicit instantiation declaration will still be implicitly
6453 // instantiated when used so that the body can be considered for
6454 // inlining, but that no out-of-line copy of the inline function would be
6455 // generated in the translation unit. -- end note ]
6456 if (FD->getTemplateSpecializationKind()
6457 == TSK_ExplicitInstantiationDeclaration)
6458 return GVA_C99Inline;
6459
6460 return GVA_CXXInline;
6461}
6462
6463GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6464 // If this is a static data member, compute the kind of template
6465 // specialization. Otherwise, this variable is not part of a
6466 // template.
6467 TemplateSpecializationKind TSK = TSK_Undeclared;
6468 if (VD->isStaticDataMember())
6469 TSK = VD->getTemplateSpecializationKind();
6470
6471 Linkage L = VD->getLinkage();
6472 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6473 VD->getType()->getLinkage() == UniqueExternalLinkage)
6474 L = UniqueExternalLinkage;
6475
6476 switch (L) {
6477 case NoLinkage:
6478 case InternalLinkage:
6479 case UniqueExternalLinkage:
6480 return GVA_Internal;
6481
6482 case ExternalLinkage:
6483 switch (TSK) {
6484 case TSK_Undeclared:
6485 case TSK_ExplicitSpecialization:
6486 return GVA_StrongExternal;
6487
6488 case TSK_ExplicitInstantiationDeclaration:
6489 llvm_unreachable("Variable should not be instantiated");
6490 // Fall through to treat this like any other instantiation.
6491
6492 case TSK_ExplicitInstantiationDefinition:
6493 return GVA_ExplicitTemplateInstantiation;
6494
6495 case TSK_ImplicitInstantiation:
6496 return GVA_TemplateInstantiation;
6497 }
6498 }
6499
6500 return GVA_StrongExternal;
6501}
6502
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00006503bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006504 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6505 if (!VD->isFileVarDecl())
6506 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00006507 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006508 return false;
6509
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006510 // Weak references don't produce any output by themselves.
6511 if (D->hasAttr<WeakRefAttr>())
6512 return false;
6513
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006514 // Aliases and used decls are required.
6515 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6516 return true;
6517
6518 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6519 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00006520 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00006521 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006522
6523 // Constructors and destructors are required.
6524 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6525 return true;
6526
6527 // The key function for a class is required.
6528 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6529 const CXXRecordDecl *RD = MD->getParent();
6530 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6531 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6532 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6533 return true;
6534 }
6535 }
6536
6537 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6538
6539 // static, static inline, always_inline, and extern inline functions can
6540 // always be deferred. Normal inline functions can be deferred in C99/C++.
6541 // Implicit template instantiations can also be deferred in C++.
6542 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6543 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6544 return false;
6545 return true;
6546 }
Douglas Gregor87d81242011-09-10 00:22:34 +00006547
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006548 const VarDecl *VD = cast<VarDecl>(D);
6549 assert(VD->isFileVarDecl() && "Expected file scoped var");
6550
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006551 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6552 return false;
6553
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006554 // Structs that have non-trivial constructors or destructors are required.
6555
6556 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00006557 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006558 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6559 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00006560 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6561 RD->hasTrivialCopyConstructor() &&
6562 RD->hasTrivialMoveConstructor() &&
6563 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006564 return true;
6565 }
6566 }
6567
6568 GVALinkage L = GetGVALinkageForVariable(VD);
6569 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6570 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6571 return false;
6572 }
6573
6574 return true;
6575}
Charles Davis53c59df2010-08-16 03:33:14 +00006576
Charles Davis99202b32010-11-09 18:04:24 +00006577CallingConv ASTContext::getDefaultMethodCallConv() {
6578 // Pass through to the C++ ABI object
6579 return ABI->getDefaultMethodCallConv();
6580}
6581
Jay Foad39c79802011-01-12 09:06:06 +00006582bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00006583 // Pass through to the C++ ABI object
6584 return ABI->isNearlyEmpty(RD);
6585}
6586
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006587MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00006588 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006589 case CXXABI_ARM:
6590 case CXXABI_Itanium:
6591 return createItaniumMangleContext(*this, getDiagnostics());
6592 case CXXABI_Microsoft:
6593 return createMicrosoftMangleContext(*this, getDiagnostics());
6594 }
David Blaikie83d382b2011-09-23 05:06:16 +00006595 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006596}
6597
Charles Davis53c59df2010-08-16 03:33:14 +00006598CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006599
6600size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00006601 return ASTRecordLayouts.getMemorySize()
6602 + llvm::capacity_in_bytes(ObjCLayouts)
6603 + llvm::capacity_in_bytes(KeyFunctions)
6604 + llvm::capacity_in_bytes(ObjCImpls)
6605 + llvm::capacity_in_bytes(BlockVarCopyInits)
6606 + llvm::capacity_in_bytes(DeclAttrs)
6607 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6608 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6609 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6610 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6611 + llvm::capacity_in_bytes(OverriddenMethods)
6612 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006613 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00006614 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006615}
Ted Kremenek540017e2011-10-06 05:00:56 +00006616
6617void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6618 ParamIndices[D] = index;
6619}
6620
6621unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6622 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6623 assert(I != ParamIndices.end() &&
6624 "ParmIndices lacks entry set by ParmVarDecl");
6625 return I->second;
6626}