blob: ba3f503e3b0c1c5fad14b06fd6a270c299847ba4 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCallea1471e2010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +000033#include "llvm/Support/Capacity.h"
Charles Davis071cc7d2010-08-16 03:33:14 +000034#include "CXXABI.h"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000035#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000036
Reid Spencer5f016e22007-07-11 17:01:13 +000037using namespace clang;
38
Douglas Gregor18274032010-07-03 00:47:00 +000039unsigned ASTContext::NumImplicitDefaultConstructors;
40unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000041unsigned ASTContext::NumImplicitCopyConstructors;
42unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000043unsigned ASTContext::NumImplicitMoveConstructors;
44unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000045unsigned ASTContext::NumImplicitCopyAssignmentOperators;
46unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000047unsigned ASTContext::NumImplicitMoveAssignmentOperators;
48unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000049unsigned ASTContext::NumImplicitDestructors;
50unsigned ASTContext::NumImplicitDestructorsDeclared;
51
Reid Spencer5f016e22007-07-11 17:01:13 +000052enum FloatingRank {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +000053 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Reid Spencer5f016e22007-07-11 17:01:13 +000054};
55
Douglas Gregor3e1274f2010-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 Gregor61c4d282011-01-05 15:48:55 +000061 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-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 Gregor61c4d282011-01-05 15:48:55 +000076 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman9e9c4542012-03-07 01:09:33 +000077 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +000078 if (NTTP->isExpandedParameterPack()) {
79 ID.AddBoolean(true);
80 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman9e9c4542012-03-07 01:09:33 +000081 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
82 QualType T = NTTP->getExpansionType(I);
83 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
84 }
Douglas Gregor6952f1e2011-01-19 20:10:05 +000085 } else
86 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +000087 continue;
88 }
89
90 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
91 ID.AddInteger(2);
92 Profile(ID, TTP);
93 }
94}
95
96TemplateTemplateParmDecl *
97ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +000098 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +000099 // Check if we already have a canonical template template parameter.
100 llvm::FoldingSetNodeID ID;
101 CanonicalTemplateTemplateParm::Profile(ID, TTP);
102 void *InsertPos = 0;
103 CanonicalTemplateTemplateParm *Canonical
104 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
105 if (Canonical)
106 return Canonical->getParam();
107
108 // Build a canonical template parameter list.
109 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000110 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000111 CanonParams.reserve(Params->size());
112 for (TemplateParameterList::const_iterator P = Params->begin(),
113 PEnd = Params->end();
114 P != PEnd; ++P) {
115 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
116 CanonParams.push_back(
117 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000118 SourceLocation(),
119 SourceLocation(),
120 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000121 TTP->getIndex(), 0, false,
122 TTP->isParameterPack()));
123 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000124 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
125 QualType T = getCanonicalType(NTTP->getType());
126 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
127 NonTypeTemplateParmDecl *Param;
128 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000129 SmallVector<QualType, 2> ExpandedTypes;
130 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000131 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
132 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
133 ExpandedTInfos.push_back(
134 getTrivialTypeSourceInfo(ExpandedTypes.back()));
135 }
136
137 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000138 SourceLocation(),
139 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000140 NTTP->getDepth(),
141 NTTP->getPosition(), 0,
142 T,
143 TInfo,
144 ExpandedTypes.data(),
145 ExpandedTypes.size(),
146 ExpandedTInfos.data());
147 } else {
148 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000149 SourceLocation(),
150 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000151 NTTP->getDepth(),
152 NTTP->getPosition(), 0,
153 T,
154 NTTP->isParameterPack(),
155 TInfo);
156 }
157 CanonParams.push_back(Param);
158
159 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000160 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
161 cast<TemplateTemplateParmDecl>(*P)));
162 }
163
164 TemplateTemplateParmDecl *CanonTTP
165 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
166 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000167 TTP->getPosition(),
168 TTP->isParameterPack(),
169 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000170 TemplateParameterList::Create(*this, SourceLocation(),
171 SourceLocation(),
172 CanonParams.data(),
173 CanonParams.size(),
174 SourceLocation()));
175
176 // Get the new insert position for the node we care about.
177 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
178 assert(Canonical == 0 && "Shouldn't be in the map!");
179 (void)Canonical;
180
181 // Create the canonical template template parameter entry.
182 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
183 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
184 return CanonTTP;
185}
186
Charles Davis071cc7d2010-08-16 03:33:14 +0000187CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000188 if (!LangOpts.CPlusPlus) return 0;
189
Charles Davis20cf7172010-08-19 02:18:14 +0000190 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000191 case CXXABI_ARM:
192 return CreateARMCXXABI(*this);
193 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000194 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000195 case CXXABI_Microsoft:
196 return CreateMicrosoftCXXABI(*this);
197 }
David Blaikie7530c032012-01-17 06:56:22 +0000198 llvm_unreachable("Invalid CXXABI type!");
Charles Davis071cc7d2010-08-16 03:33:14 +0000199}
200
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000201static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000202 const LangOptions &LOpts) {
203 if (LOpts.FakeAddressSpaceMap) {
204 // The fake address space map must have a distinct entry for each
205 // language-specific address space.
206 static const unsigned FakeAddrSpaceMap[] = {
207 1, // opencl_global
208 2, // opencl_local
209 3 // opencl_constant
210 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000211 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000212 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000213 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000214 }
215}
216
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000217ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000218 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000219 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000220 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000221 unsigned size_reserve,
222 bool DelayInitialization)
223 : FunctionProtoTypes(this_()),
224 TemplateSpecializationTypes(this_()),
225 DependentTemplateSpecializationTypes(this_()),
226 SubstTemplateTemplateParmPacks(this_()),
227 GlobalNestedNameSpecifier(0),
228 Int128Decl(0), UInt128Decl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000229 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000230 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000231 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000232 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
233 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
234 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000235 NullTypeSourceInfo(QualType()),
236 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000237 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000238 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000239 Idents(idents), Selectors(sels),
240 BuiltinInfo(builtins),
241 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000242 ExternalSource(0), Listener(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000243 LastSDM(0, 0),
244 UniqueBlockByRefTypeID(0)
245{
Mike Stump1eb44332009-09-09 15:08:12 +0000246 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000247 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000248
249 if (!DelayInitialization) {
250 assert(t && "No target supplied for ASTContext initialization");
251 InitBuiltinTypes(*t);
252 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000253}
254
Reid Spencer5f016e22007-07-11 17:01:13 +0000255ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000256 // Release the DenseMaps associated with DeclContext objects.
257 // FIXME: Is this the ideal solution?
258 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000259
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000260 // Call all of the deallocation functions.
261 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
262 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000263
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000264 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000265 // because they can contain DenseMaps.
266 for (llvm::DenseMap<const ObjCContainerDecl*,
267 const ASTRecordLayout*>::iterator
268 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
269 // Increment in loop to prevent using deallocated memory.
270 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
271 R->Destroy(*this);
272
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000273 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
274 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
275 // Increment in loop to prevent using deallocated memory.
276 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
277 R->Destroy(*this);
278 }
Douglas Gregor63200642010-08-30 16:49:28 +0000279
280 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
281 AEnd = DeclAttrs.end();
282 A != AEnd; ++A)
283 A->second->~AttrVec();
284}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000285
Douglas Gregor00545312010-05-23 18:26:36 +0000286void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
287 Deallocations.push_back(std::make_pair(Callback, Data));
288}
289
Mike Stump1eb44332009-09-09 15:08:12 +0000290void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000291ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000292 ExternalSource.reset(Source.take());
293}
294
Reid Spencer5f016e22007-07-11 17:01:13 +0000295void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000296 llvm::errs() << "\n*** AST Context Stats:\n";
297 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000298
Douglas Gregordbe833d2009-05-26 14:40:08 +0000299 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000300#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000301#define ABSTRACT_TYPE(Name, Parent)
302#include "clang/AST/TypeNodes.def"
303 0 // Extra
304 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000305
Reid Spencer5f016e22007-07-11 17:01:13 +0000306 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
307 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000308 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000309 }
310
Douglas Gregordbe833d2009-05-26 14:40:08 +0000311 unsigned Idx = 0;
312 unsigned TotalBytes = 0;
313#define TYPE(Name, Parent) \
314 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000315 llvm::errs() << " " << counts[Idx] << " " << #Name \
316 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000317 TotalBytes += counts[Idx] * sizeof(Name##Type); \
318 ++Idx;
319#define ABSTRACT_TYPE(Name, Parent)
320#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Chandler Carruthcd92a652011-07-04 05:32:14 +0000322 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
323
Douglas Gregor4923aa22010-07-02 20:37:36 +0000324 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000325 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
326 << NumImplicitDefaultConstructors
327 << " implicit default constructors created\n";
328 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
329 << NumImplicitCopyConstructors
330 << " implicit copy constructors created\n";
Sean Huntffe37fd2011-05-25 20:50:04 +0000331 if (getLangOptions().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000332 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
333 << NumImplicitMoveConstructors
334 << " implicit move constructors created\n";
335 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
336 << NumImplicitCopyAssignmentOperators
337 << " implicit copy assignment operators created\n";
Sean Huntffe37fd2011-05-25 20:50:04 +0000338 if (getLangOptions().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000339 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
340 << NumImplicitMoveAssignmentOperators
341 << " implicit move assignment operators created\n";
342 llvm::errs() << NumImplicitDestructorsDeclared << "/"
343 << NumImplicitDestructors
344 << " implicit destructors created\n";
345
Douglas Gregor2cf26342009-04-09 22:27:44 +0000346 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000347 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000348 ExternalSource->PrintStats();
349 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000350
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000351 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000352}
353
Douglas Gregor772eeae2011-08-12 06:49:56 +0000354TypedefDecl *ASTContext::getInt128Decl() const {
355 if (!Int128Decl) {
356 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
357 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
358 getTranslationUnitDecl(),
359 SourceLocation(),
360 SourceLocation(),
361 &Idents.get("__int128_t"),
362 TInfo);
363 }
364
365 return Int128Decl;
366}
367
368TypedefDecl *ASTContext::getUInt128Decl() const {
369 if (!UInt128Decl) {
370 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
371 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
372 getTranslationUnitDecl(),
373 SourceLocation(),
374 SourceLocation(),
375 &Idents.get("__uint128_t"),
376 TInfo);
377 }
378
379 return UInt128Decl;
380}
Reid Spencer5f016e22007-07-11 17:01:13 +0000381
John McCalle27ec8a2009-10-23 23:03:21 +0000382void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000383 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000384 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000385 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000386}
387
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000388void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
389 assert((!this->Target || this->Target == &Target) &&
390 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000391 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000393 this->Target = &Target;
394
395 ABI.reset(createCXXABI(Target));
396 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
397
Reid Spencer5f016e22007-07-11 17:01:13 +0000398 // C99 6.2.5p19.
399 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Reid Spencer5f016e22007-07-11 17:01:13 +0000401 // C99 6.2.5p2.
402 InitBuiltinType(BoolTy, BuiltinType::Bool);
403 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000404 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000405 InitBuiltinType(CharTy, BuiltinType::Char_S);
406 else
407 InitBuiltinType(CharTy, BuiltinType::Char_U);
408 // C99 6.2.5p4.
409 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
410 InitBuiltinType(ShortTy, BuiltinType::Short);
411 InitBuiltinType(IntTy, BuiltinType::Int);
412 InitBuiltinType(LongTy, BuiltinType::Long);
413 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Reid Spencer5f016e22007-07-11 17:01:13 +0000415 // C99 6.2.5p6.
416 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
417 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
418 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
419 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
420 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Reid Spencer5f016e22007-07-11 17:01:13 +0000422 // C99 6.2.5p10.
423 InitBuiltinType(FloatTy, BuiltinType::Float);
424 InitBuiltinType(DoubleTy, BuiltinType::Double);
425 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000426
Chris Lattner2df9ced2009-04-30 02:43:43 +0000427 // GNU extension, 128-bit integers.
428 InitBuiltinType(Int128Ty, BuiltinType::Int128);
429 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
430
Chris Lattner3f59c972010-12-25 23:25:43 +0000431 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedmand3d77cd2011-04-30 19:24:24 +0000432 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattner3f59c972010-12-25 23:25:43 +0000433 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
434 else // -fshort-wchar makes wchar_t be unsigned.
435 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
436 } else // C99
Chris Lattner3a250322009-02-26 23:43:47 +0000437 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000438
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000439 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
440 InitBuiltinType(Char16Ty, BuiltinType::Char16);
441 else // C99
442 Char16Ty = getFromTargetType(Target.getChar16Type());
443
444 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
445 InitBuiltinType(Char32Ty, BuiltinType::Char32);
446 else // C99
447 Char32Ty = getFromTargetType(Target.getChar32Type());
448
Douglas Gregor898574e2008-12-05 23:32:09 +0000449 // Placeholder type for type-dependent expressions whose type is
450 // completely unknown. No code should ever check a type against
451 // DependentTy and users should never see it; however, it is here to
452 // help diagnose failures to properly check for type-dependent
453 // expressions.
454 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000455
John McCall2a984ca2010-10-12 00:20:44 +0000456 // Placeholder type for functions.
457 InitBuiltinType(OverloadTy, BuiltinType::Overload);
458
John McCall864c0412011-04-26 20:42:42 +0000459 // Placeholder type for bound members.
460 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
461
John McCall3c3b7f92011-10-25 17:37:35 +0000462 // Placeholder type for pseudo-objects.
463 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
464
John McCall1de4d4e2011-04-07 08:22:57 +0000465 // "any" type; useful for debugger-like clients.
466 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
467
John McCall0ddaeb92011-10-17 18:09:15 +0000468 // Placeholder type for unbridged ARC casts.
469 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
470
Reid Spencer5f016e22007-07-11 17:01:13 +0000471 // C99 6.2.5p11.
472 FloatComplexTy = getComplexType(FloatTy);
473 DoubleComplexTy = getComplexType(DoubleTy);
474 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000475
Steve Naroff7e219e42007-10-15 14:41:52 +0000476 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000477
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000478 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000479 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
480 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000481 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000482
483 // Builtin type for __objc_yes and __objc_no
484 ObjCBuiltinBoolTy = SignedCharTy;
485
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000486 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000487
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000488 // void * type
489 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000490
491 // nullptr type (C++0x 2.14.7)
492 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000493
494 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
495 InitBuiltinType(HalfTy, BuiltinType::Half);
Reid Spencer5f016e22007-07-11 17:01:13 +0000496}
497
David Blaikied6471f72011-09-25 23:23:43 +0000498DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000499 return SourceMgr.getDiagnostics();
500}
501
Douglas Gregor63200642010-08-30 16:49:28 +0000502AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
503 AttrVec *&Result = DeclAttrs[D];
504 if (!Result) {
505 void *Mem = Allocate(sizeof(AttrVec));
506 Result = new (Mem) AttrVec;
507 }
508
509 return *Result;
510}
511
512/// \brief Erase the attributes corresponding to the given declaration.
513void ASTContext::eraseDeclAttrs(const Decl *D) {
514 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
515 if (Pos != DeclAttrs.end()) {
516 Pos->second->~AttrVec();
517 DeclAttrs.erase(Pos);
518 }
519}
520
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000521MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000522ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000523 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000524 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000525 = InstantiatedFromStaticDataMember.find(Var);
526 if (Pos == InstantiatedFromStaticDataMember.end())
527 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Douglas Gregor7caa6822009-07-24 20:34:43 +0000529 return Pos->second;
530}
531
Mike Stump1eb44332009-09-09 15:08:12 +0000532void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000533ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000534 TemplateSpecializationKind TSK,
535 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000536 assert(Inst->isStaticDataMember() && "Not a static data member");
537 assert(Tmpl->isStaticDataMember() && "Not a static data member");
538 assert(!InstantiatedFromStaticDataMember[Inst] &&
539 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000540 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000541 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000542}
543
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000544FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
545 const FunctionDecl *FD){
546 assert(FD && "Specialization is 0");
547 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000548 = ClassScopeSpecializationPattern.find(FD);
549 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000550 return 0;
551
552 return Pos->second;
553}
554
555void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
556 FunctionDecl *Pattern) {
557 assert(FD && "Specialization is 0");
558 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000559 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000560}
561
John McCall7ba107a2009-11-18 02:36:19 +0000562NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000563ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000564 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000565 = InstantiatedFromUsingDecl.find(UUD);
566 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000567 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Anders Carlsson0d8df782009-08-29 19:37:28 +0000569 return Pos->second;
570}
571
572void
John McCalled976492009-12-04 22:46:56 +0000573ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
574 assert((isa<UsingDecl>(Pattern) ||
575 isa<UnresolvedUsingValueDecl>(Pattern) ||
576 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
577 "pattern decl is not a using decl");
578 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
579 InstantiatedFromUsingDecl[Inst] = Pattern;
580}
581
582UsingShadowDecl *
583ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
584 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
585 = InstantiatedFromUsingShadowDecl.find(Inst);
586 if (Pos == InstantiatedFromUsingShadowDecl.end())
587 return 0;
588
589 return Pos->second;
590}
591
592void
593ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
594 UsingShadowDecl *Pattern) {
595 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
596 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000597}
598
Anders Carlssond8b285f2009-09-01 04:26:58 +0000599FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
600 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
601 = InstantiatedFromUnnamedFieldDecl.find(Field);
602 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
603 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000604
Anders Carlssond8b285f2009-09-01 04:26:58 +0000605 return Pos->second;
606}
607
608void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
609 FieldDecl *Tmpl) {
610 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
611 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
612 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
613 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000614
Anders Carlssond8b285f2009-09-01 04:26:58 +0000615 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
616}
617
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000618bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
619 const FieldDecl *LastFD) const {
620 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000621 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000622}
623
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000624bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
625 const FieldDecl *LastFD) const {
626 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000627 FD->getBitWidthValue(*this) == 0 &&
628 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000629}
630
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000631bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
632 const FieldDecl *LastFD) const {
633 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000634 FD->getBitWidthValue(*this) &&
635 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000636}
637
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000638bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000639 const FieldDecl *LastFD) const {
640 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000641 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000642}
643
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000644bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000645 const FieldDecl *LastFD) const {
646 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000647 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000648}
649
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000650ASTContext::overridden_cxx_method_iterator
651ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
652 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
653 = OverriddenMethods.find(Method);
654 if (Pos == OverriddenMethods.end())
655 return 0;
656
657 return Pos->second.begin();
658}
659
660ASTContext::overridden_cxx_method_iterator
661ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
662 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
663 = OverriddenMethods.find(Method);
664 if (Pos == OverriddenMethods.end())
665 return 0;
666
667 return Pos->second.end();
668}
669
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000670unsigned
671ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
672 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
673 = OverriddenMethods.find(Method);
674 if (Pos == OverriddenMethods.end())
675 return 0;
676
677 return Pos->second.size();
678}
679
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000680void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
681 const CXXMethodDecl *Overridden) {
682 OverriddenMethods[Method].push_back(Overridden);
683}
684
Douglas Gregore6649772011-12-03 00:30:27 +0000685void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
686 assert(!Import->NextLocalImport && "Import declaration already in the chain");
687 assert(!Import->isFromASTFile() && "Non-local import declaration");
688 if (!FirstLocalImport) {
689 FirstLocalImport = Import;
690 LastLocalImport = Import;
691 return;
692 }
693
694 LastLocalImport->NextLocalImport = Import;
695 LastLocalImport = Import;
696}
697
Chris Lattner464175b2007-07-18 17:52:12 +0000698//===----------------------------------------------------------------------===//
699// Type Sizing and Analysis
700//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000701
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000702/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
703/// scalar floating point type.
704const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000705 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000706 assert(BT && "Not a floating point type!");
707 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000708 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000709 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000710 case BuiltinType::Float: return Target->getFloatFormat();
711 case BuiltinType::Double: return Target->getDoubleFormat();
712 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000713 }
714}
715
Ken Dyck8b752f12010-01-27 17:10:57 +0000716/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000717/// specified decl. Note that bitfields do not have a valid alignment, so
718/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000719/// If @p RefAsPointee, references are treated like their underlying type
720/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +0000721CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000722 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +0000723
John McCall4081a5c2010-10-08 18:24:19 +0000724 bool UseAlignAttrOnly = false;
725 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
726 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +0000727
John McCall4081a5c2010-10-08 18:24:19 +0000728 // __attribute__((aligned)) can increase or decrease alignment
729 // *except* on a struct or struct member, where it only increases
730 // alignment unless 'packed' is also specified.
731 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +0000732 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +0000733 // ignore that possibility; Sema should diagnose it.
734 if (isa<FieldDecl>(D)) {
735 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
736 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
737 } else {
738 UseAlignAttrOnly = true;
739 }
740 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +0000741 else if (isa<FieldDecl>(D))
742 UseAlignAttrOnly =
743 D->hasAttr<PackedAttr>() ||
744 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +0000745
John McCallba4f5d52011-01-20 07:57:12 +0000746 // If we're using the align attribute only, just ignore everything
747 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +0000748 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +0000749 // do nothing
750
John McCall4081a5c2010-10-08 18:24:19 +0000751 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +0000752 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000753 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000754 if (RefAsPointee)
755 T = RT->getPointeeType();
756 else
757 T = getPointerType(RT->getPointeeType());
758 }
759 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +0000760 // Adjust alignments of declarations with array type by the
761 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000762 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +0000763 const ArrayType *arrayType;
764 if (MinWidth && (arrayType = getAsArrayType(T))) {
765 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000766 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +0000767 else if (isa<ConstantArrayType>(arrayType) &&
768 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000769 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000770
John McCall3b657512011-01-19 10:06:00 +0000771 // Walk through any array types while we're at it.
772 T = getBaseElementType(arrayType);
773 }
Chad Rosier9f1210c2011-07-26 07:03:04 +0000774 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedmandcdafb62009-02-22 02:56:25 +0000775 }
John McCallba4f5d52011-01-20 07:57:12 +0000776
777 // Fields can be subject to extra alignment constraints, like if
778 // the field is packed, the struct is packed, or the struct has a
779 // a max-field-alignment constraint (#pragma pack). So calculate
780 // the actual alignment of the field within the struct, and then
781 // (as we're expected to) constrain that by the alignment of the type.
782 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
783 // So calculate the alignment of the field.
784 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
785
786 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +0000787 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +0000788
789 // Use the GCD of that and the offset within the record.
790 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
791 if (offset > 0) {
792 // Alignment is always a power of 2, so the GCD will be a power of 2,
793 // which means we get to do this crazy thing instead of Euclid's.
794 uint64_t lowBitOfOffset = offset & (~offset + 1);
795 if (lowBitOfOffset < fieldAlign)
796 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
797 }
798
799 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +0000800 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000801 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000802
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000803 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +0000804}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000805
John McCallea1471e2010-05-20 01:18:31 +0000806std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000807ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +0000808 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000809 return std::make_pair(toCharUnitsFromBits(Info.first),
810 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +0000811}
812
813std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000814ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +0000815 return getTypeInfoInChars(T.getTypePtr());
816}
817
Daniel Dunbarbc5419a2012-03-09 04:12:54 +0000818std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
819 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
820 if (it != MemoizedTypeInfo.end())
821 return it->second;
822
823 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
824 MemoizedTypeInfo.insert(std::make_pair(T, Info));
825 return Info;
826}
827
828/// getTypeInfoImpl - Return the size of the specified type, in bits. This
829/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000830///
831/// FIXME: Pointers into different addr spaces could have different sizes and
832/// alignment requirements: getPointerInfo should take an AddrSpace, this
833/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000834std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +0000835ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +0000836 uint64_t Width=0;
837 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000838 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000839#define TYPE(Class, Base)
840#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000841#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000842#define DEPENDENT_TYPE(Class, Base) case Type::Class:
843#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +0000844 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000845
Chris Lattner692233e2007-07-13 22:27:08 +0000846 case Type::FunctionNoProto:
847 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000848 // GCC extension: alignof(function) = 32 bits
849 Width = 0;
850 Align = 32;
851 break;
852
Douglas Gregor72564e72009-02-26 23:50:07 +0000853 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000854 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000855 Width = 0;
856 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
857 break;
858
Steve Narofffb22d962007-08-30 01:06:46 +0000859 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000860 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000861
Chris Lattner98be4942008-03-05 18:54:05 +0000862 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +0000863 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +0000864 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
865 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +0000866 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +0000867 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +0000868 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000869 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000870 }
Nate Begeman213541a2008-04-18 23:10:10 +0000871 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000872 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000873 const VectorType *VT = cast<VectorType>(T);
874 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
875 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000876 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000877 // If the alignment is not a power of 2, round up to the next power of 2.
878 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000879 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000880 Align = llvm::NextPowerOf2(Align);
881 Width = llvm::RoundUpToAlignment(Width, Align);
882 }
Chris Lattner030d8842007-07-19 22:06:24 +0000883 break;
884 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000885
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000886 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000887 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000888 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000889 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000890 // GCC extension: alignof(void) = 8 bits.
891 Width = 0;
892 Align = 8;
893 break;
894
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000895 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000896 Width = Target->getBoolWidth();
897 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000898 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000899 case BuiltinType::Char_S:
900 case BuiltinType::Char_U:
901 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000902 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000903 Width = Target->getCharWidth();
904 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000905 break;
Chris Lattner3f59c972010-12-25 23:25:43 +0000906 case BuiltinType::WChar_S:
907 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000908 Width = Target->getWCharWidth();
909 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000910 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000911 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000912 Width = Target->getChar16Width();
913 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000914 break;
915 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000916 Width = Target->getChar32Width();
917 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000918 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000919 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000920 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000921 Width = Target->getShortWidth();
922 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000923 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000924 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000925 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000926 Width = Target->getIntWidth();
927 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000928 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000929 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000930 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000931 Width = Target->getLongWidth();
932 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000933 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000934 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000935 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000936 Width = Target->getLongLongWidth();
937 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000938 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000939 case BuiltinType::Int128:
940 case BuiltinType::UInt128:
941 Width = 128;
942 Align = 128; // int128_t is 128-bit aligned on all targets.
943 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000944 case BuiltinType::Half:
945 Width = Target->getHalfWidth();
946 Align = Target->getHalfAlign();
947 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000948 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000949 Width = Target->getFloatWidth();
950 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000951 break;
952 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000953 Width = Target->getDoubleWidth();
954 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000955 break;
956 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000957 Width = Target->getLongDoubleWidth();
958 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000959 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000960 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000961 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
962 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000963 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000964 case BuiltinType::ObjCId:
965 case BuiltinType::ObjCClass:
966 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000967 Width = Target->getPointerWidth(0);
968 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000969 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000970 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000971 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000972 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000973 Width = Target->getPointerWidth(0);
974 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000975 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000976 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000977 unsigned AS = getTargetAddressSpace(
978 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000979 Width = Target->getPointerWidth(AS);
980 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +0000981 break;
982 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000983 case Type::LValueReference:
984 case Type::RValueReference: {
985 // alignof and sizeof should never enter this code path here, so we go
986 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000987 unsigned AS = getTargetAddressSpace(
988 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000989 Width = Target->getPointerWidth(AS);
990 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +0000991 break;
992 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000993 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000994 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000995 Width = Target->getPointerWidth(AS);
996 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000997 break;
998 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000999 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001000 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001001 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001002 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +00001003 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001004 Align = PtrDiffInfo.second;
1005 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001006 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001007 case Type::Complex: {
1008 // Complex types have the same alignment as their elements, but twice the
1009 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001010 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001011 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001012 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001013 Align = EltInfo.second;
1014 break;
1015 }
John McCallc12c5bb2010-05-15 11:32:37 +00001016 case Type::ObjCObject:
1017 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001018 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001019 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001020 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001021 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001022 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001023 break;
1024 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001025 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001026 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001027 const TagType *TT = cast<TagType>(T);
1028
1029 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001030 Width = 8;
1031 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001032 break;
1033 }
Mike Stump1eb44332009-09-09 15:08:12 +00001034
Daniel Dunbar1d751182008-11-08 05:48:37 +00001035 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001036 return getTypeInfo(ET->getDecl()->getIntegerType());
1037
Daniel Dunbar1d751182008-11-08 05:48:37 +00001038 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001039 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001040 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001041 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001042 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001043 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001044
Chris Lattner9fcfe922009-10-22 05:17:15 +00001045 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001046 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1047 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001048
Richard Smith34b41d92011-02-20 03:19:35 +00001049 case Type::Auto: {
1050 const AutoType *A = cast<AutoType>(T);
1051 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001052 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001053 }
1054
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001055 case Type::Paren:
1056 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1057
Douglas Gregor18857642009-04-30 17:32:17 +00001058 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001059 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001060 std::pair<uint64_t, unsigned> Info
1061 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001062 // If the typedef has an aligned attribute on it, it overrides any computed
1063 // alignment we have. This violates the GCC documentation (which says that
1064 // attribute(aligned) can only round up) but matches its implementation.
1065 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1066 Align = AttrAlign;
1067 else
1068 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001069 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001070 break;
Chris Lattner71763312008-04-06 22:05:18 +00001071 }
Douglas Gregor18857642009-04-30 17:32:17 +00001072
1073 case Type::TypeOfExpr:
1074 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1075 .getTypePtr());
1076
1077 case Type::TypeOf:
1078 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1079
Anders Carlsson395b4752009-06-24 19:06:50 +00001080 case Type::Decltype:
1081 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1082 .getTypePtr());
1083
Sean Huntca63c202011-05-24 22:41:36 +00001084 case Type::UnaryTransform:
1085 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1086
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001087 case Type::Elaborated:
1088 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001089
John McCall9d156a72011-01-06 01:58:22 +00001090 case Type::Attributed:
1091 return getTypeInfo(
1092 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1093
Richard Smith3e4c6c42011-05-05 21:57:07 +00001094 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001095 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001096 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001097 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1098 // A type alias template specialization may refer to a typedef with the
1099 // aligned attribute on it.
1100 if (TST->isTypeAlias())
1101 return getTypeInfo(TST->getAliasedType().getTypePtr());
1102 else
1103 return getTypeInfo(getCanonicalType(T));
1104 }
1105
Eli Friedmanb001de72011-10-06 23:00:33 +00001106 case Type::Atomic: {
Eli Friedman2be46072011-10-14 20:59:01 +00001107 std::pair<uint64_t, unsigned> Info
1108 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1109 Width = Info.first;
1110 Align = Info.second;
1111 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1112 llvm::isPowerOf2_64(Width)) {
1113 // We can potentially perform lock-free atomic operations for this
1114 // type; promote the alignment appropriately.
1115 // FIXME: We could potentially promote the width here as well...
1116 // is that worthwhile? (Non-struct atomic types generally have
1117 // power-of-two size anyway, but structs might not. Requires a bit
1118 // of implementation work to make sure we zero out the extra bits.)
1119 Align = static_cast<unsigned>(Width);
1120 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001121 }
1122
Douglas Gregor18857642009-04-30 17:32:17 +00001123 }
Mike Stump1eb44332009-09-09 15:08:12 +00001124
Eli Friedman2be46072011-10-14 20:59:01 +00001125 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001126 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001127}
1128
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001129/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1130CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1131 return CharUnits::fromQuantity(BitSize / getCharWidth());
1132}
1133
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001134/// toBits - Convert a size in characters to a size in characters.
1135int64_t ASTContext::toBits(CharUnits CharSize) const {
1136 return CharSize.getQuantity() * getCharWidth();
1137}
1138
Ken Dyckbdc601b2009-12-22 14:23:30 +00001139/// getTypeSizeInChars - Return the size of the specified type, in characters.
1140/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001141CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001142 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001143}
Jay Foad4ba2a172011-01-12 09:06:06 +00001144CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001145 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001146}
1147
Ken Dyck16e20cc2010-01-26 17:25:18 +00001148/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001149/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001150CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001151 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001152}
Jay Foad4ba2a172011-01-12 09:06:06 +00001153CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001154 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001155}
1156
Chris Lattner34ebde42009-01-27 18:08:34 +00001157/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1158/// type for the current target in bits. This can be different than the ABI
1159/// alignment in cases where it is beneficial for performance to overalign
1160/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001161unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001162 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001163
1164 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001165 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001166 T = CT->getElementType().getTypePtr();
1167 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1168 T->isSpecificBuiltinType(BuiltinType::LongLong))
1169 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1170
Chris Lattner34ebde42009-01-27 18:08:34 +00001171 return ABIAlign;
1172}
1173
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001174/// DeepCollectObjCIvars -
1175/// This routine first collects all declared, but not synthesized, ivars in
1176/// super class and then collects all ivars, including those synthesized for
1177/// current class. This routine is used for implementation of current class
1178/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001179///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001180void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1181 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001182 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001183 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1184 DeepCollectObjCIvars(SuperClass, false, Ivars);
1185 if (!leafClass) {
1186 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1187 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanian11062e12010-02-19 00:31:17 +00001188 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001189 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001190 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001191 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001192 Iv= Iv->getNextIvar())
1193 Ivars.push_back(Iv);
1194 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001195}
1196
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001197/// CollectInheritedProtocols - Collect all protocols in current class and
1198/// those inherited by it.
1199void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001200 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001201 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001202 // We can use protocol_iterator here instead of
1203 // all_referenced_protocol_iterator since we are walking all categories.
1204 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1205 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001206 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001207 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001208 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001209 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001210 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001211 CollectInheritedProtocols(*P, Protocols);
1212 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001213 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001214
1215 // Categories of this Interface.
1216 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1217 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1218 CollectInheritedProtocols(CDeclChain, Protocols);
1219 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1220 while (SD) {
1221 CollectInheritedProtocols(SD, Protocols);
1222 SD = SD->getSuperClass();
1223 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001224 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001225 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001226 PE = OC->protocol_end(); P != PE; ++P) {
1227 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001228 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001229 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1230 PE = Proto->protocol_end(); P != PE; ++P)
1231 CollectInheritedProtocols(*P, Protocols);
1232 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001233 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001234 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1235 PE = OP->protocol_end(); P != PE; ++P) {
1236 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001237 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001238 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1239 PE = Proto->protocol_end(); P != PE; ++P)
1240 CollectInheritedProtocols(*P, Protocols);
1241 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001242 }
1243}
1244
Jay Foad4ba2a172011-01-12 09:06:06 +00001245unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001246 unsigned count = 0;
1247 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001248 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1249 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001250 count += CDecl->ivar_size();
1251
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001252 // Count ivar defined in this class's implementation. This
1253 // includes synthesized ivars.
1254 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001255 count += ImplDecl->ivar_size();
1256
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001257 return count;
1258}
1259
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001260bool ASTContext::isSentinelNullExpr(const Expr *E) {
1261 if (!E)
1262 return false;
1263
1264 // nullptr_t is always treated as null.
1265 if (E->getType()->isNullPtrType()) return true;
1266
1267 if (E->getType()->isAnyPointerType() &&
1268 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1269 Expr::NPC_ValueDependentIsNull))
1270 return true;
1271
1272 // Unfortunately, __null has type 'int'.
1273 if (isa<GNUNullExpr>(E)) return true;
1274
1275 return false;
1276}
1277
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001278/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1279ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1280 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1281 I = ObjCImpls.find(D);
1282 if (I != ObjCImpls.end())
1283 return cast<ObjCImplementationDecl>(I->second);
1284 return 0;
1285}
1286/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1287ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1288 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1289 I = ObjCImpls.find(D);
1290 if (I != ObjCImpls.end())
1291 return cast<ObjCCategoryImplDecl>(I->second);
1292 return 0;
1293}
1294
1295/// \brief Set the implementation of ObjCInterfaceDecl.
1296void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1297 ObjCImplementationDecl *ImplD) {
1298 assert(IFaceD && ImplD && "Passed null params");
1299 ObjCImpls[IFaceD] = ImplD;
1300}
1301/// \brief Set the implementation of ObjCCategoryDecl.
1302void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1303 ObjCCategoryImplDecl *ImplD) {
1304 assert(CatD && ImplD && "Passed null params");
1305 ObjCImpls[CatD] = ImplD;
1306}
1307
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001308ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1309 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1310 return ID;
1311 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1312 return CD->getClassInterface();
1313 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1314 return IMD->getClassInterface();
1315
1316 return 0;
1317}
1318
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001319/// \brief Get the copy initialization expression of VarDecl,or NULL if
1320/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001321Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001322 assert(VD && "Passed null params");
1323 assert(VD->hasAttr<BlocksAttr>() &&
1324 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001325 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001326 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001327 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1328}
1329
1330/// \brief Set the copy inialization expression of a block var decl.
1331void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1332 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001333 assert(VD->hasAttr<BlocksAttr>() &&
1334 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001335 BlockVarCopyInits[VD] = Init;
1336}
1337
John McCalla93c9342009-12-07 02:54:59 +00001338/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001339///
John McCalla93c9342009-12-07 02:54:59 +00001340/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001341/// the TypeLoc wrappers.
1342///
1343/// \param T the type that will be the basis for type source info. This type
1344/// should refer to how the declarator was written in source code, not to
1345/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001346TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001347 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001348 if (!DataSize)
1349 DataSize = TypeLoc::getFullDataSizeForType(T);
1350 else
1351 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001352 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001353
John McCalla93c9342009-12-07 02:54:59 +00001354 TypeSourceInfo *TInfo =
1355 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1356 new (TInfo) TypeSourceInfo(T);
1357 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001358}
1359
John McCalla93c9342009-12-07 02:54:59 +00001360TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001361 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001362 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001363 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001364 return DI;
1365}
1366
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001367const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001368ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001369 return getObjCLayout(D, 0);
1370}
1371
1372const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001373ASTContext::getASTObjCImplementationLayout(
1374 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001375 return getObjCLayout(D->getClassInterface(), D);
1376}
1377
Chris Lattnera7674d82007-07-13 22:13:22 +00001378//===----------------------------------------------------------------------===//
1379// Type creation/memoization methods
1380//===----------------------------------------------------------------------===//
1381
Jay Foad4ba2a172011-01-12 09:06:06 +00001382QualType
John McCall3b657512011-01-19 10:06:00 +00001383ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1384 unsigned fastQuals = quals.getFastQualifiers();
1385 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001386
1387 // Check if we've already instantiated this type.
1388 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001389 ExtQuals::Profile(ID, baseType, quals);
1390 void *insertPos = 0;
1391 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1392 assert(eq->getQualifiers() == quals);
1393 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001394 }
1395
John McCall3b657512011-01-19 10:06:00 +00001396 // If the base type is not canonical, make the appropriate canonical type.
1397 QualType canon;
1398 if (!baseType->isCanonicalUnqualified()) {
1399 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00001400 canonSplit.Quals.addConsistentQualifiers(quals);
1401 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001402
1403 // Re-find the insert position.
1404 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1405 }
1406
1407 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1408 ExtQualNodes.InsertNode(eq, insertPos);
1409 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001410}
1411
Jay Foad4ba2a172011-01-12 09:06:06 +00001412QualType
1413ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001414 QualType CanT = getCanonicalType(T);
1415 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001416 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001417
John McCall0953e762009-09-24 19:53:00 +00001418 // If we are composing extended qualifiers together, merge together
1419 // into one ExtQuals node.
1420 QualifierCollector Quals;
1421 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001422
John McCall0953e762009-09-24 19:53:00 +00001423 // If this type already has an address space specified, it cannot get
1424 // another one.
1425 assert(!Quals.hasAddressSpace() &&
1426 "Type cannot be in multiple addr spaces!");
1427 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001428
John McCall0953e762009-09-24 19:53:00 +00001429 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001430}
1431
Chris Lattnerb7d25532009-02-18 22:53:11 +00001432QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001433 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001434 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001435 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001436 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001437
John McCall7f040a92010-12-24 02:08:15 +00001438 if (const PointerType *ptr = T->getAs<PointerType>()) {
1439 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001440 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001441 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1442 return getPointerType(ResultType);
1443 }
1444 }
Mike Stump1eb44332009-09-09 15:08:12 +00001445
John McCall0953e762009-09-24 19:53:00 +00001446 // If we are composing extended qualifiers together, merge together
1447 // into one ExtQuals node.
1448 QualifierCollector Quals;
1449 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001450
John McCall0953e762009-09-24 19:53:00 +00001451 // If this type already has an ObjCGC specified, it cannot get
1452 // another one.
1453 assert(!Quals.hasObjCGCAttr() &&
1454 "Type cannot have multiple ObjCGCs!");
1455 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001456
John McCall0953e762009-09-24 19:53:00 +00001457 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001458}
Chris Lattnera7674d82007-07-13 22:13:22 +00001459
John McCalle6a365d2010-12-19 02:44:49 +00001460const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1461 FunctionType::ExtInfo Info) {
1462 if (T->getExtInfo() == Info)
1463 return T;
1464
1465 QualType Result;
1466 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1467 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1468 } else {
1469 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1470 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1471 EPI.ExtInfo = Info;
1472 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1473 FPT->getNumArgs(), EPI);
1474 }
1475
1476 return cast<FunctionType>(Result.getTypePtr());
1477}
1478
Reid Spencer5f016e22007-07-11 17:01:13 +00001479/// getComplexType - Return the uniqued reference to the type for a complex
1480/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001481QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001482 // Unique pointers, to guarantee there is only one pointer of a particular
1483 // structure.
1484 llvm::FoldingSetNodeID ID;
1485 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001486
Reid Spencer5f016e22007-07-11 17:01:13 +00001487 void *InsertPos = 0;
1488 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1489 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001490
Reid Spencer5f016e22007-07-11 17:01:13 +00001491 // If the pointee type isn't canonical, this won't be a canonical type either,
1492 // so fill in the canonical type field.
1493 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001494 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001495 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001496
Reid Spencer5f016e22007-07-11 17:01:13 +00001497 // Get the new insert position for the node we care about.
1498 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001499 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001500 }
John McCall6b304a02009-09-24 23:30:46 +00001501 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001502 Types.push_back(New);
1503 ComplexTypes.InsertNode(New, InsertPos);
1504 return QualType(New, 0);
1505}
1506
Reid Spencer5f016e22007-07-11 17:01:13 +00001507/// getPointerType - Return the uniqued reference to the type for a pointer to
1508/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001509QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001510 // Unique pointers, to guarantee there is only one pointer of a particular
1511 // structure.
1512 llvm::FoldingSetNodeID ID;
1513 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001514
Reid Spencer5f016e22007-07-11 17:01:13 +00001515 void *InsertPos = 0;
1516 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1517 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001518
Reid Spencer5f016e22007-07-11 17:01:13 +00001519 // If the pointee type isn't canonical, this won't be a canonical type either,
1520 // so fill in the canonical type field.
1521 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001522 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001523 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001524
Reid Spencer5f016e22007-07-11 17:01:13 +00001525 // Get the new insert position for the node we care about.
1526 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001527 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001528 }
John McCall6b304a02009-09-24 23:30:46 +00001529 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001530 Types.push_back(New);
1531 PointerTypes.InsertNode(New, InsertPos);
1532 return QualType(New, 0);
1533}
1534
Mike Stump1eb44332009-09-09 15:08:12 +00001535/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001536/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001537QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001538 assert(T->isFunctionType() && "block of function types only");
1539 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001540 // structure.
1541 llvm::FoldingSetNodeID ID;
1542 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001543
Steve Naroff5618bd42008-08-27 16:04:49 +00001544 void *InsertPos = 0;
1545 if (BlockPointerType *PT =
1546 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1547 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001548
1549 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001550 // type either so fill in the canonical type field.
1551 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001552 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001553 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001554
Steve Naroff5618bd42008-08-27 16:04:49 +00001555 // Get the new insert position for the node we care about.
1556 BlockPointerType *NewIP =
1557 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001558 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001559 }
John McCall6b304a02009-09-24 23:30:46 +00001560 BlockPointerType *New
1561 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001562 Types.push_back(New);
1563 BlockPointerTypes.InsertNode(New, InsertPos);
1564 return QualType(New, 0);
1565}
1566
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001567/// getLValueReferenceType - Return the uniqued reference to the type for an
1568/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001569QualType
1570ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00001571 assert(getCanonicalType(T) != OverloadTy &&
1572 "Unresolved overloaded function type");
1573
Reid Spencer5f016e22007-07-11 17:01:13 +00001574 // Unique pointers, to guarantee there is only one pointer of a particular
1575 // structure.
1576 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001577 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001578
1579 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001580 if (LValueReferenceType *RT =
1581 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001583
John McCall54e14c42009-10-22 22:37:11 +00001584 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1585
Reid Spencer5f016e22007-07-11 17:01:13 +00001586 // If the referencee type isn't canonical, this won't be a canonical type
1587 // either, so fill in the canonical type field.
1588 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001589 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1590 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1591 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001592
Reid Spencer5f016e22007-07-11 17:01:13 +00001593 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001594 LValueReferenceType *NewIP =
1595 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001596 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001597 }
1598
John McCall6b304a02009-09-24 23:30:46 +00001599 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001600 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1601 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001602 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001603 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001604
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001605 return QualType(New, 0);
1606}
1607
1608/// getRValueReferenceType - Return the uniqued reference to the type for an
1609/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001610QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001611 // Unique pointers, to guarantee there is only one pointer of a particular
1612 // structure.
1613 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001614 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001615
1616 void *InsertPos = 0;
1617 if (RValueReferenceType *RT =
1618 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1619 return QualType(RT, 0);
1620
John McCall54e14c42009-10-22 22:37:11 +00001621 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1622
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001623 // If the referencee type isn't canonical, this won't be a canonical type
1624 // either, so fill in the canonical type field.
1625 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001626 if (InnerRef || !T.isCanonical()) {
1627 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1628 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001629
1630 // Get the new insert position for the node we care about.
1631 RValueReferenceType *NewIP =
1632 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001633 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001634 }
1635
John McCall6b304a02009-09-24 23:30:46 +00001636 RValueReferenceType *New
1637 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001638 Types.push_back(New);
1639 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001640 return QualType(New, 0);
1641}
1642
Sebastian Redlf30208a2009-01-24 21:16:55 +00001643/// getMemberPointerType - Return the uniqued reference to the type for a
1644/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00001645QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001646 // Unique pointers, to guarantee there is only one pointer of a particular
1647 // structure.
1648 llvm::FoldingSetNodeID ID;
1649 MemberPointerType::Profile(ID, T, Cls);
1650
1651 void *InsertPos = 0;
1652 if (MemberPointerType *PT =
1653 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1654 return QualType(PT, 0);
1655
1656 // If the pointee or class type isn't canonical, this won't be a canonical
1657 // type either, so fill in the canonical type field.
1658 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001659 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001660 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1661
1662 // Get the new insert position for the node we care about.
1663 MemberPointerType *NewIP =
1664 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001665 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001666 }
John McCall6b304a02009-09-24 23:30:46 +00001667 MemberPointerType *New
1668 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001669 Types.push_back(New);
1670 MemberPointerTypes.InsertNode(New, InsertPos);
1671 return QualType(New, 0);
1672}
1673
Mike Stump1eb44332009-09-09 15:08:12 +00001674/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001675/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001676QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001677 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001678 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001679 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001680 assert((EltTy->isDependentType() ||
1681 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001682 "Constant array of VLAs is illegal!");
1683
Chris Lattner38aeec72009-05-13 04:12:56 +00001684 // Convert the array size into a canonical width matching the pointer size for
1685 // the target.
1686 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001687 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001688 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00001689
Reid Spencer5f016e22007-07-11 17:01:13 +00001690 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001691 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001692
Reid Spencer5f016e22007-07-11 17:01:13 +00001693 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001694 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001695 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001696 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001697
John McCall3b657512011-01-19 10:06:00 +00001698 // If the element type isn't canonical or has qualifiers, this won't
1699 // be a canonical type either, so fill in the canonical type field.
1700 QualType Canon;
1701 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1702 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00001703 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001704 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00001705 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001706
Reid Spencer5f016e22007-07-11 17:01:13 +00001707 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001708 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001709 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001710 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001711 }
Mike Stump1eb44332009-09-09 15:08:12 +00001712
John McCall6b304a02009-09-24 23:30:46 +00001713 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001714 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001715 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001716 Types.push_back(New);
1717 return QualType(New, 0);
1718}
1719
John McCallce889032011-01-18 08:40:38 +00001720/// getVariableArrayDecayedType - Turns the given type, which may be
1721/// variably-modified, into the corresponding type with all the known
1722/// sizes replaced with [*].
1723QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1724 // Vastly most common case.
1725 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001726
John McCallce889032011-01-18 08:40:38 +00001727 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001728
John McCallce889032011-01-18 08:40:38 +00001729 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00001730 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00001731 switch (ty->getTypeClass()) {
1732#define TYPE(Class, Base)
1733#define ABSTRACT_TYPE(Class, Base)
1734#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1735#include "clang/AST/TypeNodes.def"
1736 llvm_unreachable("didn't desugar past all non-canonical types?");
1737
1738 // These types should never be variably-modified.
1739 case Type::Builtin:
1740 case Type::Complex:
1741 case Type::Vector:
1742 case Type::ExtVector:
1743 case Type::DependentSizedExtVector:
1744 case Type::ObjCObject:
1745 case Type::ObjCInterface:
1746 case Type::ObjCObjectPointer:
1747 case Type::Record:
1748 case Type::Enum:
1749 case Type::UnresolvedUsing:
1750 case Type::TypeOfExpr:
1751 case Type::TypeOf:
1752 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00001753 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00001754 case Type::DependentName:
1755 case Type::InjectedClassName:
1756 case Type::TemplateSpecialization:
1757 case Type::DependentTemplateSpecialization:
1758 case Type::TemplateTypeParm:
1759 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00001760 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00001761 case Type::PackExpansion:
1762 llvm_unreachable("type should never be variably-modified");
1763
1764 // These types can be variably-modified but should never need to
1765 // further decay.
1766 case Type::FunctionNoProto:
1767 case Type::FunctionProto:
1768 case Type::BlockPointer:
1769 case Type::MemberPointer:
1770 return type;
1771
1772 // These types can be variably-modified. All these modifications
1773 // preserve structure except as noted by comments.
1774 // TODO: if we ever care about optimizing VLAs, there are no-op
1775 // optimizations available here.
1776 case Type::Pointer:
1777 result = getPointerType(getVariableArrayDecayedType(
1778 cast<PointerType>(ty)->getPointeeType()));
1779 break;
1780
1781 case Type::LValueReference: {
1782 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1783 result = getLValueReferenceType(
1784 getVariableArrayDecayedType(lv->getPointeeType()),
1785 lv->isSpelledAsLValue());
1786 break;
1787 }
1788
1789 case Type::RValueReference: {
1790 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1791 result = getRValueReferenceType(
1792 getVariableArrayDecayedType(lv->getPointeeType()));
1793 break;
1794 }
1795
Eli Friedmanb001de72011-10-06 23:00:33 +00001796 case Type::Atomic: {
1797 const AtomicType *at = cast<AtomicType>(ty);
1798 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1799 break;
1800 }
1801
John McCallce889032011-01-18 08:40:38 +00001802 case Type::ConstantArray: {
1803 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1804 result = getConstantArrayType(
1805 getVariableArrayDecayedType(cat->getElementType()),
1806 cat->getSize(),
1807 cat->getSizeModifier(),
1808 cat->getIndexTypeCVRQualifiers());
1809 break;
1810 }
1811
1812 case Type::DependentSizedArray: {
1813 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1814 result = getDependentSizedArrayType(
1815 getVariableArrayDecayedType(dat->getElementType()),
1816 dat->getSizeExpr(),
1817 dat->getSizeModifier(),
1818 dat->getIndexTypeCVRQualifiers(),
1819 dat->getBracketsRange());
1820 break;
1821 }
1822
1823 // Turn incomplete types into [*] types.
1824 case Type::IncompleteArray: {
1825 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1826 result = getVariableArrayType(
1827 getVariableArrayDecayedType(iat->getElementType()),
1828 /*size*/ 0,
1829 ArrayType::Normal,
1830 iat->getIndexTypeCVRQualifiers(),
1831 SourceRange());
1832 break;
1833 }
1834
1835 // Turn VLA types into [*] types.
1836 case Type::VariableArray: {
1837 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1838 result = getVariableArrayType(
1839 getVariableArrayDecayedType(vat->getElementType()),
1840 /*size*/ 0,
1841 ArrayType::Star,
1842 vat->getIndexTypeCVRQualifiers(),
1843 vat->getBracketsRange());
1844 break;
1845 }
1846 }
1847
1848 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00001849 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00001850}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001851
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001852/// getVariableArrayType - Returns a non-unique reference to the type for a
1853/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001854QualType ASTContext::getVariableArrayType(QualType EltTy,
1855 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001856 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001857 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00001858 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001859 // Since we don't unique expressions, it isn't possible to unique VLA's
1860 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00001861 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00001862
John McCall3b657512011-01-19 10:06:00 +00001863 // Be sure to pull qualifiers off the element type.
1864 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1865 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00001866 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001867 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00001868 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00001869 }
1870
John McCall6b304a02009-09-24 23:30:46 +00001871 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001872 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001873
1874 VariableArrayTypes.push_back(New);
1875 Types.push_back(New);
1876 return QualType(New, 0);
1877}
1878
Douglas Gregor898574e2008-12-05 23:32:09 +00001879/// getDependentSizedArrayType - Returns a non-unique reference to
1880/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001881/// type.
John McCall3b657512011-01-19 10:06:00 +00001882QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1883 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00001884 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001885 unsigned elementTypeQuals,
1886 SourceRange brackets) const {
1887 assert((!numElements || numElements->isTypeDependent() ||
1888 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001889 "Size must be type- or value-dependent!");
1890
John McCall3b657512011-01-19 10:06:00 +00001891 // Dependently-sized array types that do not have a specified number
1892 // of elements will have their sizes deduced from a dependent
1893 // initializer. We do no canonicalization here at all, which is okay
1894 // because they can't be used in most locations.
1895 if (!numElements) {
1896 DependentSizedArrayType *newType
1897 = new (*this, TypeAlignment)
1898 DependentSizedArrayType(*this, elementType, QualType(),
1899 numElements, ASM, elementTypeQuals,
1900 brackets);
1901 Types.push_back(newType);
1902 return QualType(newType, 0);
1903 }
1904
1905 // Otherwise, we actually build a new type every time, but we
1906 // also build a canonical type.
1907
1908 SplitQualType canonElementType = getCanonicalType(elementType).split();
1909
1910 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001911 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001912 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00001913 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00001914 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001915
John McCall3b657512011-01-19 10:06:00 +00001916 // Look for an existing type with these properties.
1917 DependentSizedArrayType *canonTy =
1918 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001919
John McCall3b657512011-01-19 10:06:00 +00001920 // If we don't have one, build one.
1921 if (!canonTy) {
1922 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00001923 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00001924 QualType(), numElements, ASM, elementTypeQuals,
1925 brackets);
1926 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1927 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001928 }
1929
John McCall3b657512011-01-19 10:06:00 +00001930 // Apply qualifiers from the element type to the array.
1931 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00001932 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00001933
John McCall3b657512011-01-19 10:06:00 +00001934 // If we didn't need extra canonicalization for the element type,
1935 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00001936 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00001937 return canon;
1938
1939 // Otherwise, we need to build a type which follows the spelling
1940 // of the element type.
1941 DependentSizedArrayType *sugaredType
1942 = new (*this, TypeAlignment)
1943 DependentSizedArrayType(*this, elementType, canon, numElements,
1944 ASM, elementTypeQuals, brackets);
1945 Types.push_back(sugaredType);
1946 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00001947}
1948
John McCall3b657512011-01-19 10:06:00 +00001949QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00001950 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001951 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001952 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001953 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001954
John McCall3b657512011-01-19 10:06:00 +00001955 void *insertPos = 0;
1956 if (IncompleteArrayType *iat =
1957 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1958 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001959
1960 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00001961 // either, so fill in the canonical type field. We also have to pull
1962 // qualifiers off the element type.
1963 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00001964
John McCall3b657512011-01-19 10:06:00 +00001965 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1966 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00001967 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00001968 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00001969 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001970
1971 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00001972 IncompleteArrayType *existing =
1973 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1974 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001975 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001976
John McCall3b657512011-01-19 10:06:00 +00001977 IncompleteArrayType *newType = new (*this, TypeAlignment)
1978 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001979
John McCall3b657512011-01-19 10:06:00 +00001980 IncompleteArrayTypes.InsertNode(newType, insertPos);
1981 Types.push_back(newType);
1982 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001983}
1984
Steve Naroff73322922007-07-18 18:00:27 +00001985/// getVectorType - Return the unique reference to a vector type of
1986/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001987QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00001988 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00001989 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001990
Reid Spencer5f016e22007-07-11 17:01:13 +00001991 // Check if we've already instantiated a vector of this type.
1992 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00001993 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00001994
Reid Spencer5f016e22007-07-11 17:01:13 +00001995 void *InsertPos = 0;
1996 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1997 return QualType(VTP, 0);
1998
1999 // If the element type isn't canonical, this won't be a canonical type either,
2000 // so fill in the canonical type field.
2001 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002002 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002003 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002004
Reid Spencer5f016e22007-07-11 17:01:13 +00002005 // Get the new insert position for the node we care about.
2006 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002007 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002008 }
John McCall6b304a02009-09-24 23:30:46 +00002009 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002010 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002011 VectorTypes.InsertNode(New, InsertPos);
2012 Types.push_back(New);
2013 return QualType(New, 0);
2014}
2015
Nate Begeman213541a2008-04-18 23:10:10 +00002016/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002017/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002018QualType
2019ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002020 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002021
Steve Naroff73322922007-07-18 18:00:27 +00002022 // Check if we've already instantiated a vector of this type.
2023 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002024 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002025 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002026 void *InsertPos = 0;
2027 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2028 return QualType(VTP, 0);
2029
2030 // If the element type isn't canonical, this won't be a canonical type either,
2031 // so fill in the canonical type field.
2032 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002033 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002034 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002035
Steve Naroff73322922007-07-18 18:00:27 +00002036 // Get the new insert position for the node we care about.
2037 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002038 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002039 }
John McCall6b304a02009-09-24 23:30:46 +00002040 ExtVectorType *New = new (*this, TypeAlignment)
2041 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002042 VectorTypes.InsertNode(New, InsertPos);
2043 Types.push_back(New);
2044 return QualType(New, 0);
2045}
2046
Jay Foad4ba2a172011-01-12 09:06:06 +00002047QualType
2048ASTContext::getDependentSizedExtVectorType(QualType vecType,
2049 Expr *SizeExpr,
2050 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002051 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002052 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002053 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002054
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002055 void *InsertPos = 0;
2056 DependentSizedExtVectorType *Canon
2057 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2058 DependentSizedExtVectorType *New;
2059 if (Canon) {
2060 // We already have a canonical version of this array type; use it as
2061 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002062 New = new (*this, TypeAlignment)
2063 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2064 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002065 } else {
2066 QualType CanonVecTy = getCanonicalType(vecType);
2067 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002068 New = new (*this, TypeAlignment)
2069 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2070 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002071
2072 DependentSizedExtVectorType *CanonCheck
2073 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2074 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2075 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002076 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2077 } else {
2078 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2079 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002080 New = new (*this, TypeAlignment)
2081 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002082 }
2083 }
Mike Stump1eb44332009-09-09 15:08:12 +00002084
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002085 Types.push_back(New);
2086 return QualType(New, 0);
2087}
2088
Douglas Gregor72564e72009-02-26 23:50:07 +00002089/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002090///
Jay Foad4ba2a172011-01-12 09:06:06 +00002091QualType
2092ASTContext::getFunctionNoProtoType(QualType ResultTy,
2093 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002094 const CallingConv DefaultCC = Info.getCC();
2095 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2096 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002097 // Unique functions, to guarantee there is only one function of a particular
2098 // structure.
2099 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002100 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002101
Reid Spencer5f016e22007-07-11 17:01:13 +00002102 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002103 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002104 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002105 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002106
Reid Spencer5f016e22007-07-11 17:01:13 +00002107 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002108 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002109 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002110 Canonical =
2111 getFunctionNoProtoType(getCanonicalType(ResultTy),
2112 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002113
Reid Spencer5f016e22007-07-11 17:01:13 +00002114 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002115 FunctionNoProtoType *NewIP =
2116 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002117 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002118 }
Mike Stump1eb44332009-09-09 15:08:12 +00002119
Roman Divackycfe9af22011-03-01 17:40:53 +00002120 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002121 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002122 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002123 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002124 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002125 return QualType(New, 0);
2126}
2127
2128/// getFunctionType - Return a normal function type with a typed argument
2129/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002130QualType
2131ASTContext::getFunctionType(QualType ResultTy,
2132 const QualType *ArgArray, unsigned NumArgs,
2133 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002134 // Unique functions, to guarantee there is only one function of a particular
2135 // structure.
2136 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002137 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002138
2139 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002140 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002141 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002142 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002143
2144 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002145 bool isCanonical =
2146 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2147 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002148 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002149 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002150 isCanonical = false;
2151
Roman Divackycfe9af22011-03-01 17:40:53 +00002152 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2153 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2154 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002155
Reid Spencer5f016e22007-07-11 17:01:13 +00002156 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002157 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002158 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002159 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002160 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002161 CanonicalArgs.reserve(NumArgs);
2162 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002163 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002164
John McCalle23cf432010-12-14 08:05:40 +00002165 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002166 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002167 CanonicalEPI.ExceptionSpecType = EST_None;
2168 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002169 CanonicalEPI.ExtInfo
2170 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2171
Chris Lattnerf52ab252008-04-06 22:59:24 +00002172 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00002173 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002174 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002175
Reid Spencer5f016e22007-07-11 17:01:13 +00002176 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002177 FunctionProtoType *NewIP =
2178 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002179 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002180 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002181
John McCallf85e1932011-06-15 23:02:42 +00002182 // FunctionProtoType objects are allocated with extra bytes after
2183 // them for three variable size arrays at the end:
2184 // - parameter types
2185 // - exception types
2186 // - consumed-arguments flags
2187 // Instead of the exception types, there could be a noexcept
2188 // expression.
John McCalle23cf432010-12-14 08:05:40 +00002189 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002190 NumArgs * sizeof(QualType);
2191 if (EPI.ExceptionSpecType == EST_Dynamic)
2192 Size += EPI.NumExceptions * sizeof(QualType);
2193 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002194 Size += sizeof(Expr*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002195 }
John McCallf85e1932011-06-15 23:02:42 +00002196 if (EPI.ConsumedArguments)
2197 Size += NumArgs * sizeof(bool);
2198
John McCalle23cf432010-12-14 08:05:40 +00002199 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002200 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2201 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002202 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002203 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002204 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002205 return QualType(FTP, 0);
2206}
2207
John McCall3cb0ebd2010-03-10 03:28:59 +00002208#ifndef NDEBUG
2209static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2210 if (!isa<CXXRecordDecl>(D)) return false;
2211 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2212 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2213 return true;
2214 if (RD->getDescribedClassTemplate() &&
2215 !isa<ClassTemplateSpecializationDecl>(RD))
2216 return true;
2217 return false;
2218}
2219#endif
2220
2221/// getInjectedClassNameType - Return the unique reference to the
2222/// injected class name type for the specified templated declaration.
2223QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002224 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002225 assert(NeedsInjectedClassNameType(Decl));
2226 if (Decl->TypeForDecl) {
2227 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002228 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002229 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2230 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2231 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2232 } else {
John McCallf4c73712011-01-19 06:33:43 +00002233 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002234 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002235 Decl->TypeForDecl = newType;
2236 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002237 }
2238 return QualType(Decl->TypeForDecl, 0);
2239}
2240
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002241/// getTypeDeclType - Return the unique reference to the type for the
2242/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002243QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002244 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002245 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002246
Richard Smith162e1c12011-04-15 14:24:37 +00002247 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002248 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002249
John McCallbecb8d52010-03-10 06:48:02 +00002250 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2251 "Template type parameter types are always available.");
2252
John McCall19c85762010-02-16 03:57:14 +00002253 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002254 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002255 "struct/union has previous declaration");
2256 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002257 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002258 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002259 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002260 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002261 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002262 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002263 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002264 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2265 Decl->TypeForDecl = newType;
2266 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002267 } else
John McCallbecb8d52010-03-10 06:48:02 +00002268 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002269
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002270 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002271}
2272
Reid Spencer5f016e22007-07-11 17:01:13 +00002273/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002274/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002275QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002276ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2277 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002278 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002279
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002280 if (Canonical.isNull())
2281 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002282 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002283 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002284 Decl->TypeForDecl = newType;
2285 Types.push_back(newType);
2286 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002287}
2288
Jay Foad4ba2a172011-01-12 09:06:06 +00002289QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002290 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2291
Douglas Gregoref96ee02012-01-14 16:38:05 +00002292 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002293 if (PrevDecl->TypeForDecl)
2294 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2295
John McCallf4c73712011-01-19 06:33:43 +00002296 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2297 Decl->TypeForDecl = newType;
2298 Types.push_back(newType);
2299 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002300}
2301
Jay Foad4ba2a172011-01-12 09:06:06 +00002302QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002303 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2304
Douglas Gregoref96ee02012-01-14 16:38:05 +00002305 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002306 if (PrevDecl->TypeForDecl)
2307 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2308
John McCallf4c73712011-01-19 06:33:43 +00002309 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2310 Decl->TypeForDecl = newType;
2311 Types.push_back(newType);
2312 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002313}
2314
John McCall9d156a72011-01-06 01:58:22 +00002315QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2316 QualType modifiedType,
2317 QualType equivalentType) {
2318 llvm::FoldingSetNodeID id;
2319 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2320
2321 void *insertPos = 0;
2322 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2323 if (type) return QualType(type, 0);
2324
2325 QualType canon = getCanonicalType(equivalentType);
2326 type = new (*this, TypeAlignment)
2327 AttributedType(canon, attrKind, modifiedType, equivalentType);
2328
2329 Types.push_back(type);
2330 AttributedTypes.InsertNode(type, insertPos);
2331
2332 return QualType(type, 0);
2333}
2334
2335
John McCall49a832b2009-10-18 09:09:24 +00002336/// \brief Retrieve a substitution-result type.
2337QualType
2338ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002339 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002340 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002341 && "replacement types must always be canonical");
2342
2343 llvm::FoldingSetNodeID ID;
2344 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2345 void *InsertPos = 0;
2346 SubstTemplateTypeParmType *SubstParm
2347 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2348
2349 if (!SubstParm) {
2350 SubstParm = new (*this, TypeAlignment)
2351 SubstTemplateTypeParmType(Parm, Replacement);
2352 Types.push_back(SubstParm);
2353 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2354 }
2355
2356 return QualType(SubstParm, 0);
2357}
2358
Douglas Gregorc3069d62011-01-14 02:55:32 +00002359/// \brief Retrieve a
2360QualType ASTContext::getSubstTemplateTypeParmPackType(
2361 const TemplateTypeParmType *Parm,
2362 const TemplateArgument &ArgPack) {
2363#ifndef NDEBUG
2364 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2365 PEnd = ArgPack.pack_end();
2366 P != PEnd; ++P) {
2367 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2368 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2369 }
2370#endif
2371
2372 llvm::FoldingSetNodeID ID;
2373 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2374 void *InsertPos = 0;
2375 if (SubstTemplateTypeParmPackType *SubstParm
2376 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2377 return QualType(SubstParm, 0);
2378
2379 QualType Canon;
2380 if (!Parm->isCanonicalUnqualified()) {
2381 Canon = getCanonicalType(QualType(Parm, 0));
2382 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2383 ArgPack);
2384 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2385 }
2386
2387 SubstTemplateTypeParmPackType *SubstParm
2388 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2389 ArgPack);
2390 Types.push_back(SubstParm);
2391 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2392 return QualType(SubstParm, 0);
2393}
2394
Douglas Gregorfab9d672009-02-05 23:33:38 +00002395/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002396/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002397/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002398QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002399 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002400 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002401 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002402 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002403 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002404 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002405 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2406
2407 if (TypeParm)
2408 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002409
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002410 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002411 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002412 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002413
2414 TemplateTypeParmType *TypeCheck
2415 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2416 assert(!TypeCheck && "Template type parameter canonical type broken");
2417 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002418 } else
John McCall6b304a02009-09-24 23:30:46 +00002419 TypeParm = new (*this, TypeAlignment)
2420 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002421
2422 Types.push_back(TypeParm);
2423 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2424
2425 return QualType(TypeParm, 0);
2426}
2427
John McCall3cb0ebd2010-03-10 03:28:59 +00002428TypeSourceInfo *
2429ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2430 SourceLocation NameLoc,
2431 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002432 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002433 assert(!Name.getAsDependentTemplateName() &&
2434 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002435 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002436
2437 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2438 TemplateSpecializationTypeLoc TL
2439 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002440 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00002441 TL.setTemplateNameLoc(NameLoc);
2442 TL.setLAngleLoc(Args.getLAngleLoc());
2443 TL.setRAngleLoc(Args.getRAngleLoc());
2444 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2445 TL.setArgLocInfo(i, Args[i].getLocInfo());
2446 return DI;
2447}
2448
Mike Stump1eb44332009-09-09 15:08:12 +00002449QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002450ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002451 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002452 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002453 assert(!Template.getAsDependentTemplateName() &&
2454 "No dependent template names here!");
2455
John McCalld5532b62009-11-23 01:53:49 +00002456 unsigned NumArgs = Args.size();
2457
Chris Lattner5f9e2722011-07-23 10:55:15 +00002458 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002459 ArgVec.reserve(NumArgs);
2460 for (unsigned i = 0; i != NumArgs; ++i)
2461 ArgVec.push_back(Args[i].getArgument());
2462
John McCall31f17ec2010-04-27 00:57:59 +00002463 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002464 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002465}
2466
Douglas Gregorb70126a2012-02-03 17:16:23 +00002467#ifndef NDEBUG
2468static bool hasAnyPackExpansions(const TemplateArgument *Args,
2469 unsigned NumArgs) {
2470 for (unsigned I = 0; I != NumArgs; ++I)
2471 if (Args[I].isPackExpansion())
2472 return true;
2473
2474 return true;
2475}
2476#endif
2477
John McCall833ca992009-10-29 08:12:44 +00002478QualType
2479ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002480 const TemplateArgument *Args,
2481 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002482 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002483 assert(!Template.getAsDependentTemplateName() &&
2484 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002485 // Look through qualified template names.
2486 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2487 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002488
Douglas Gregorb70126a2012-02-03 17:16:23 +00002489 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00002490 Template.getAsTemplateDecl() &&
2491 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00002492 QualType CanonType;
2493 if (!Underlying.isNull())
2494 CanonType = getCanonicalType(Underlying);
2495 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00002496 // We can get here with an alias template when the specialization contains
2497 // a pack expansion that does not match up with a parameter pack.
2498 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2499 "Caller must compute aliased type");
2500 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00002501 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2502 NumArgs);
2503 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002504
Douglas Gregor1275ae02009-07-28 23:00:59 +00002505 // Allocate the (non-canonical) template specialization type, but don't
2506 // try to unique it: these types typically have location information that
2507 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002508 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2509 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00002510 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00002511 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002512 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00002513 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2514 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00002515
Douglas Gregor55f6b142009-02-09 18:46:07 +00002516 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002517 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002518}
2519
Mike Stump1eb44332009-09-09 15:08:12 +00002520QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002521ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2522 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002523 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002524 assert(!Template.getAsDependentTemplateName() &&
2525 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002526
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002527 // Look through qualified template names.
2528 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2529 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002530
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002531 // Build the canonical template specialization type.
2532 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002533 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002534 CanonArgs.reserve(NumArgs);
2535 for (unsigned I = 0; I != NumArgs; ++I)
2536 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2537
2538 // Determine whether this canonical template specialization type already
2539 // exists.
2540 llvm::FoldingSetNodeID ID;
2541 TemplateSpecializationType::Profile(ID, CanonTemplate,
2542 CanonArgs.data(), NumArgs, *this);
2543
2544 void *InsertPos = 0;
2545 TemplateSpecializationType *Spec
2546 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2547
2548 if (!Spec) {
2549 // Allocate a new canonical template specialization type.
2550 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2551 sizeof(TemplateArgument) * NumArgs),
2552 TypeAlignment);
2553 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2554 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002555 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002556 Types.push_back(Spec);
2557 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2558 }
2559
2560 assert(Spec->isDependentType() &&
2561 "Non-dependent template-id type must have a canonical type");
2562 return QualType(Spec, 0);
2563}
2564
2565QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002566ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2567 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002568 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002569 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002570 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002571
2572 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002573 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002574 if (T)
2575 return QualType(T, 0);
2576
Douglas Gregor789b1f62010-02-04 18:10:26 +00002577 QualType Canon = NamedType;
2578 if (!Canon.isCanonical()) {
2579 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002580 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2581 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002582 (void)CheckT;
2583 }
2584
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002585 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002586 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002587 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002588 return QualType(T, 0);
2589}
2590
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002591QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002592ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002593 llvm::FoldingSetNodeID ID;
2594 ParenType::Profile(ID, InnerType);
2595
2596 void *InsertPos = 0;
2597 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2598 if (T)
2599 return QualType(T, 0);
2600
2601 QualType Canon = InnerType;
2602 if (!Canon.isCanonical()) {
2603 Canon = getCanonicalType(InnerType);
2604 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2605 assert(!CheckT && "Paren canonical type broken");
2606 (void)CheckT;
2607 }
2608
2609 T = new (*this) ParenType(InnerType, Canon);
2610 Types.push_back(T);
2611 ParenTypes.InsertNode(T, InsertPos);
2612 return QualType(T, 0);
2613}
2614
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002615QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2616 NestedNameSpecifier *NNS,
2617 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002618 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002619 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2620
2621 if (Canon.isNull()) {
2622 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002623 ElaboratedTypeKeyword CanonKeyword = Keyword;
2624 if (Keyword == ETK_None)
2625 CanonKeyword = ETK_Typename;
2626
2627 if (CanonNNS != NNS || CanonKeyword != Keyword)
2628 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002629 }
2630
2631 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002632 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002633
2634 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002635 DependentNameType *T
2636 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002637 if (T)
2638 return QualType(T, 0);
2639
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002640 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002641 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002642 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002643 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002644}
2645
Mike Stump1eb44332009-09-09 15:08:12 +00002646QualType
John McCall33500952010-06-11 00:33:02 +00002647ASTContext::getDependentTemplateSpecializationType(
2648 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002649 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002650 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002651 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00002652 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00002653 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00002654 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2655 ArgCopy.push_back(Args[I].getArgument());
2656 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2657 ArgCopy.size(),
2658 ArgCopy.data());
2659}
2660
2661QualType
2662ASTContext::getDependentTemplateSpecializationType(
2663 ElaboratedTypeKeyword Keyword,
2664 NestedNameSpecifier *NNS,
2665 const IdentifierInfo *Name,
2666 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002667 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00002668 assert((!NNS || NNS->isDependent()) &&
2669 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00002670
Douglas Gregor789b1f62010-02-04 18:10:26 +00002671 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002672 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2673 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002674
2675 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002676 DependentTemplateSpecializationType *T
2677 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002678 if (T)
2679 return QualType(T, 0);
2680
John McCall33500952010-06-11 00:33:02 +00002681 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002682
John McCall33500952010-06-11 00:33:02 +00002683 ElaboratedTypeKeyword CanonKeyword = Keyword;
2684 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2685
2686 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002687 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00002688 for (unsigned I = 0; I != NumArgs; ++I) {
2689 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2690 if (!CanonArgs[I].structurallyEquals(Args[I]))
2691 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002692 }
2693
John McCall33500952010-06-11 00:33:02 +00002694 QualType Canon;
2695 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2696 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2697 Name, NumArgs,
2698 CanonArgs.data());
2699
2700 // Find the insert position again.
2701 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2702 }
2703
2704 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2705 sizeof(TemplateArgument) * NumArgs),
2706 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002707 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002708 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002709 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002710 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002711 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002712}
2713
Douglas Gregorcded4f62011-01-14 17:04:44 +00002714QualType ASTContext::getPackExpansionType(QualType Pattern,
2715 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00002716 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002717 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002718
2719 assert(Pattern->containsUnexpandedParameterPack() &&
2720 "Pack expansions must expand one or more parameter packs");
2721 void *InsertPos = 0;
2722 PackExpansionType *T
2723 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2724 if (T)
2725 return QualType(T, 0);
2726
2727 QualType Canon;
2728 if (!Pattern.isCanonical()) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002729 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002730
2731 // Find the insert position again.
2732 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2733 }
2734
Douglas Gregorcded4f62011-01-14 17:04:44 +00002735 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002736 Types.push_back(T);
2737 PackExpansionTypes.InsertNode(T, InsertPos);
2738 return QualType(T, 0);
2739}
2740
Chris Lattner88cb27a2008-04-07 04:56:42 +00002741/// CmpProtocolNames - Comparison predicate for sorting protocols
2742/// alphabetically.
2743static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2744 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002745 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002746}
2747
John McCallc12c5bb2010-05-15 11:32:37 +00002748static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002749 unsigned NumProtocols) {
2750 if (NumProtocols == 0) return true;
2751
Douglas Gregor61cc2962012-01-02 02:00:30 +00002752 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2753 return false;
2754
John McCall54e14c42009-10-22 22:37:11 +00002755 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00002756 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2757 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00002758 return false;
2759 return true;
2760}
2761
2762static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002763 unsigned &NumProtocols) {
2764 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002765
Chris Lattner88cb27a2008-04-07 04:56:42 +00002766 // Sort protocols, keyed by name.
2767 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2768
Douglas Gregor61cc2962012-01-02 02:00:30 +00002769 // Canonicalize.
2770 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2771 Protocols[I] = Protocols[I]->getCanonicalDecl();
2772
Chris Lattner88cb27a2008-04-07 04:56:42 +00002773 // Remove duplicates.
2774 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2775 NumProtocols = ProtocolsEnd-Protocols;
2776}
2777
John McCallc12c5bb2010-05-15 11:32:37 +00002778QualType ASTContext::getObjCObjectType(QualType BaseType,
2779 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00002780 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002781 // If the base type is an interface and there aren't any protocols
2782 // to add, then the interface type will do just fine.
2783 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2784 return BaseType;
2785
2786 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002787 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002788 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002789 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002790 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2791 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002792
John McCallc12c5bb2010-05-15 11:32:37 +00002793 // Build the canonical type, which has the canonical base type and
2794 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002795 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002796 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2797 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2798 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002799 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00002800 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002801 unsigned UniqueCount = NumProtocols;
2802
John McCall54e14c42009-10-22 22:37:11 +00002803 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002804 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2805 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002806 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002807 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2808 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002809 }
2810
2811 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002812 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2813 }
2814
2815 unsigned Size = sizeof(ObjCObjectTypeImpl);
2816 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2817 void *Mem = Allocate(Size, TypeAlignment);
2818 ObjCObjectTypeImpl *T =
2819 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2820
2821 Types.push_back(T);
2822 ObjCObjectTypes.InsertNode(T, InsertPos);
2823 return QualType(T, 0);
2824}
2825
2826/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2827/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002828QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002829 llvm::FoldingSetNodeID ID;
2830 ObjCObjectPointerType::Profile(ID, ObjectT);
2831
2832 void *InsertPos = 0;
2833 if (ObjCObjectPointerType *QT =
2834 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2835 return QualType(QT, 0);
2836
2837 // Find the canonical object type.
2838 QualType Canonical;
2839 if (!ObjectT.isCanonical()) {
2840 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2841
2842 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002843 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2844 }
2845
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002846 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002847 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2848 ObjCObjectPointerType *QType =
2849 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002850
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002851 Types.push_back(QType);
2852 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002853 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002854}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002855
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002856/// getObjCInterfaceType - Return the unique reference to the type for the
2857/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00002858QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
2859 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002860 if (Decl->TypeForDecl)
2861 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002862
Douglas Gregor0af55012011-12-16 03:12:41 +00002863 if (PrevDecl) {
2864 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
2865 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2866 return QualType(PrevDecl->TypeForDecl, 0);
2867 }
2868
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00002869 // Prefer the definition, if there is one.
2870 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
2871 Decl = Def;
2872
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002873 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2874 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2875 Decl->TypeForDecl = T;
2876 Types.push_back(T);
2877 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002878}
2879
Douglas Gregor72564e72009-02-26 23:50:07 +00002880/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2881/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002882/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002883/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002884/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002885QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002886 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002887 if (tofExpr->isTypeDependent()) {
2888 llvm::FoldingSetNodeID ID;
2889 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002890
Douglas Gregorb1975722009-07-30 23:18:24 +00002891 void *InsertPos = 0;
2892 DependentTypeOfExprType *Canon
2893 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2894 if (Canon) {
2895 // We already have a "canonical" version of an identical, dependent
2896 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002897 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002898 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00002899 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00002900 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002901 Canon
2902 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002903 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2904 toe = Canon;
2905 }
2906 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002907 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002908 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002909 }
Steve Naroff9752f252007-08-01 18:02:17 +00002910 Types.push_back(toe);
2911 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002912}
2913
Steve Naroff9752f252007-08-01 18:02:17 +00002914/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2915/// TypeOfType AST's. The only motivation to unique these nodes would be
2916/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002917/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002918/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002919QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002920 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002921 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002922 Types.push_back(tot);
2923 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002924}
2925
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002926
Anders Carlsson395b4752009-06-24 19:06:50 +00002927/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2928/// DecltypeType AST's. The only motivation to unique these nodes would be
2929/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002930/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00002931/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00002932QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002933 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00002934
2935 // C++0x [temp.type]p2:
2936 // If an expression e involves a template parameter, decltype(e) denotes a
2937 // unique dependent type. Two such decltype-specifiers refer to the same
2938 // type only if their expressions are equivalent (14.5.6.1).
2939 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002940 llvm::FoldingSetNodeID ID;
2941 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002942
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002943 void *InsertPos = 0;
2944 DependentDecltypeType *Canon
2945 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2946 if (Canon) {
2947 // We already have a "canonical" version of an equivalent, dependent
2948 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002949 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002950 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00002951 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002952 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002953 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002954 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2955 dt = Canon;
2956 }
2957 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00002958 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
2959 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002960 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002961 Types.push_back(dt);
2962 return QualType(dt, 0);
2963}
2964
Sean Huntca63c202011-05-24 22:41:36 +00002965/// getUnaryTransformationType - We don't unique these, since the memory
2966/// savings are minimal and these are rare.
2967QualType ASTContext::getUnaryTransformType(QualType BaseType,
2968 QualType UnderlyingType,
2969 UnaryTransformType::UTTKind Kind)
2970 const {
2971 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00002972 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2973 Kind,
2974 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00002975 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00002976 Types.push_back(Ty);
2977 return QualType(Ty, 0);
2978}
2979
Richard Smith483b9f32011-02-21 20:05:19 +00002980/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00002981QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00002982 void *InsertPos = 0;
2983 if (!DeducedType.isNull()) {
2984 // Look in the folding set for an existing type.
2985 llvm::FoldingSetNodeID ID;
2986 AutoType::Profile(ID, DeducedType);
2987 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2988 return QualType(AT, 0);
2989 }
2990
2991 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2992 Types.push_back(AT);
2993 if (InsertPos)
2994 AutoTypes.InsertNode(AT, InsertPos);
2995 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00002996}
2997
Eli Friedmanb001de72011-10-06 23:00:33 +00002998/// getAtomicType - Return the uniqued reference to the atomic type for
2999/// the given value type.
3000QualType ASTContext::getAtomicType(QualType T) const {
3001 // Unique pointers, to guarantee there is only one pointer of a particular
3002 // structure.
3003 llvm::FoldingSetNodeID ID;
3004 AtomicType::Profile(ID, T);
3005
3006 void *InsertPos = 0;
3007 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3008 return QualType(AT, 0);
3009
3010 // If the atomic value type isn't canonical, this won't be a canonical type
3011 // either, so fill in the canonical type field.
3012 QualType Canonical;
3013 if (!T.isCanonical()) {
3014 Canonical = getAtomicType(getCanonicalType(T));
3015
3016 // Get the new insert position for the node we care about.
3017 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3018 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3019 }
3020 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3021 Types.push_back(New);
3022 AtomicTypes.InsertNode(New, InsertPos);
3023 return QualType(New, 0);
3024}
3025
Richard Smithad762fc2011-04-14 22:09:26 +00003026/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3027QualType ASTContext::getAutoDeductType() const {
3028 if (AutoDeductTy.isNull())
3029 AutoDeductTy = getAutoType(QualType());
3030 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3031 return AutoDeductTy;
3032}
3033
3034/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3035QualType ASTContext::getAutoRRefDeductType() const {
3036 if (AutoRRefDeductTy.isNull())
3037 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3038 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3039 return AutoRRefDeductTy;
3040}
3041
Reid Spencer5f016e22007-07-11 17:01:13 +00003042/// getTagDeclType - Return the unique reference to the type for the
3043/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003044QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003045 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003046 // FIXME: What is the design on getTagDeclType when it requires casting
3047 // away const? mutable?
3048 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003049}
3050
Mike Stump1eb44332009-09-09 15:08:12 +00003051/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3052/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3053/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003054CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003055 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003056}
3057
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003058/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3059CanQualType ASTContext::getIntMaxType() const {
3060 return getFromTargetType(Target->getIntMaxType());
3061}
3062
3063/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3064CanQualType ASTContext::getUIntMaxType() const {
3065 return getFromTargetType(Target->getUIntMaxType());
3066}
3067
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003068/// getSignedWCharType - Return the type of "signed wchar_t".
3069/// Used when in C++, as a GCC extension.
3070QualType ASTContext::getSignedWCharType() const {
3071 // FIXME: derive from "Target" ?
3072 return WCharTy;
3073}
3074
3075/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3076/// Used when in C++, as a GCC extension.
3077QualType ASTContext::getUnsignedWCharType() const {
3078 // FIXME: derive from "Target" ?
3079 return UnsignedIntTy;
3080}
3081
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003082/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003083/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3084QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003085 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003086}
3087
Chris Lattnere6327742008-04-02 05:18:44 +00003088//===----------------------------------------------------------------------===//
3089// Type Operators
3090//===----------------------------------------------------------------------===//
3091
Jay Foad4ba2a172011-01-12 09:06:06 +00003092CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003093 // Push qualifiers into arrays, and then discard any remaining
3094 // qualifiers.
3095 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003096 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003097 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003098 QualType Result;
3099 if (isa<ArrayType>(Ty)) {
3100 Result = getArrayDecayedType(QualType(Ty,0));
3101 } else if (isa<FunctionType>(Ty)) {
3102 Result = getPointerType(QualType(Ty, 0));
3103 } else {
3104 Result = QualType(Ty, 0);
3105 }
3106
3107 return CanQualType::CreateUnsafe(Result);
3108}
3109
John McCall62c28c82011-01-18 07:41:22 +00003110QualType ASTContext::getUnqualifiedArrayType(QualType type,
3111 Qualifiers &quals) {
3112 SplitQualType splitType = type.getSplitUnqualifiedType();
3113
3114 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3115 // the unqualified desugared type and then drops it on the floor.
3116 // We then have to strip that sugar back off with
3117 // getUnqualifiedDesugaredType(), which is silly.
3118 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003119 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003120
3121 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003122 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003123 quals = splitType.Quals;
3124 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003125 }
3126
John McCall62c28c82011-01-18 07:41:22 +00003127 // Otherwise, recurse on the array's element type.
3128 QualType elementType = AT->getElementType();
3129 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3130
3131 // If that didn't change the element type, AT has no qualifiers, so we
3132 // can just use the results in splitType.
3133 if (elementType == unqualElementType) {
3134 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003135 quals = splitType.Quals;
3136 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003137 }
3138
3139 // Otherwise, add in the qualifiers from the outermost type, then
3140 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003141 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003142
Douglas Gregor9dadd942010-05-17 18:45:21 +00003143 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003144 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003145 CAT->getSizeModifier(), 0);
3146 }
3147
Douglas Gregor9dadd942010-05-17 18:45:21 +00003148 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003149 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003150 }
3151
Douglas Gregor9dadd942010-05-17 18:45:21 +00003152 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003153 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003154 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003155 VAT->getSizeModifier(),
3156 VAT->getIndexTypeCVRQualifiers(),
3157 VAT->getBracketsRange());
3158 }
3159
3160 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003161 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003162 DSAT->getSizeModifier(), 0,
3163 SourceRange());
3164}
3165
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003166/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3167/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3168/// they point to and return true. If T1 and T2 aren't pointer types
3169/// or pointer-to-member types, or if they are not similar at this
3170/// level, returns false and leaves T1 and T2 unchanged. Top-level
3171/// qualifiers on T1 and T2 are ignored. This function will typically
3172/// be called in a loop that successively "unwraps" pointer and
3173/// pointer-to-member types to compare them at each level.
3174bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3175 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3176 *T2PtrType = T2->getAs<PointerType>();
3177 if (T1PtrType && T2PtrType) {
3178 T1 = T1PtrType->getPointeeType();
3179 T2 = T2PtrType->getPointeeType();
3180 return true;
3181 }
3182
3183 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3184 *T2MPType = T2->getAs<MemberPointerType>();
3185 if (T1MPType && T2MPType &&
3186 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3187 QualType(T2MPType->getClass(), 0))) {
3188 T1 = T1MPType->getPointeeType();
3189 T2 = T2MPType->getPointeeType();
3190 return true;
3191 }
3192
3193 if (getLangOptions().ObjC1) {
3194 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3195 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3196 if (T1OPType && T2OPType) {
3197 T1 = T1OPType->getPointeeType();
3198 T2 = T2OPType->getPointeeType();
3199 return true;
3200 }
3201 }
3202
3203 // FIXME: Block pointers, too?
3204
3205 return false;
3206}
3207
Jay Foad4ba2a172011-01-12 09:06:06 +00003208DeclarationNameInfo
3209ASTContext::getNameForTemplate(TemplateName Name,
3210 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003211 switch (Name.getKind()) {
3212 case TemplateName::QualifiedTemplate:
3213 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003214 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003215 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3216 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003217
John McCall14606042011-06-30 08:33:18 +00003218 case TemplateName::OverloadedTemplate: {
3219 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3220 // DNInfo work in progress: CHECKME: what about DNLoc?
3221 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3222 }
3223
3224 case TemplateName::DependentTemplate: {
3225 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003226 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003227 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003228 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3229 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003230 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003231 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3232 // DNInfo work in progress: FIXME: source locations?
3233 DeclarationNameLoc DNLoc;
3234 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3235 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3236 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003237 }
3238 }
3239
John McCall14606042011-06-30 08:33:18 +00003240 case TemplateName::SubstTemplateTemplateParm: {
3241 SubstTemplateTemplateParmStorage *subst
3242 = Name.getAsSubstTemplateTemplateParm();
3243 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3244 NameLoc);
3245 }
3246
3247 case TemplateName::SubstTemplateTemplateParmPack: {
3248 SubstTemplateTemplateParmPackStorage *subst
3249 = Name.getAsSubstTemplateTemplateParmPack();
3250 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3251 NameLoc);
3252 }
3253 }
3254
3255 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003256}
3257
Jay Foad4ba2a172011-01-12 09:06:06 +00003258TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003259 switch (Name.getKind()) {
3260 case TemplateName::QualifiedTemplate:
3261 case TemplateName::Template: {
3262 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003263 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003264 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003265 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3266
3267 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003268 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003269 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003270
John McCall14606042011-06-30 08:33:18 +00003271 case TemplateName::OverloadedTemplate:
3272 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003273
John McCall14606042011-06-30 08:33:18 +00003274 case TemplateName::DependentTemplate: {
3275 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3276 assert(DTN && "Non-dependent template names must refer to template decls.");
3277 return DTN->CanonicalTemplateName;
3278 }
3279
3280 case TemplateName::SubstTemplateTemplateParm: {
3281 SubstTemplateTemplateParmStorage *subst
3282 = Name.getAsSubstTemplateTemplateParm();
3283 return getCanonicalTemplateName(subst->getReplacement());
3284 }
3285
3286 case TemplateName::SubstTemplateTemplateParmPack: {
3287 SubstTemplateTemplateParmPackStorage *subst
3288 = Name.getAsSubstTemplateTemplateParmPack();
3289 TemplateTemplateParmDecl *canonParameter
3290 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3291 TemplateArgument canonArgPack
3292 = getCanonicalTemplateArgument(subst->getArgumentPack());
3293 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3294 }
3295 }
3296
3297 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003298}
3299
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003300bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3301 X = getCanonicalTemplateName(X);
3302 Y = getCanonicalTemplateName(Y);
3303 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3304}
3305
Mike Stump1eb44332009-09-09 15:08:12 +00003306TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003307ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003308 switch (Arg.getKind()) {
3309 case TemplateArgument::Null:
3310 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003311
Douglas Gregor1275ae02009-07-28 23:00:59 +00003312 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003313 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003314
Douglas Gregor1275ae02009-07-28 23:00:59 +00003315 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00003316 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003317
Douglas Gregor788cd062009-11-11 01:00:40 +00003318 case TemplateArgument::Template:
3319 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003320
3321 case TemplateArgument::TemplateExpansion:
3322 return TemplateArgument(getCanonicalTemplateName(
3323 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003324 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003325
Douglas Gregor1275ae02009-07-28 23:00:59 +00003326 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00003327 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003328 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003329
Douglas Gregor1275ae02009-07-28 23:00:59 +00003330 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003331 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003332
Douglas Gregor1275ae02009-07-28 23:00:59 +00003333 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003334 if (Arg.pack_size() == 0)
3335 return Arg;
3336
Douglas Gregor910f8002010-11-07 23:05:16 +00003337 TemplateArgument *CanonArgs
3338 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003339 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003340 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003341 AEnd = Arg.pack_end();
3342 A != AEnd; (void)++A, ++Idx)
3343 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003344
Douglas Gregor910f8002010-11-07 23:05:16 +00003345 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003346 }
3347 }
3348
3349 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00003350 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00003351}
3352
Douglas Gregord57959a2009-03-27 23:10:48 +00003353NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003354ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003355 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003356 return 0;
3357
3358 switch (NNS->getKind()) {
3359 case NestedNameSpecifier::Identifier:
3360 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003361 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003362 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3363 NNS->getAsIdentifier());
3364
3365 case NestedNameSpecifier::Namespace:
3366 // A namespace is canonical; build a nested-name-specifier with
3367 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003368 return NestedNameSpecifier::Create(*this, 0,
3369 NNS->getAsNamespace()->getOriginalNamespace());
3370
3371 case NestedNameSpecifier::NamespaceAlias:
3372 // A namespace is canonical; build a nested-name-specifier with
3373 // this namespace and no prefix.
3374 return NestedNameSpecifier::Create(*this, 0,
3375 NNS->getAsNamespaceAlias()->getNamespace()
3376 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003377
3378 case NestedNameSpecifier::TypeSpec:
3379 case NestedNameSpecifier::TypeSpecWithTemplate: {
3380 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003381
3382 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3383 // break it apart into its prefix and identifier, then reconsititute those
3384 // as the canonical nested-name-specifier. This is required to canonicalize
3385 // a dependent nested-name-specifier involving typedefs of dependent-name
3386 // types, e.g.,
3387 // typedef typename T::type T1;
3388 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00003389 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3390 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00003391 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00003392
Eli Friedman16412ef2012-03-03 04:09:56 +00003393 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3394 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3395 // first place?
John McCall3b657512011-01-19 10:06:00 +00003396 return NestedNameSpecifier::Create(*this, 0, false,
3397 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003398 }
3399
3400 case NestedNameSpecifier::Global:
3401 // The global specifier is canonical and unique.
3402 return NNS;
3403 }
3404
David Blaikie7530c032012-01-17 06:56:22 +00003405 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00003406}
3407
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003408
Jay Foad4ba2a172011-01-12 09:06:06 +00003409const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003410 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003411 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003412 // Handle the common positive case fast.
3413 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3414 return AT;
3415 }
Mike Stump1eb44332009-09-09 15:08:12 +00003416
John McCall0953e762009-09-24 19:53:00 +00003417 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003418 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003419 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003420
John McCall0953e762009-09-24 19:53:00 +00003421 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003422 // implements C99 6.7.3p8: "If the specification of an array type includes
3423 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003424
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003425 // If we get here, we either have type qualifiers on the type, or we have
3426 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003427 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003428
John McCall3b657512011-01-19 10:06:00 +00003429 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00003430 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00003431
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003432 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00003433 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00003434 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003435 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003436
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003437 // Otherwise, we have an array and we have qualifiers on it. Push the
3438 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003439 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003440
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003441 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3442 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3443 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003444 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003445 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3446 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3447 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003448 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003449
Mike Stump1eb44332009-09-09 15:08:12 +00003450 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003451 = dyn_cast<DependentSizedArrayType>(ATy))
3452 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003453 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003454 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003455 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003456 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003457 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003458
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003459 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003460 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003461 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003462 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003463 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003464 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003465}
3466
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003467QualType ASTContext::getAdjustedParameterType(QualType T) {
3468 // C99 6.7.5.3p7:
3469 // A declaration of a parameter as "array of type" shall be
3470 // adjusted to "qualified pointer to type", where the type
3471 // qualifiers (if any) are those specified within the [ and ] of
3472 // the array type derivation.
3473 if (T->isArrayType())
3474 return getArrayDecayedType(T);
3475
3476 // C99 6.7.5.3p8:
3477 // A declaration of a parameter as "function returning type"
3478 // shall be adjusted to "pointer to function returning type", as
3479 // in 6.3.2.1.
3480 if (T->isFunctionType())
3481 return getPointerType(T);
3482
3483 return T;
3484}
3485
3486QualType ASTContext::getSignatureParameterType(QualType T) {
3487 T = getVariableArrayDecayedType(T);
3488 T = getAdjustedParameterType(T);
3489 return T.getUnqualifiedType();
3490}
3491
Chris Lattnere6327742008-04-02 05:18:44 +00003492/// getArrayDecayedType - Return the properly qualified result of decaying the
3493/// specified array type to a pointer. This operation is non-trivial when
3494/// handling typedefs etc. The canonical type of "T" must be an array type,
3495/// this returns a pointer to a properly qualified element of the array.
3496///
3497/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003498QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003499 // Get the element type with 'getAsArrayType' so that we don't lose any
3500 // typedefs in the element type of the array. This also handles propagation
3501 // of type qualifiers from the array type into the element type if present
3502 // (C99 6.7.3p8).
3503 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3504 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003505
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003506 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003507
3508 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003509 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003510}
3511
John McCall3b657512011-01-19 10:06:00 +00003512QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3513 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003514}
3515
John McCall3b657512011-01-19 10:06:00 +00003516QualType ASTContext::getBaseElementType(QualType type) const {
3517 Qualifiers qs;
3518 while (true) {
3519 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00003520 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00003521 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003522
John McCall3b657512011-01-19 10:06:00 +00003523 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00003524 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00003525 }
Mike Stump1eb44332009-09-09 15:08:12 +00003526
John McCall3b657512011-01-19 10:06:00 +00003527 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003528}
3529
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003530/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003531uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003532ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3533 uint64_t ElementCount = 1;
3534 do {
3535 ElementCount *= CA->getSize().getZExtValue();
3536 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3537 } while (CA);
3538 return ElementCount;
3539}
3540
Reid Spencer5f016e22007-07-11 17:01:13 +00003541/// getFloatingRank - Return a relative rank for floating point types.
3542/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003543static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003544 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003545 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003546
John McCall183700f2009-09-21 23:43:11 +00003547 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3548 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003549 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00003550 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00003551 case BuiltinType::Float: return FloatRank;
3552 case BuiltinType::Double: return DoubleRank;
3553 case BuiltinType::LongDouble: return LongDoubleRank;
3554 }
3555}
3556
Mike Stump1eb44332009-09-09 15:08:12 +00003557/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3558/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003559/// 'typeDomain' is a real floating point or complex type.
3560/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003561QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3562 QualType Domain) const {
3563 FloatingRank EltRank = getFloatingRank(Size);
3564 if (Domain->isComplexType()) {
3565 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00003566 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00003567 case FloatRank: return FloatComplexTy;
3568 case DoubleRank: return DoubleComplexTy;
3569 case LongDoubleRank: return LongDoubleComplexTy;
3570 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003571 }
Chris Lattner1361b112008-04-06 23:58:54 +00003572
3573 assert(Domain->isRealFloatingType() && "Unknown domain!");
3574 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00003575 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattner1361b112008-04-06 23:58:54 +00003576 case FloatRank: return FloatTy;
3577 case DoubleRank: return DoubleTy;
3578 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003579 }
David Blaikie561d3ab2012-01-17 02:30:50 +00003580 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00003581}
3582
Chris Lattner7cfeb082008-04-06 23:55:33 +00003583/// getFloatingTypeOrder - Compare the rank of the two specified floating
3584/// point types, ignoring the domain of the type (i.e. 'double' ==
3585/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003586/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003587int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003588 FloatingRank LHSR = getFloatingRank(LHS);
3589 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003590
Chris Lattnera75cea32008-04-06 23:38:49 +00003591 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003592 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003593 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003594 return 1;
3595 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003596}
3597
Chris Lattnerf52ab252008-04-06 22:59:24 +00003598/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3599/// routine will assert if passed a built-in type that isn't an integer or enum,
3600/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003601unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003602 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003603
Chris Lattnerf52ab252008-04-06 22:59:24 +00003604 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003605 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00003606 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003607 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003608 case BuiltinType::Char_S:
3609 case BuiltinType::Char_U:
3610 case BuiltinType::SChar:
3611 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003612 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003613 case BuiltinType::Short:
3614 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003615 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003616 case BuiltinType::Int:
3617 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003618 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003619 case BuiltinType::Long:
3620 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003621 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003622 case BuiltinType::LongLong:
3623 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003624 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003625 case BuiltinType::Int128:
3626 case BuiltinType::UInt128:
3627 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003628 }
3629}
3630
Eli Friedman04e83572009-08-20 04:21:42 +00003631/// \brief Whether this is a promotable bitfield reference according
3632/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3633///
3634/// \returns the type this bit-field will promote to, or NULL if no
3635/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00003636QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003637 if (E->isTypeDependent() || E->isValueDependent())
3638 return QualType();
3639
Eli Friedman04e83572009-08-20 04:21:42 +00003640 FieldDecl *Field = E->getBitField();
3641 if (!Field)
3642 return QualType();
3643
3644 QualType FT = Field->getType();
3645
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003646 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00003647 uint64_t IntSize = getTypeSize(IntTy);
3648 // GCC extension compatibility: if the bit-field size is less than or equal
3649 // to the size of int, it gets promoted no matter what its type is.
3650 // For instance, unsigned long bf : 4 gets promoted to signed int.
3651 if (BitWidth < IntSize)
3652 return IntTy;
3653
3654 if (BitWidth == IntSize)
3655 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3656
3657 // Types bigger than int are not subject to promotions, and therefore act
3658 // like the base type.
3659 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3660 // is ridiculous.
3661 return QualType();
3662}
3663
Eli Friedmana95d7572009-08-19 07:44:53 +00003664/// getPromotedIntegerType - Returns the type that Promotable will
3665/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3666/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003667QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003668 assert(!Promotable.isNull());
3669 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003670 if (const EnumType *ET = Promotable->getAs<EnumType>())
3671 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00003672
3673 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3674 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3675 // (3.9.1) can be converted to a prvalue of the first of the following
3676 // types that can represent all the values of its underlying type:
3677 // int, unsigned int, long int, unsigned long int, long long int, or
3678 // unsigned long long int [...]
3679 // FIXME: Is there some better way to compute this?
3680 if (BT->getKind() == BuiltinType::WChar_S ||
3681 BT->getKind() == BuiltinType::WChar_U ||
3682 BT->getKind() == BuiltinType::Char16 ||
3683 BT->getKind() == BuiltinType::Char32) {
3684 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3685 uint64_t FromSize = getTypeSize(BT);
3686 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3687 LongLongTy, UnsignedLongLongTy };
3688 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3689 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3690 if (FromSize < ToSize ||
3691 (FromSize == ToSize &&
3692 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3693 return PromoteTypes[Idx];
3694 }
3695 llvm_unreachable("char type should fit into long long");
3696 }
3697 }
3698
3699 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00003700 if (Promotable->isSignedIntegerType())
3701 return IntTy;
3702 uint64_t PromotableSize = getTypeSize(Promotable);
3703 uint64_t IntSize = getTypeSize(IntTy);
3704 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3705 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3706}
3707
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003708/// \brief Recurses in pointer/array types until it finds an objc retainable
3709/// type and returns its ownership.
3710Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3711 while (!T.isNull()) {
3712 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3713 return T.getObjCLifetime();
3714 if (T->isArrayType())
3715 T = getBaseElementType(T);
3716 else if (const PointerType *PT = T->getAs<PointerType>())
3717 T = PT->getPointeeType();
3718 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00003719 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003720 else
3721 break;
3722 }
3723
3724 return Qualifiers::OCL_None;
3725}
3726
Mike Stump1eb44332009-09-09 15:08:12 +00003727/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003728/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003729/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003730int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00003731 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3732 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003733 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003734
Chris Lattnerf52ab252008-04-06 22:59:24 +00003735 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3736 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003737
Chris Lattner7cfeb082008-04-06 23:55:33 +00003738 unsigned LHSRank = getIntegerRank(LHSC);
3739 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003740
Chris Lattner7cfeb082008-04-06 23:55:33 +00003741 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3742 if (LHSRank == RHSRank) return 0;
3743 return LHSRank > RHSRank ? 1 : -1;
3744 }
Mike Stump1eb44332009-09-09 15:08:12 +00003745
Chris Lattner7cfeb082008-04-06 23:55:33 +00003746 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3747 if (LHSUnsigned) {
3748 // If the unsigned [LHS] type is larger, return it.
3749 if (LHSRank >= RHSRank)
3750 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003751
Chris Lattner7cfeb082008-04-06 23:55:33 +00003752 // If the signed type can represent all values of the unsigned type, it
3753 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003754 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003755 return -1;
3756 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003757
Chris Lattner7cfeb082008-04-06 23:55:33 +00003758 // If the unsigned [RHS] type is larger, return it.
3759 if (RHSRank >= LHSRank)
3760 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003761
Chris Lattner7cfeb082008-04-06 23:55:33 +00003762 // If the signed type can represent all values of the unsigned type, it
3763 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003764 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003765 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003766}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003767
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003768static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003769CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3770 DeclContext *DC, IdentifierInfo *Id) {
3771 SourceLocation Loc;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003772 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003773 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003774 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003775 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003776}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003777
Mike Stump1eb44332009-09-09 15:08:12 +00003778// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003779QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003780 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003781 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003782 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003783 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003784 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003785
Anders Carlssonf06273f2007-11-19 00:25:30 +00003786 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003787
Anders Carlsson71993dd2007-08-17 05:31:46 +00003788 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003789 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003790 // int flags;
3791 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003792 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003793 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003794 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003795 FieldTypes[3] = LongTy;
3796
Anders Carlsson71993dd2007-08-17 05:31:46 +00003797 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003798 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003799 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003800 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00003801 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003802 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003803 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003804 /*Mutable=*/false,
3805 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003806 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003807 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003808 }
3809
Douglas Gregor838db382010-02-11 01:19:42 +00003810 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003811 }
Mike Stump1eb44332009-09-09 15:08:12 +00003812
Anders Carlsson71993dd2007-08-17 05:31:46 +00003813 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003814}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003815
Douglas Gregor319ac892009-04-23 22:29:11 +00003816void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003817 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003818 assert(Rec && "Invalid CFConstantStringType");
3819 CFConstantStringTypeDecl = Rec->getDecl();
3820}
3821
Jay Foad4ba2a172011-01-12 09:06:06 +00003822QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00003823 if (BlockDescriptorType)
3824 return getTagDeclType(BlockDescriptorType);
3825
3826 RecordDecl *T;
3827 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003828 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003829 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003830 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003831
3832 QualType FieldTypes[] = {
3833 UnsignedLongTy,
3834 UnsignedLongTy,
3835 };
3836
3837 const char *FieldNames[] = {
3838 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003839 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003840 };
3841
3842 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003843 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003844 SourceLocation(),
3845 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003846 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003847 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003848 /*Mutable=*/false,
3849 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003850 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003851 T->addDecl(Field);
3852 }
3853
Douglas Gregor838db382010-02-11 01:19:42 +00003854 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003855
3856 BlockDescriptorType = T;
3857
3858 return getTagDeclType(BlockDescriptorType);
3859}
3860
Jay Foad4ba2a172011-01-12 09:06:06 +00003861QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00003862 if (BlockDescriptorExtendedType)
3863 return getTagDeclType(BlockDescriptorExtendedType);
3864
3865 RecordDecl *T;
3866 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003867 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003868 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003869 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003870
3871 QualType FieldTypes[] = {
3872 UnsignedLongTy,
3873 UnsignedLongTy,
3874 getPointerType(VoidPtrTy),
3875 getPointerType(VoidPtrTy)
3876 };
3877
3878 const char *FieldNames[] = {
3879 "reserved",
3880 "Size",
3881 "CopyFuncPtr",
3882 "DestroyFuncPtr"
3883 };
3884
3885 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003886 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00003887 SourceLocation(),
3888 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003889 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003890 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003891 /*Mutable=*/false,
3892 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003893 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003894 T->addDecl(Field);
3895 }
3896
Douglas Gregor838db382010-02-11 01:19:42 +00003897 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003898
3899 BlockDescriptorExtendedType = T;
3900
3901 return getTagDeclType(BlockDescriptorExtendedType);
3902}
3903
Jay Foad4ba2a172011-01-12 09:06:06 +00003904bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCallf85e1932011-06-15 23:02:42 +00003905 if (Ty->isObjCRetainableType())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003906 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003907 if (getLangOptions().CPlusPlus) {
3908 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3909 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Huntffe37fd2011-05-25 20:50:04 +00003910 return RD->hasConstCopyConstructor();
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003911
3912 }
3913 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003914 return false;
3915}
3916
Jay Foad4ba2a172011-01-12 09:06:06 +00003917QualType
Chris Lattner5f9e2722011-07-23 10:55:15 +00003918ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003919 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003920 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003921 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003922 // unsigned int __flags;
3923 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003924 // void *__copy_helper; // as needed
3925 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003926 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003927 // } *
3928
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003929 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3930
3931 // FIXME: Move up
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003932 SmallString<36> Name;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003933 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3934 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003935 RecordDecl *T;
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003936 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003937 T->startDefinition();
3938 QualType Int32Ty = IntTy;
3939 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3940 QualType FieldTypes[] = {
3941 getPointerType(VoidPtrTy),
3942 getPointerType(getTagDeclType(T)),
3943 Int32Ty,
3944 Int32Ty,
3945 getPointerType(VoidPtrTy),
3946 getPointerType(VoidPtrTy),
3947 Ty
3948 };
3949
Chris Lattner5f9e2722011-07-23 10:55:15 +00003950 StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003951 "__isa",
3952 "__forwarding",
3953 "__flags",
3954 "__size",
3955 "__copy_helper",
3956 "__destroy_helper",
3957 DeclName,
3958 };
3959
3960 for (size_t i = 0; i < 7; ++i) {
3961 if (!HasCopyAndDispose && i >=4 && i <= 5)
3962 continue;
3963 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003964 SourceLocation(),
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003965 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003966 FieldTypes[i], /*TInfo=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003967 /*BitWidth=*/0, /*Mutable=*/false,
3968 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003969 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003970 T->addDecl(Field);
3971 }
3972
Douglas Gregor838db382010-02-11 01:19:42 +00003973 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003974
3975 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003976}
3977
Douglas Gregore97179c2011-09-08 01:46:34 +00003978TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
3979 if (!ObjCInstanceTypeDecl)
3980 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
3981 getTranslationUnitDecl(),
3982 SourceLocation(),
3983 SourceLocation(),
3984 &Idents.get("instancetype"),
3985 getTrivialTypeSourceInfo(getObjCIdType()));
3986 return ObjCInstanceTypeDecl;
3987}
3988
Anders Carlssone8c49532007-10-29 06:33:42 +00003989// This returns true if a type has been typedefed to BOOL:
3990// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003991static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003992 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003993 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3994 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003995
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003996 return false;
3997}
3998
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003999/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004000/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004001CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004002 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4003 return CharUnits::Zero();
4004
Ken Dyck199c3d62010-01-11 17:06:35 +00004005 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004006
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004007 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004008 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004009 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004010 // Treat arrays as pointers, since that's how they're passed in.
4011 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004012 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004013 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004014}
4015
4016static inline
4017std::string charUnitsToString(const CharUnits &CU) {
4018 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004019}
4020
John McCall6b5a61b2011-02-07 10:33:21 +00004021/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004022/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004023std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4024 std::string S;
4025
David Chisnall5e530af2009-11-17 19:33:30 +00004026 const BlockDecl *Decl = Expr->getBlockDecl();
4027 QualType BlockTy =
4028 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4029 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00004030 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00004031 // Compute size of all parameters.
4032 // Start with computing size of a pointer in number of bytes.
4033 // FIXME: There might(should) be a better way of doing this computation!
4034 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004035 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4036 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004037 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004038 E = Decl->param_end(); PI != E; ++PI) {
4039 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004040 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00004041 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004042 ParmOffset += sz;
4043 }
4044 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004045 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004046 // Block pointer and offset.
4047 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004048
4049 // Argument types.
4050 ParmOffset = PtrSize;
4051 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4052 Decl->param_end(); PI != E; ++PI) {
4053 ParmVarDecl *PVDecl = *PI;
4054 QualType PType = PVDecl->getOriginalType();
4055 if (const ArrayType *AT =
4056 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4057 // Use array's original type only if it has known number of
4058 // elements.
4059 if (!isa<ConstantArrayType>(AT))
4060 PType = PVDecl->getType();
4061 } else if (PType->isFunctionType())
4062 PType = PVDecl->getType();
4063 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004064 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004065 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004066 }
John McCall6b5a61b2011-02-07 10:33:21 +00004067
4068 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004069}
4070
Douglas Gregorf968d832011-05-27 01:19:52 +00004071bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004072 std::string& S) {
4073 // Encode result type.
4074 getObjCEncodingForType(Decl->getResultType(), S);
4075 CharUnits ParmOffset;
4076 // Compute size of all parameters.
4077 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4078 E = Decl->param_end(); PI != E; ++PI) {
4079 QualType PType = (*PI)->getType();
4080 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004081 if (sz.isZero())
4082 return true;
4083
David Chisnall5389f482010-12-30 14:05:53 +00004084 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004085 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004086 ParmOffset += sz;
4087 }
4088 S += charUnitsToString(ParmOffset);
4089 ParmOffset = CharUnits::Zero();
4090
4091 // Argument types.
4092 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4093 E = Decl->param_end(); PI != E; ++PI) {
4094 ParmVarDecl *PVDecl = *PI;
4095 QualType PType = PVDecl->getOriginalType();
4096 if (const ArrayType *AT =
4097 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4098 // Use array's original type only if it has known number of
4099 // elements.
4100 if (!isa<ConstantArrayType>(AT))
4101 PType = PVDecl->getType();
4102 } else if (PType->isFunctionType())
4103 PType = PVDecl->getType();
4104 getObjCEncodingForType(PType, S);
4105 S += charUnitsToString(ParmOffset);
4106 ParmOffset += getObjCEncodingTypeSize(PType);
4107 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004108
4109 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004110}
4111
Bob Wilsondc8dab62011-11-30 01:57:58 +00004112/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4113/// method parameter or return type. If Extended, include class names and
4114/// block object types.
4115void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4116 QualType T, std::string& S,
4117 bool Extended) const {
4118 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4119 getObjCEncodingForTypeQualifier(QT, S);
4120 // Encode parameter type.
4121 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4122 true /*OutermostType*/,
4123 false /*EncodingProperty*/,
4124 false /*StructField*/,
4125 Extended /*EncodeBlockParameters*/,
4126 Extended /*EncodeClassNames*/);
4127}
4128
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004129/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004130/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004131bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004132 std::string& S,
4133 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004134 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004135 // Encode return type.
4136 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4137 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004138 // Compute size of all parameters.
4139 // Start with computing size of a pointer in number of bytes.
4140 // FIXME: There might(should) be a better way of doing this computation!
4141 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004142 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004143 // The first two arguments (self and _cmd) are pointers; account for
4144 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004145 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004146 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004147 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004148 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004149 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004150 if (sz.isZero())
4151 return true;
4152
Ken Dyck199c3d62010-01-11 17:06:35 +00004153 assert (sz.isPositive() &&
4154 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004155 ParmOffset += sz;
4156 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004157 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004158 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004159 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004160
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004161 // Argument types.
4162 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004163 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004164 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004165 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004166 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004167 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004168 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4169 // Use array's original type only if it has known number of
4170 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004171 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004172 PType = PVDecl->getType();
4173 } else if (PType->isFunctionType())
4174 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004175 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4176 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004177 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004178 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004179 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004180
4181 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004182}
4183
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004184/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004185/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004186/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4187/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004188/// Property attributes are stored as a comma-delimited C string. The simple
4189/// attributes readonly and bycopy are encoded as single characters. The
4190/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4191/// encoded as single characters, followed by an identifier. Property types
4192/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004193/// these attributes are defined by the following enumeration:
4194/// @code
4195/// enum PropertyAttributes {
4196/// kPropertyReadOnly = 'R', // property is read-only.
4197/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4198/// kPropertyByref = '&', // property is a reference to the value last assigned
4199/// kPropertyDynamic = 'D', // property is dynamic
4200/// kPropertyGetter = 'G', // followed by getter selector name
4201/// kPropertySetter = 'S', // followed by setter selector name
4202/// kPropertyInstanceVariable = 'V' // followed by instance variable name
4203/// kPropertyType = 't' // followed by old-style type encoding.
4204/// kPropertyWeak = 'W' // 'weak' property
4205/// kPropertyStrong = 'P' // property GC'able
4206/// kPropertyNonAtomic = 'N' // property non-atomic
4207/// };
4208/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004209void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004210 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004211 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004212 // Collect information from the property implementation decl(s).
4213 bool Dynamic = false;
4214 ObjCPropertyImplDecl *SynthesizePID = 0;
4215
4216 // FIXME: Duplicated code due to poor abstraction.
4217 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004218 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004219 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4220 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004221 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004222 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004223 ObjCPropertyImplDecl *PID = *i;
4224 if (PID->getPropertyDecl() == PD) {
4225 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4226 Dynamic = true;
4227 } else {
4228 SynthesizePID = PID;
4229 }
4230 }
4231 }
4232 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004233 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004234 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004235 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004236 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004237 ObjCPropertyImplDecl *PID = *i;
4238 if (PID->getPropertyDecl() == PD) {
4239 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4240 Dynamic = true;
4241 } else {
4242 SynthesizePID = PID;
4243 }
4244 }
Mike Stump1eb44332009-09-09 15:08:12 +00004245 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004246 }
4247 }
4248
4249 // FIXME: This is not very efficient.
4250 S = "T";
4251
4252 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004253 // GCC has some special rules regarding encoding of properties which
4254 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004255 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004256 true /* outermost type */,
4257 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004258
4259 if (PD->isReadOnly()) {
4260 S += ",R";
4261 } else {
4262 switch (PD->getSetterKind()) {
4263 case ObjCPropertyDecl::Assign: break;
4264 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004265 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004266 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004267 }
4268 }
4269
4270 // It really isn't clear at all what this means, since properties
4271 // are "dynamic by default".
4272 if (Dynamic)
4273 S += ",D";
4274
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004275 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4276 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004277
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004278 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4279 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004280 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004281 }
4282
4283 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4284 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004285 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004286 }
4287
4288 if (SynthesizePID) {
4289 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4290 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004291 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004292 }
4293
4294 // FIXME: OBJCGC: weak & strong
4295}
4296
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004297/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004298/// Another legacy compatibility encoding: 32-bit longs are encoded as
4299/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004300/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4301///
4302void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004303 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004304 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004305 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004306 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004307 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004308 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004309 PointeeTy = IntTy;
4310 }
4311 }
4312}
4313
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004314void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004315 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004316 // We follow the behavior of gcc, expanding structures which are
4317 // directly pointed to, and expanding embedded structures. Note that
4318 // these rules are sufficient to prevent recursive encoding of the
4319 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004320 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004321 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004322}
4323
David Chisnall64fd7e82010-06-04 01:10:52 +00004324static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4325 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004326 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnall64fd7e82010-06-04 01:10:52 +00004327 case BuiltinType::Void: return 'v';
4328 case BuiltinType::Bool: return 'B';
4329 case BuiltinType::Char_U:
4330 case BuiltinType::UChar: return 'C';
4331 case BuiltinType::UShort: return 'S';
4332 case BuiltinType::UInt: return 'I';
4333 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00004334 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004335 case BuiltinType::UInt128: return 'T';
4336 case BuiltinType::ULongLong: return 'Q';
4337 case BuiltinType::Char_S:
4338 case BuiltinType::SChar: return 'c';
4339 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004340 case BuiltinType::WChar_S:
4341 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004342 case BuiltinType::Int: return 'i';
4343 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00004344 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004345 case BuiltinType::LongLong: return 'q';
4346 case BuiltinType::Int128: return 't';
4347 case BuiltinType::Float: return 'f';
4348 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004349 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004350 }
4351}
4352
Douglas Gregor5471bc82011-09-08 17:18:35 +00004353static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4354 EnumDecl *Enum = ET->getDecl();
4355
4356 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4357 if (!Enum->isFixed())
4358 return 'i';
4359
4360 // The encoding of a fixed enum type matches its fixed underlying type.
4361 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4362}
4363
Jay Foad4ba2a172011-01-12 09:06:06 +00004364static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004365 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004366 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004367 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004368 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4369 // The GNU runtime requires more information; bitfields are encoded as b,
4370 // then the offset (in bits) of the first element, then the type of the
4371 // bitfield, then the size in bits. For example, in this structure:
4372 //
4373 // struct
4374 // {
4375 // int integer;
4376 // int flags:2;
4377 // };
4378 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4379 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4380 // information is not especially sensible, but we're stuck with it for
4381 // compatibility with GCC, although providing it breaks anything that
4382 // actually uses runtime introspection and wants to work on both runtimes...
4383 if (!Ctx->getLangOptions().NeXTRuntime) {
4384 const RecordDecl *RD = FD->getParent();
4385 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004386 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00004387 if (const EnumType *ET = T->getAs<EnumType>())
4388 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnallc7ff82c2010-12-26 20:12:30 +00004389 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004390 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004391 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004392 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004393}
4394
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004395// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004396void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4397 bool ExpandPointedToStructures,
4398 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004399 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004400 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004401 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004402 bool StructField,
4403 bool EncodeBlockParameters,
4404 bool EncodeClassNames) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004405 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004406 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004407 return EncodeBitField(this, S, T, FD);
4408 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004409 return;
4410 }
Mike Stump1eb44332009-09-09 15:08:12 +00004411
John McCall183700f2009-09-21 23:43:11 +00004412 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004413 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004414 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004415 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004416 return;
4417 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004418
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004419 // encoding for pointer or r3eference types.
4420 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004421 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004422 if (PT->isObjCSelType()) {
4423 S += ':';
4424 return;
4425 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004426 PointeeTy = PT->getPointeeType();
4427 }
4428 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4429 PointeeTy = RT->getPointeeType();
4430 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004431 bool isReadOnly = false;
4432 // For historical/compatibility reasons, the read-only qualifier of the
4433 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4434 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004435 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004436 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004437 if (OutermostType && T.isConstQualified()) {
4438 isReadOnly = true;
4439 S += 'r';
4440 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004441 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004442 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004443 while (P->getAs<PointerType>())
4444 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004445 if (P.isConstQualified()) {
4446 isReadOnly = true;
4447 S += 'r';
4448 }
4449 }
4450 if (isReadOnly) {
4451 // Another legacy compatibility encoding. Some ObjC qualifier and type
4452 // combinations need to be rearranged.
4453 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00004454 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00004455 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004456 }
Mike Stump1eb44332009-09-09 15:08:12 +00004457
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004458 if (PointeeTy->isCharType()) {
4459 // char pointer types should be encoded as '*' unless it is a
4460 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004461 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004462 S += '*';
4463 return;
4464 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004465 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004466 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4467 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4468 S += '#';
4469 return;
4470 }
4471 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4472 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4473 S += '@';
4474 return;
4475 }
4476 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004477 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004478 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004479 getLegacyIntegralTypeEncoding(PointeeTy);
4480
Mike Stump1eb44332009-09-09 15:08:12 +00004481 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004482 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004483 return;
4484 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004485
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004486 if (const ArrayType *AT =
4487 // Ignore type qualifiers etc.
4488 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004489 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004490 // Incomplete arrays are encoded as a pointer to the array element.
4491 S += '^';
4492
Mike Stump1eb44332009-09-09 15:08:12 +00004493 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004494 false, ExpandStructures, FD);
4495 } else {
4496 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004497
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004498 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4499 if (getTypeSize(CAT->getElementType()) == 0)
4500 S += '0';
4501 else
4502 S += llvm::utostr(CAT->getSize().getZExtValue());
4503 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00004504 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004505 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4506 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00004507 S += '0';
4508 }
Mike Stump1eb44332009-09-09 15:08:12 +00004509
4510 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004511 false, ExpandStructures, FD);
4512 S += ']';
4513 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004514 return;
4515 }
Mike Stump1eb44332009-09-09 15:08:12 +00004516
John McCall183700f2009-09-21 23:43:11 +00004517 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004518 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004519 return;
4520 }
Mike Stump1eb44332009-09-09 15:08:12 +00004521
Ted Kremenek6217b802009-07-29 21:53:49 +00004522 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004523 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004524 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004525 // Anonymous structures print as '?'
4526 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4527 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004528 if (ClassTemplateSpecializationDecl *Spec
4529 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4530 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4531 std::string TemplateArgsStr
4532 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004533 TemplateArgs.data(),
4534 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00004535 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004536
4537 S += TemplateArgsStr;
4538 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004539 } else {
4540 S += '?';
4541 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004542 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004543 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004544 if (!RDecl->isUnion()) {
4545 getObjCEncodingForStructureImpl(RDecl, S, FD);
4546 } else {
4547 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4548 FieldEnd = RDecl->field_end();
4549 Field != FieldEnd; ++Field) {
4550 if (FD) {
4551 S += '"';
4552 S += Field->getNameAsString();
4553 S += '"';
4554 }
Mike Stump1eb44332009-09-09 15:08:12 +00004555
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004556 // Special case bit-fields.
4557 if (Field->isBitField()) {
4558 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4559 (*Field));
4560 } else {
4561 QualType qt = Field->getType();
4562 getLegacyIntegralTypeEncoding(qt);
4563 getObjCEncodingForTypeImpl(qt, S, false, true,
4564 FD, /*OutermostType*/false,
4565 /*EncodingProperty*/false,
4566 /*StructField*/true);
4567 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004568 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004569 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004570 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004571 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004572 return;
4573 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004574
Douglas Gregor5471bc82011-09-08 17:18:35 +00004575 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004576 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004577 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004578 else
Douglas Gregor5471bc82011-09-08 17:18:35 +00004579 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004580 return;
4581 }
Mike Stump1eb44332009-09-09 15:08:12 +00004582
Bob Wilsondc8dab62011-11-30 01:57:58 +00004583 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004584 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00004585 if (EncodeBlockParameters) {
4586 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4587
4588 S += '<';
4589 // Block return type
4590 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4591 ExpandPointedToStructures, ExpandStructures,
4592 FD,
4593 false /* OutermostType */,
4594 EncodingProperty,
4595 false /* StructField */,
4596 EncodeBlockParameters,
4597 EncodeClassNames);
4598 // Block self
4599 S += "@?";
4600 // Block parameters
4601 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4602 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4603 E = FPT->arg_type_end(); I && (I != E); ++I) {
4604 getObjCEncodingForTypeImpl(*I, S,
4605 ExpandPointedToStructures,
4606 ExpandStructures,
4607 FD,
4608 false /* OutermostType */,
4609 EncodingProperty,
4610 false /* StructField */,
4611 EncodeBlockParameters,
4612 EncodeClassNames);
4613 }
4614 }
4615 S += '>';
4616 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004617 return;
4618 }
Mike Stump1eb44332009-09-09 15:08:12 +00004619
John McCallc12c5bb2010-05-15 11:32:37 +00004620 // Ignore protocol qualifiers when mangling at this level.
4621 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4622 T = OT->getBaseType();
4623
John McCall0953e762009-09-24 19:53:00 +00004624 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004625 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004626 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004627 S += '{';
4628 const IdentifierInfo *II = OI->getIdentifier();
4629 S += II->getName();
4630 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00004631 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004632 DeepCollectObjCIvars(OI, true, Ivars);
4633 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00004634 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004635 if (Field->isBitField())
4636 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004637 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004638 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004639 }
4640 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004641 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004642 }
Mike Stump1eb44332009-09-09 15:08:12 +00004643
John McCall183700f2009-09-21 23:43:11 +00004644 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004645 if (OPT->isObjCIdType()) {
4646 S += '@';
4647 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004648 }
Mike Stump1eb44332009-09-09 15:08:12 +00004649
Steve Naroff27d20a22009-10-28 22:03:49 +00004650 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4651 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4652 // Since this is a binary compatibility issue, need to consult with runtime
4653 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004654 S += '#';
4655 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004656 }
Mike Stump1eb44332009-09-09 15:08:12 +00004657
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004658 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004659 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004660 ExpandPointedToStructures,
4661 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00004662 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00004663 // Note that we do extended encoding of protocol qualifer list
4664 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004665 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004666 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4667 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004668 S += '<';
4669 S += (*I)->getNameAsString();
4670 S += '>';
4671 }
4672 S += '"';
4673 }
4674 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004675 }
Mike Stump1eb44332009-09-09 15:08:12 +00004676
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004677 QualType PointeeTy = OPT->getPointeeType();
4678 if (!EncodingProperty &&
4679 isa<TypedefType>(PointeeTy.getTypePtr())) {
4680 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004681 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004682 // {...};
4683 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004684 getObjCEncodingForTypeImpl(PointeeTy, S,
4685 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004686 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004687 return;
4688 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004689
4690 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00004691 if (OPT->getInterfaceDecl() &&
4692 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004693 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004694 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004695 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4696 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004697 S += '<';
4698 S += (*I)->getNameAsString();
4699 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004700 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004701 S += '"';
4702 }
4703 return;
4704 }
Mike Stump1eb44332009-09-09 15:08:12 +00004705
John McCall532ec7b2010-05-17 23:56:34 +00004706 // gcc just blithely ignores member pointers.
4707 // TODO: maybe there should be a mangling for these
4708 if (T->getAs<MemberPointerType>())
4709 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004710
4711 if (T->isVectorType()) {
4712 // This matches gcc's encoding, even though technically it is
4713 // insufficient.
4714 // FIXME. We should do a better job than gcc.
4715 return;
4716 }
4717
David Blaikieb219cfc2011-09-23 05:06:16 +00004718 llvm_unreachable("@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004719}
4720
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004721void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4722 std::string &S,
4723 const FieldDecl *FD,
4724 bool includeVBases) const {
4725 assert(RDecl && "Expected non-null RecordDecl");
4726 assert(!RDecl->isUnion() && "Should not be called for unions");
4727 if (!RDecl->getDefinition())
4728 return;
4729
4730 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4731 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4732 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4733
4734 if (CXXRec) {
4735 for (CXXRecordDecl::base_class_iterator
4736 BI = CXXRec->bases_begin(),
4737 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4738 if (!BI->isVirtual()) {
4739 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004740 if (base->isEmpty())
4741 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004742 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4743 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4744 std::make_pair(offs, base));
4745 }
4746 }
4747 }
4748
4749 unsigned i = 0;
4750 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4751 FieldEnd = RDecl->field_end();
4752 Field != FieldEnd; ++Field, ++i) {
4753 uint64_t offs = layout.getFieldOffset(i);
4754 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4755 std::make_pair(offs, *Field));
4756 }
4757
4758 if (CXXRec && includeVBases) {
4759 for (CXXRecordDecl::base_class_iterator
4760 BI = CXXRec->vbases_begin(),
4761 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4762 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004763 if (base->isEmpty())
4764 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004765 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00004766 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4767 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4768 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004769 }
4770 }
4771
4772 CharUnits size;
4773 if (CXXRec) {
4774 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4775 } else {
4776 size = layout.getSize();
4777 }
4778
4779 uint64_t CurOffs = 0;
4780 std::multimap<uint64_t, NamedDecl *>::iterator
4781 CurLayObj = FieldOrBaseOffsets.begin();
4782
Argyrios Kyrtzidiscb8061e2011-08-22 16:03:14 +00004783 if ((CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) ||
4784 (CurLayObj == FieldOrBaseOffsets.end() &&
4785 CXXRec && CXXRec->isDynamicClass())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004786 assert(CXXRec && CXXRec->isDynamicClass() &&
4787 "Offset 0 was empty but no VTable ?");
4788 if (FD) {
4789 S += "\"_vptr$";
4790 std::string recname = CXXRec->getNameAsString();
4791 if (recname.empty()) recname = "?";
4792 S += recname;
4793 S += '"';
4794 }
4795 S += "^^?";
4796 CurOffs += getTypeSize(VoidPtrTy);
4797 }
4798
4799 if (!RDecl->hasFlexibleArrayMember()) {
4800 // Mark the end of the structure.
4801 uint64_t offs = toBits(size);
4802 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4803 std::make_pair(offs, (NamedDecl*)0));
4804 }
4805
4806 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4807 assert(CurOffs <= CurLayObj->first);
4808
4809 if (CurOffs < CurLayObj->first) {
4810 uint64_t padding = CurLayObj->first - CurOffs;
4811 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4812 // packing/alignment of members is different that normal, in which case
4813 // the encoding will be out-of-sync with the real layout.
4814 // If the runtime switches to just consider the size of types without
4815 // taking into account alignment, we could make padding explicit in the
4816 // encoding (e.g. using arrays of chars). The encoding strings would be
4817 // longer then though.
4818 CurOffs += padding;
4819 }
4820
4821 NamedDecl *dcl = CurLayObj->second;
4822 if (dcl == 0)
4823 break; // reached end of structure.
4824
4825 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4826 // We expand the bases without their virtual bases since those are going
4827 // in the initial structure. Note that this differs from gcc which
4828 // expands virtual bases each time one is encountered in the hierarchy,
4829 // making the encoding type bigger than it really is.
4830 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004831 assert(!base->isEmpty());
4832 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004833 } else {
4834 FieldDecl *field = cast<FieldDecl>(dcl);
4835 if (FD) {
4836 S += '"';
4837 S += field->getNameAsString();
4838 S += '"';
4839 }
4840
4841 if (field->isBitField()) {
4842 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004843 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004844 } else {
4845 QualType qt = field->getType();
4846 getLegacyIntegralTypeEncoding(qt);
4847 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4848 /*OutermostType*/false,
4849 /*EncodingProperty*/false,
4850 /*StructField*/true);
4851 CurOffs += getTypeSize(field->getType());
4852 }
4853 }
4854 }
4855}
4856
Mike Stump1eb44332009-09-09 15:08:12 +00004857void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004858 std::string& S) const {
4859 if (QT & Decl::OBJC_TQ_In)
4860 S += 'n';
4861 if (QT & Decl::OBJC_TQ_Inout)
4862 S += 'N';
4863 if (QT & Decl::OBJC_TQ_Out)
4864 S += 'o';
4865 if (QT & Decl::OBJC_TQ_Bycopy)
4866 S += 'O';
4867 if (QT & Decl::OBJC_TQ_Byref)
4868 S += 'R';
4869 if (QT & Decl::OBJC_TQ_Oneway)
4870 S += 'V';
4871}
4872
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004873void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004874 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004875
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004876 BuiltinVaListType = T;
4877}
4878
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00004879TypedefDecl *ASTContext::getObjCIdDecl() const {
4880 if (!ObjCIdDecl) {
4881 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4882 T = getObjCObjectPointerType(T);
4883 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4884 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4885 getTranslationUnitDecl(),
4886 SourceLocation(), SourceLocation(),
4887 &Idents.get("id"), IdInfo);
4888 }
4889
4890 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00004891}
4892
Douglas Gregor7a27ea52011-08-12 06:17:30 +00004893TypedefDecl *ASTContext::getObjCSelDecl() const {
4894 if (!ObjCSelDecl) {
4895 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4896 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4897 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4898 getTranslationUnitDecl(),
4899 SourceLocation(), SourceLocation(),
4900 &Idents.get("SEL"), SelInfo);
4901 }
4902 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004903}
4904
Douglas Gregor79d67262011-08-12 05:59:41 +00004905TypedefDecl *ASTContext::getObjCClassDecl() const {
4906 if (!ObjCClassDecl) {
4907 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4908 T = getObjCObjectPointerType(T);
4909 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4910 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4911 getTranslationUnitDecl(),
4912 SourceLocation(), SourceLocation(),
4913 &Idents.get("Class"), ClassInfo);
4914 }
4915
4916 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004917}
4918
Douglas Gregora6ea10e2012-01-17 18:09:05 +00004919ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
4920 if (!ObjCProtocolClassDecl) {
4921 ObjCProtocolClassDecl
4922 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
4923 SourceLocation(),
4924 &Idents.get("Protocol"),
4925 /*PrevDecl=*/0,
4926 SourceLocation(), true);
4927 }
4928
4929 return ObjCProtocolClassDecl;
4930}
4931
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004932void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004933 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004934 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004935
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004936 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004937}
4938
John McCall0bd6feb2009-12-02 08:04:21 +00004939/// \brief Retrieve the template name that corresponds to a non-empty
4940/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00004941TemplateName
4942ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4943 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00004944 unsigned size = End - Begin;
4945 assert(size > 1 && "set is not overloaded!");
4946
4947 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4948 size * sizeof(FunctionTemplateDecl*));
4949 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4950
4951 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004952 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004953 NamedDecl *D = *I;
4954 assert(isa<FunctionTemplateDecl>(D) ||
4955 (isa<UsingShadowDecl>(D) &&
4956 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4957 *Storage++ = D;
4958 }
4959
4960 return TemplateName(OT);
4961}
4962
Douglas Gregor7532dc62009-03-30 22:58:21 +00004963/// \brief Retrieve the template name that represents a qualified
4964/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00004965TemplateName
4966ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4967 bool TemplateKeyword,
4968 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00004969 assert(NNS && "Missing nested-name-specifier in qualified template name");
4970
Douglas Gregor789b1f62010-02-04 18:10:26 +00004971 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004972 llvm::FoldingSetNodeID ID;
4973 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4974
4975 void *InsertPos = 0;
4976 QualifiedTemplateName *QTN =
4977 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4978 if (!QTN) {
4979 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4980 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4981 }
4982
4983 return TemplateName(QTN);
4984}
4985
4986/// \brief Retrieve the template name that represents a dependent
4987/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00004988TemplateName
4989ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4990 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004991 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004992 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004993
4994 llvm::FoldingSetNodeID ID;
4995 DependentTemplateName::Profile(ID, NNS, Name);
4996
4997 void *InsertPos = 0;
4998 DependentTemplateName *QTN =
4999 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5000
5001 if (QTN)
5002 return TemplateName(QTN);
5003
5004 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5005 if (CanonNNS == NNS) {
5006 QTN = new (*this,4) DependentTemplateName(NNS, Name);
5007 } else {
5008 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5009 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005010 DependentTemplateName *CheckQTN =
5011 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5012 assert(!CheckQTN && "Dependent type name canonicalization broken");
5013 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00005014 }
5015
5016 DependentTemplateNames.InsertNode(QTN, InsertPos);
5017 return TemplateName(QTN);
5018}
5019
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005020/// \brief Retrieve the template name that represents a dependent
5021/// template name such as \c MetaFun::template operator+.
5022TemplateName
5023ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00005024 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005025 assert((!NNS || NNS->isDependent()) &&
5026 "Nested name specifier must be dependent");
5027
5028 llvm::FoldingSetNodeID ID;
5029 DependentTemplateName::Profile(ID, NNS, Operator);
5030
5031 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00005032 DependentTemplateName *QTN
5033 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005034
5035 if (QTN)
5036 return TemplateName(QTN);
5037
5038 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5039 if (CanonNNS == NNS) {
5040 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5041 } else {
5042 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5043 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005044
5045 DependentTemplateName *CheckQTN
5046 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5047 assert(!CheckQTN && "Dependent template name canonicalization broken");
5048 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005049 }
5050
5051 DependentTemplateNames.InsertNode(QTN, InsertPos);
5052 return TemplateName(QTN);
5053}
5054
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005055TemplateName
John McCall14606042011-06-30 08:33:18 +00005056ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5057 TemplateName replacement) const {
5058 llvm::FoldingSetNodeID ID;
5059 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5060
5061 void *insertPos = 0;
5062 SubstTemplateTemplateParmStorage *subst
5063 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5064
5065 if (!subst) {
5066 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5067 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5068 }
5069
5070 return TemplateName(subst);
5071}
5072
5073TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005074ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5075 const TemplateArgument &ArgPack) const {
5076 ASTContext &Self = const_cast<ASTContext &>(*this);
5077 llvm::FoldingSetNodeID ID;
5078 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5079
5080 void *InsertPos = 0;
5081 SubstTemplateTemplateParmPackStorage *Subst
5082 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5083
5084 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00005085 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005086 ArgPack.pack_size(),
5087 ArgPack.pack_begin());
5088 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5089 }
5090
5091 return TemplateName(Subst);
5092}
5093
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005094/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00005095/// TargetInfo, produce the corresponding type. The unsigned @p Type
5096/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00005097CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005098 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00005099 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005100 case TargetInfo::SignedShort: return ShortTy;
5101 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5102 case TargetInfo::SignedInt: return IntTy;
5103 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5104 case TargetInfo::SignedLong: return LongTy;
5105 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5106 case TargetInfo::SignedLongLong: return LongLongTy;
5107 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5108 }
5109
David Blaikieb219cfc2011-09-23 05:06:16 +00005110 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005111}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00005112
5113//===----------------------------------------------------------------------===//
5114// Type Predicates.
5115//===----------------------------------------------------------------------===//
5116
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005117/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5118/// garbage collection attribute.
5119///
John McCallae278a32011-01-12 00:34:59 +00005120Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
Douglas Gregore289d812011-09-13 17:21:33 +00005121 if (getLangOptions().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00005122 return Qualifiers::GCNone;
5123
5124 assert(getLangOptions().ObjC1);
5125 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5126
5127 // Default behaviour under objective-C's gc is for ObjC pointers
5128 // (or pointers to them) be treated as though they were declared
5129 // as __strong.
5130 if (GCAttrs == Qualifiers::GCNone) {
5131 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5132 return Qualifiers::Strong;
5133 else if (Ty->isPointerType())
5134 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5135 } else {
5136 // It's not valid to set GC attributes on anything that isn't a
5137 // pointer.
5138#ifndef NDEBUG
5139 QualType CT = Ty->getCanonicalTypeInternal();
5140 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5141 CT = AT->getElementType();
5142 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5143#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005144 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00005145 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005146}
5147
Chris Lattner6ac46a42008-04-07 06:51:04 +00005148//===----------------------------------------------------------------------===//
5149// Type Compatibility Testing
5150//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00005151
Mike Stump1eb44332009-09-09 15:08:12 +00005152/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005153/// compatible.
5154static bool areCompatVectorTypes(const VectorType *LHS,
5155 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00005156 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00005157 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00005158 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00005159}
5160
Douglas Gregor255210e2010-08-06 10:14:59 +00005161bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5162 QualType SecondVec) {
5163 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5164 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5165
5166 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5167 return true;
5168
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005169 // Treat Neon vector types and most AltiVec vector types as if they are the
5170 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00005171 const VectorType *First = FirstVec->getAs<VectorType>();
5172 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005173 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00005174 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005175 First->getVectorKind() != VectorType::AltiVecPixel &&
5176 First->getVectorKind() != VectorType::AltiVecBool &&
5177 Second->getVectorKind() != VectorType::AltiVecPixel &&
5178 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00005179 return true;
5180
5181 return false;
5182}
5183
Steve Naroff4084c302009-07-23 01:01:38 +00005184//===----------------------------------------------------------------------===//
5185// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5186//===----------------------------------------------------------------------===//
5187
5188/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5189/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00005190bool
5191ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5192 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005193 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00005194 return true;
5195 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5196 E = rProto->protocol_end(); PI != E; ++PI)
5197 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5198 return true;
5199 return false;
5200}
5201
Steve Naroff4084c302009-07-23 01:01:38 +00005202/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5203/// return true if lhs's protocols conform to rhs's protocol; false
5204/// otherwise.
5205bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5206 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5207 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5208 return false;
5209}
5210
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005211/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5212/// Class<p1, ...>.
5213bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5214 QualType rhs) {
5215 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5216 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5217 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5218
5219 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5220 E = lhsQID->qual_end(); I != E; ++I) {
5221 bool match = false;
5222 ObjCProtocolDecl *lhsProto = *I;
5223 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5224 E = rhsOPT->qual_end(); J != E; ++J) {
5225 ObjCProtocolDecl *rhsProto = *J;
5226 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5227 match = true;
5228 break;
5229 }
5230 }
5231 if (!match)
5232 return false;
5233 }
5234 return true;
5235}
5236
Steve Naroff4084c302009-07-23 01:01:38 +00005237/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5238/// ObjCQualifiedIDType.
5239bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5240 bool compare) {
5241 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00005242 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005243 lhs->isObjCIdType() || lhs->isObjCClassType())
5244 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005245 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005246 rhs->isObjCIdType() || rhs->isObjCClassType())
5247 return true;
5248
5249 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00005250 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005251
Steve Naroff4084c302009-07-23 01:01:38 +00005252 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005253
Steve Naroff4084c302009-07-23 01:01:38 +00005254 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005255 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00005256 // make sure we check the class hierarchy.
5257 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5258 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5259 E = lhsQID->qual_end(); I != E; ++I) {
5260 // when comparing an id<P> on lhs with a static type on rhs,
5261 // see if static class implements all of id's protocols, directly or
5262 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005263 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00005264 return false;
5265 }
5266 }
5267 // If there are no qualifiers and no interface, we have an 'id'.
5268 return true;
5269 }
Mike Stump1eb44332009-09-09 15:08:12 +00005270 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005271 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5272 E = lhsQID->qual_end(); I != E; ++I) {
5273 ObjCProtocolDecl *lhsProto = *I;
5274 bool match = false;
5275
5276 // when comparing an id<P> on lhs with a static type on rhs,
5277 // see if static class implements all of id's protocols, directly or
5278 // through its super class and categories.
5279 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5280 E = rhsOPT->qual_end(); J != E; ++J) {
5281 ObjCProtocolDecl *rhsProto = *J;
5282 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5283 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5284 match = true;
5285 break;
5286 }
5287 }
Mike Stump1eb44332009-09-09 15:08:12 +00005288 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00005289 // make sure we check the class hierarchy.
5290 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5291 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5292 E = lhsQID->qual_end(); I != E; ++I) {
5293 // when comparing an id<P> on lhs with a static type on rhs,
5294 // see if static class implements all of id's protocols, directly or
5295 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005296 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00005297 match = true;
5298 break;
5299 }
5300 }
5301 }
5302 if (!match)
5303 return false;
5304 }
Mike Stump1eb44332009-09-09 15:08:12 +00005305
Steve Naroff4084c302009-07-23 01:01:38 +00005306 return true;
5307 }
Mike Stump1eb44332009-09-09 15:08:12 +00005308
Steve Naroff4084c302009-07-23 01:01:38 +00005309 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5310 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5311
Mike Stump1eb44332009-09-09 15:08:12 +00005312 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00005313 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005314 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005315 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5316 E = lhsOPT->qual_end(); I != E; ++I) {
5317 ObjCProtocolDecl *lhsProto = *I;
5318 bool match = false;
5319
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005320 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00005321 // see if static class implements all of id's protocols, directly or
5322 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005323 // First, lhs protocols in the qualifier list must be found, direct
5324 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00005325 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5326 E = rhsQID->qual_end(); J != E; ++J) {
5327 ObjCProtocolDecl *rhsProto = *J;
5328 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5329 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5330 match = true;
5331 break;
5332 }
5333 }
5334 if (!match)
5335 return false;
5336 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005337
5338 // Static class's protocols, or its super class or category protocols
5339 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5340 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5341 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5342 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5343 // This is rather dubious but matches gcc's behavior. If lhs has
5344 // no type qualifier and its class has no static protocol(s)
5345 // assume that it is mismatch.
5346 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5347 return false;
5348 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5349 LHSInheritedProtocols.begin(),
5350 E = LHSInheritedProtocols.end(); I != E; ++I) {
5351 bool match = false;
5352 ObjCProtocolDecl *lhsProto = (*I);
5353 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5354 E = rhsQID->qual_end(); J != E; ++J) {
5355 ObjCProtocolDecl *rhsProto = *J;
5356 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5357 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5358 match = true;
5359 break;
5360 }
5361 }
5362 if (!match)
5363 return false;
5364 }
5365 }
Steve Naroff4084c302009-07-23 01:01:38 +00005366 return true;
5367 }
5368 return false;
5369}
5370
Eli Friedman3d815e72008-08-22 00:56:42 +00005371/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005372/// compatible for assignment from RHS to LHS. This handles validation of any
5373/// protocol qualifiers on the LHS or RHS.
5374///
Steve Naroff14108da2009-07-10 23:34:53 +00005375bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5376 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00005377 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5378 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5379
Steve Naroffde2e22d2009-07-15 18:40:39 +00005380 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00005381 if (LHS->isObjCUnqualifiedIdOrClass() ||
5382 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00005383 return true;
5384
John McCallc12c5bb2010-05-15 11:32:37 +00005385 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00005386 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5387 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00005388 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005389
5390 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5391 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5392 QualType(RHSOPT,0));
5393
John McCallc12c5bb2010-05-15 11:32:37 +00005394 // If we have 2 user-defined types, fall into that path.
5395 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00005396 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00005397
Steve Naroff4084c302009-07-23 01:01:38 +00005398 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005399}
5400
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005401/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00005402/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005403/// arguments in block literals. When passed as arguments, passing 'A*' where
5404/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5405/// not OK. For the return type, the opposite is not OK.
5406bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5407 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005408 const ObjCObjectPointerType *RHSOPT,
5409 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005410 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005411 return true;
5412
5413 if (LHSOPT->isObjCBuiltinType()) {
5414 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5415 }
5416
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005417 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005418 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5419 QualType(RHSOPT,0),
5420 false);
5421
5422 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5423 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5424 if (LHS && RHS) { // We have 2 user-defined types.
5425 if (LHS != RHS) {
5426 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005427 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005428 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005429 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005430 }
5431 else
5432 return true;
5433 }
5434 return false;
5435}
5436
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005437/// getIntersectionOfProtocols - This routine finds the intersection of set
5438/// of protocols inherited from two distinct objective-c pointer objects.
5439/// It is used to build composite qualifier list of the composite type of
5440/// the conditional expression involving two objective-c pointer objects.
5441static
5442void getIntersectionOfProtocols(ASTContext &Context,
5443 const ObjCObjectPointerType *LHSOPT,
5444 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005445 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005446
John McCallc12c5bb2010-05-15 11:32:37 +00005447 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5448 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5449 assert(LHS->getInterface() && "LHS must have an interface base");
5450 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005451
5452 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5453 unsigned LHSNumProtocols = LHS->getNumProtocols();
5454 if (LHSNumProtocols > 0)
5455 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5456 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005457 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005458 Context.CollectInheritedProtocols(LHS->getInterface(),
5459 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005460 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5461 LHSInheritedProtocols.end());
5462 }
5463
5464 unsigned RHSNumProtocols = RHS->getNumProtocols();
5465 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00005466 ObjCProtocolDecl **RHSProtocols =
5467 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005468 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5469 if (InheritedProtocolSet.count(RHSProtocols[i]))
5470 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00005471 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005472 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005473 Context.CollectInheritedProtocols(RHS->getInterface(),
5474 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005475 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5476 RHSInheritedProtocols.begin(),
5477 E = RHSInheritedProtocols.end(); I != E; ++I)
5478 if (InheritedProtocolSet.count((*I)))
5479 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005480 }
5481}
5482
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005483/// areCommonBaseCompatible - Returns common base class of the two classes if
5484/// one found. Note that this is O'2 algorithm. But it will be called as the
5485/// last type comparison in a ?-exp of ObjC pointer types before a
5486/// warning is issued. So, its invokation is extremely rare.
5487QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00005488 const ObjCObjectPointerType *Lptr,
5489 const ObjCObjectPointerType *Rptr) {
5490 const ObjCObjectType *LHS = Lptr->getObjectType();
5491 const ObjCObjectType *RHS = Rptr->getObjectType();
5492 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5493 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00005494 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005495 return QualType();
5496
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005497 do {
John McCallc12c5bb2010-05-15 11:32:37 +00005498 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005499 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005500 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005501 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5502
5503 QualType Result = QualType(LHS, 0);
5504 if (!Protocols.empty())
5505 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5506 Result = getObjCObjectPointerType(Result);
5507 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005508 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005509 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005510
5511 return QualType();
5512}
5513
John McCallc12c5bb2010-05-15 11:32:37 +00005514bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5515 const ObjCObjectType *RHS) {
5516 assert(LHS->getInterface() && "LHS is not an interface type");
5517 assert(RHS->getInterface() && "RHS is not an interface type");
5518
Chris Lattner6ac46a42008-04-07 06:51:04 +00005519 // Verify that the base decls are compatible: the RHS must be a subclass of
5520 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00005521 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00005522 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005523
Chris Lattner6ac46a42008-04-07 06:51:04 +00005524 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5525 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00005526 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00005527 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005528
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005529 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5530 // more detailed analysis is required.
5531 if (RHS->getNumProtocols() == 0) {
5532 // OK, if LHS is a superclass of RHS *and*
5533 // this superclass is assignment compatible with LHS.
5534 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005535 bool IsSuperClass =
5536 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5537 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005538 // OK if conversion of LHS to SuperClass results in narrowing of types
5539 // ; i.e., SuperClass may implement at least one of the protocols
5540 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5541 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5542 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005543 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005544 // If super class has no protocols, it is not a match.
5545 if (SuperClassInheritedProtocols.empty())
5546 return false;
5547
5548 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5549 LHSPE = LHS->qual_end();
5550 LHSPI != LHSPE; LHSPI++) {
5551 bool SuperImplementsProtocol = false;
5552 ObjCProtocolDecl *LHSProto = (*LHSPI);
5553
5554 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5555 SuperClassInheritedProtocols.begin(),
5556 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5557 ObjCProtocolDecl *SuperClassProto = (*I);
5558 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5559 SuperImplementsProtocol = true;
5560 break;
5561 }
5562 }
5563 if (!SuperImplementsProtocol)
5564 return false;
5565 }
5566 return true;
5567 }
5568 return false;
5569 }
Mike Stump1eb44332009-09-09 15:08:12 +00005570
John McCallc12c5bb2010-05-15 11:32:37 +00005571 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5572 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005573 LHSPI != LHSPE; LHSPI++) {
5574 bool RHSImplementsProtocol = false;
5575
5576 // If the RHS doesn't implement the protocol on the left, the types
5577 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00005578 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5579 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00005580 RHSPI != RHSPE; RHSPI++) {
5581 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005582 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00005583 break;
5584 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005585 }
5586 // FIXME: For better diagnostics, consider passing back the protocol name.
5587 if (!RHSImplementsProtocol)
5588 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005589 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005590 // The RHS implements all protocols listed on the LHS.
5591 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005592}
5593
Steve Naroff389bf462009-02-12 17:52:19 +00005594bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5595 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00005596 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5597 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005598
Steve Naroff14108da2009-07-10 23:34:53 +00005599 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00005600 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005601
5602 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5603 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00005604}
5605
Douglas Gregor569c3162010-08-07 11:51:51 +00005606bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5607 return canAssignObjCInterfaces(
5608 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5609 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5610}
5611
Mike Stump1eb44332009-09-09 15:08:12 +00005612/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00005613/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00005614/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00005615/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00005616bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5617 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005618 if (getLangOptions().CPlusPlus)
5619 return hasSameType(LHS, RHS);
5620
Douglas Gregor447234d2010-07-29 15:18:02 +00005621 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00005622}
5623
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005624bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00005625 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005626}
5627
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005628bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5629 return !mergeTypes(LHS, RHS, true).isNull();
5630}
5631
Peter Collingbourne48466752010-10-24 18:30:18 +00005632/// mergeTransparentUnionType - if T is a transparent union type and a member
5633/// of T is compatible with SubType, return the merged type, else return
5634/// QualType()
5635QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5636 bool OfBlockPointer,
5637 bool Unqualified) {
5638 if (const RecordType *UT = T->getAsUnionType()) {
5639 RecordDecl *UD = UT->getDecl();
5640 if (UD->hasAttr<TransparentUnionAttr>()) {
5641 for (RecordDecl::field_iterator it = UD->field_begin(),
5642 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00005643 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005644 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5645 if (!MT.isNull())
5646 return MT;
5647 }
5648 }
5649 }
5650
5651 return QualType();
5652}
5653
5654/// mergeFunctionArgumentTypes - merge two types which appear as function
5655/// argument types
5656QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5657 bool OfBlockPointer,
5658 bool Unqualified) {
5659 // GNU extension: two types are compatible if they appear as a function
5660 // argument, one of the types is a transparent union type and the other
5661 // type is compatible with a union member
5662 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5663 Unqualified);
5664 if (!lmerge.isNull())
5665 return lmerge;
5666
5667 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5668 Unqualified);
5669 if (!rmerge.isNull())
5670 return rmerge;
5671
5672 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5673}
5674
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005675QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00005676 bool OfBlockPointer,
5677 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00005678 const FunctionType *lbase = lhs->getAs<FunctionType>();
5679 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00005680 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5681 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00005682 bool allLTypes = true;
5683 bool allRTypes = true;
5684
5685 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005686 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005687 if (OfBlockPointer) {
5688 QualType RHS = rbase->getResultType();
5689 QualType LHS = lbase->getResultType();
5690 bool UnqualifiedResult = Unqualified;
5691 if (!UnqualifiedResult)
5692 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005693 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005694 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005695 else
John McCall8cc246c2010-12-15 01:06:38 +00005696 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5697 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005698 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005699
5700 if (Unqualified)
5701 retType = retType.getUnqualifiedType();
5702
5703 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5704 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5705 if (Unqualified) {
5706 LRetType = LRetType.getUnqualifiedType();
5707 RRetType = RRetType.getUnqualifiedType();
5708 }
5709
5710 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005711 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00005712 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005713 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005714
Daniel Dunbar6a15c852010-04-28 16:20:58 +00005715 // FIXME: double check this
5716 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5717 // rbase->getRegParmAttr() != 0 &&
5718 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00005719 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5720 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00005721
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005722 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00005723 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005724 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005725
John McCall8cc246c2010-12-15 01:06:38 +00005726 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00005727 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5728 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00005729 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5730 return QualType();
5731
John McCallf85e1932011-06-15 23:02:42 +00005732 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5733 return QualType();
5734
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005735 // functypes which return are preferred over those that do not.
5736 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5737 allLTypes = false;
5738 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5739 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005740 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5741 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00005742
John McCallf85e1932011-06-15 23:02:42 +00005743 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00005744
Eli Friedman3d815e72008-08-22 00:56:42 +00005745 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00005746 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5747 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005748 unsigned lproto_nargs = lproto->getNumArgs();
5749 unsigned rproto_nargs = rproto->getNumArgs();
5750
5751 // Compatible functions must have the same number of arguments
5752 if (lproto_nargs != rproto_nargs)
5753 return QualType();
5754
5755 // Variadic and non-variadic functions aren't compatible
5756 if (lproto->isVariadic() != rproto->isVariadic())
5757 return QualType();
5758
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00005759 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5760 return QualType();
5761
Fariborz Jahanian78213e42011-09-28 21:52:05 +00005762 if (LangOpts.ObjCAutoRefCount &&
5763 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5764 return QualType();
5765
Eli Friedman3d815e72008-08-22 00:56:42 +00005766 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00005767 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00005768 for (unsigned i = 0; i < lproto_nargs; i++) {
5769 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5770 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005771 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5772 OfBlockPointer,
5773 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005774 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005775
5776 if (Unqualified)
5777 argtype = argtype.getUnqualifiedType();
5778
Eli Friedman3d815e72008-08-22 00:56:42 +00005779 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00005780 if (Unqualified) {
5781 largtype = largtype.getUnqualifiedType();
5782 rargtype = rargtype.getUnqualifiedType();
5783 }
5784
Chris Lattner61710852008-10-05 17:34:18 +00005785 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5786 allLTypes = false;
5787 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5788 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00005789 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00005790
Eli Friedman3d815e72008-08-22 00:56:42 +00005791 if (allLTypes) return lhs;
5792 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005793
5794 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5795 EPI.ExtInfo = einfo;
5796 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005797 }
5798
5799 if (lproto) allRTypes = false;
5800 if (rproto) allLTypes = false;
5801
Douglas Gregor72564e72009-02-26 23:50:07 +00005802 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00005803 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00005804 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005805 if (proto->isVariadic()) return QualType();
5806 // Check that the types are compatible with the types that
5807 // would result from default argument promotions (C99 6.7.5.3p15).
5808 // The only types actually affected are promotable integer
5809 // types and floats, which would be passed as a different
5810 // type depending on whether the prototype is visible.
5811 unsigned proto_nargs = proto->getNumArgs();
5812 for (unsigned i = 0; i < proto_nargs; ++i) {
5813 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00005814
5815 // Look at the promotion type of enum types, since that is the type used
5816 // to pass enum values.
5817 if (const EnumType *Enum = argTy->getAs<EnumType>())
5818 argTy = Enum->getDecl()->getPromotionType();
5819
Eli Friedman3d815e72008-08-22 00:56:42 +00005820 if (argTy->isPromotableIntegerType() ||
5821 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5822 return QualType();
5823 }
5824
5825 if (allLTypes) return lhs;
5826 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005827
5828 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5829 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00005830 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005831 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005832 }
5833
5834 if (allLTypes) return lhs;
5835 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00005836 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00005837}
5838
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005839QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00005840 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005841 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00005842 // C++ [expr]: If an expression initially has the type "reference to T", the
5843 // type is adjusted to "T" prior to any further analysis, the expression
5844 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005845 // expression is an lvalue unless the reference is an rvalue reference and
5846 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005847 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5848 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00005849
5850 if (Unqualified) {
5851 LHS = LHS.getUnqualifiedType();
5852 RHS = RHS.getUnqualifiedType();
5853 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005854
Eli Friedman3d815e72008-08-22 00:56:42 +00005855 QualType LHSCan = getCanonicalType(LHS),
5856 RHSCan = getCanonicalType(RHS);
5857
5858 // If two types are identical, they are compatible.
5859 if (LHSCan == RHSCan)
5860 return LHS;
5861
John McCall0953e762009-09-24 19:53:00 +00005862 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005863 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5864 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00005865 if (LQuals != RQuals) {
5866 // If any of these qualifiers are different, we have a type
5867 // mismatch.
5868 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00005869 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5870 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00005871 return QualType();
5872
5873 // Exactly one GC qualifier difference is allowed: __strong is
5874 // okay if the other type has no GC qualifier but is an Objective
5875 // C object pointer (i.e. implicitly strong by default). We fix
5876 // this by pretending that the unqualified type was actually
5877 // qualified __strong.
5878 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5879 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5880 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5881
5882 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5883 return QualType();
5884
5885 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5886 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5887 }
5888 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5889 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5890 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005891 return QualType();
John McCall0953e762009-09-24 19:53:00 +00005892 }
5893
5894 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00005895
Eli Friedman852d63b2009-06-01 01:22:52 +00005896 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5897 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00005898
Chris Lattner1adb8832008-01-14 05:45:46 +00005899 // We want to consider the two function types to be the same for these
5900 // comparisons, just force one to the other.
5901 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5902 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00005903
5904 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00005905 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5906 LHSClass = Type::ConstantArray;
5907 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5908 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00005909
John McCallc12c5bb2010-05-15 11:32:37 +00005910 // ObjCInterfaces are just specialized ObjCObjects.
5911 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5912 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5913
Nate Begeman213541a2008-04-18 23:10:10 +00005914 // Canonicalize ExtVector -> Vector.
5915 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5916 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00005917
Chris Lattnera36a61f2008-04-07 05:43:21 +00005918 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005919 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00005920 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00005921 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00005922 // Compatibility is based on the underlying type, not the promotion
5923 // type.
John McCall183700f2009-09-21 23:43:11 +00005924 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00005925 QualType TINT = ETy->getDecl()->getIntegerType();
5926 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005927 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005928 }
John McCall183700f2009-09-21 23:43:11 +00005929 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00005930 QualType TINT = ETy->getDecl()->getIntegerType();
5931 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005932 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005933 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00005934 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00005935 if (OfBlockPointer && !BlockReturnType) {
5936 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
5937 return LHS;
5938 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
5939 return RHS;
5940 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00005941
Eli Friedman3d815e72008-08-22 00:56:42 +00005942 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005943 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005944
Steve Naroff4a746782008-01-09 22:43:08 +00005945 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005946 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00005947#define TYPE(Class, Base)
5948#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00005949#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00005950#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5951#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5952#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00005953 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00005954
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005955 case Type::LValueReference:
5956 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00005957 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00005958 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00005959
John McCallc12c5bb2010-05-15 11:32:37 +00005960 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00005961 case Type::IncompleteArray:
5962 case Type::VariableArray:
5963 case Type::FunctionProto:
5964 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00005965 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00005966
Chris Lattner1adb8832008-01-14 05:45:46 +00005967 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00005968 {
5969 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005970 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5971 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005972 if (Unqualified) {
5973 LHSPointee = LHSPointee.getUnqualifiedType();
5974 RHSPointee = RHSPointee.getUnqualifiedType();
5975 }
5976 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5977 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005978 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00005979 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005980 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00005981 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005982 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005983 return getPointerType(ResultType);
5984 }
Steve Naroffc0febd52008-12-10 17:49:55 +00005985 case Type::BlockPointer:
5986 {
5987 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005988 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5989 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005990 if (Unqualified) {
5991 LHSPointee = LHSPointee.getUnqualifiedType();
5992 RHSPointee = RHSPointee.getUnqualifiedType();
5993 }
5994 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5995 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00005996 if (ResultType.isNull()) return QualType();
5997 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5998 return LHS;
5999 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6000 return RHS;
6001 return getBlockPointerType(ResultType);
6002 }
Eli Friedmanb001de72011-10-06 23:00:33 +00006003 case Type::Atomic:
6004 {
6005 // Merge two pointer types, while trying to preserve typedef info
6006 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6007 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6008 if (Unqualified) {
6009 LHSValue = LHSValue.getUnqualifiedType();
6010 RHSValue = RHSValue.getUnqualifiedType();
6011 }
6012 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6013 Unqualified);
6014 if (ResultType.isNull()) return QualType();
6015 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6016 return LHS;
6017 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6018 return RHS;
6019 return getAtomicType(ResultType);
6020 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006021 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00006022 {
6023 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6024 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6025 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6026 return QualType();
6027
6028 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6029 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006030 if (Unqualified) {
6031 LHSElem = LHSElem.getUnqualifiedType();
6032 RHSElem = RHSElem.getUnqualifiedType();
6033 }
6034
6035 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006036 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00006037 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6038 return LHS;
6039 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6040 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00006041 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6042 ArrayType::ArraySizeModifier(), 0);
6043 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6044 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006045 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6046 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00006047 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6048 return LHS;
6049 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6050 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006051 if (LVAT) {
6052 // FIXME: This isn't correct! But tricky to implement because
6053 // the array's size has to be the size of LHS, but the type
6054 // has to be different.
6055 return LHS;
6056 }
6057 if (RVAT) {
6058 // FIXME: This isn't correct! But tricky to implement because
6059 // the array's size has to be the size of RHS, but the type
6060 // has to be different.
6061 return RHS;
6062 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00006063 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6064 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00006065 return getIncompleteArrayType(ResultType,
6066 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006067 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006068 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00006069 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00006070 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00006071 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00006072 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00006073 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006074 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00006075 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00006076 case Type::Complex:
6077 // Distinct complex types are incompatible.
6078 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006079 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006080 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00006081 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6082 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006083 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00006084 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00006085 case Type::ObjCObject: {
6086 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006087 // FIXME: This should be type compatibility, e.g. whether
6088 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00006089 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6090 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6091 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00006092 return LHS;
6093
Eli Friedman3d815e72008-08-22 00:56:42 +00006094 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00006095 }
Steve Naroff14108da2009-07-10 23:34:53 +00006096 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006097 if (OfBlockPointer) {
6098 if (canAssignObjCInterfacesInBlockPointer(
6099 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006100 RHS->getAs<ObjCObjectPointerType>(),
6101 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00006102 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006103 return QualType();
6104 }
John McCall183700f2009-09-21 23:43:11 +00006105 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6106 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00006107 return LHS;
6108
Steve Naroffbc76dd02008-12-10 22:14:21 +00006109 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00006110 }
Steve Naroffec0550f2007-10-15 20:41:53 +00006111 }
Douglas Gregor72564e72009-02-26 23:50:07 +00006112
David Blaikie7530c032012-01-17 06:56:22 +00006113 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00006114}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00006115
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006116bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6117 const FunctionProtoType *FromFunctionType,
6118 const FunctionProtoType *ToFunctionType) {
6119 if (FromFunctionType->hasAnyConsumedArgs() !=
6120 ToFunctionType->hasAnyConsumedArgs())
6121 return false;
6122 FunctionProtoType::ExtProtoInfo FromEPI =
6123 FromFunctionType->getExtProtoInfo();
6124 FunctionProtoType::ExtProtoInfo ToEPI =
6125 ToFunctionType->getExtProtoInfo();
6126 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6127 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6128 ArgIdx != NumArgs; ++ArgIdx) {
6129 if (FromEPI.ConsumedArguments[ArgIdx] !=
6130 ToEPI.ConsumedArguments[ArgIdx])
6131 return false;
6132 }
6133 return true;
6134}
6135
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006136/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6137/// 'RHS' attributes and returns the merged version; including for function
6138/// return types.
6139QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6140 QualType LHSCan = getCanonicalType(LHS),
6141 RHSCan = getCanonicalType(RHS);
6142 // If two types are identical, they are compatible.
6143 if (LHSCan == RHSCan)
6144 return LHS;
6145 if (RHSCan->isFunctionType()) {
6146 if (!LHSCan->isFunctionType())
6147 return QualType();
6148 QualType OldReturnType =
6149 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6150 QualType NewReturnType =
6151 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6152 QualType ResReturnType =
6153 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6154 if (ResReturnType.isNull())
6155 return QualType();
6156 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6157 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6158 // In either case, use OldReturnType to build the new function type.
6159 const FunctionType *F = LHS->getAs<FunctionType>();
6160 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00006161 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6162 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006163 QualType ResultType
6164 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006165 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006166 return ResultType;
6167 }
6168 }
6169 return QualType();
6170 }
6171
6172 // If the qualifiers are different, the types can still be merged.
6173 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6174 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6175 if (LQuals != RQuals) {
6176 // If any of these qualifiers are different, we have a type mismatch.
6177 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6178 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6179 return QualType();
6180
6181 // Exactly one GC qualifier difference is allowed: __strong is
6182 // okay if the other type has no GC qualifier but is an Objective
6183 // C object pointer (i.e. implicitly strong by default). We fix
6184 // this by pretending that the unqualified type was actually
6185 // qualified __strong.
6186 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6187 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6188 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6189
6190 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6191 return QualType();
6192
6193 if (GC_L == Qualifiers::Strong)
6194 return LHS;
6195 if (GC_R == Qualifiers::Strong)
6196 return RHS;
6197 return QualType();
6198 }
6199
6200 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6201 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6202 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6203 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6204 if (ResQT == LHSBaseQT)
6205 return LHS;
6206 if (ResQT == RHSBaseQT)
6207 return RHS;
6208 }
6209 return QualType();
6210}
6211
Chris Lattner5426bf62008-04-07 07:01:58 +00006212//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00006213// Integer Predicates
6214//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00006215
Jay Foad4ba2a172011-01-12 09:06:06 +00006216unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00006217 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00006218 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006219 if (T->isBooleanType())
6220 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00006221 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00006222 return (unsigned)getTypeSize(T);
6223}
6224
6225QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00006226 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00006227
6228 // Turn <4 x signed int> -> <4 x unsigned int>
6229 if (const VectorType *VTy = T->getAs<VectorType>())
6230 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00006231 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00006232
6233 // For enums, we return the unsigned version of the base type.
6234 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00006235 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00006236
6237 const BuiltinType *BTy = T->getAs<BuiltinType>();
6238 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006239 switch (BTy->getKind()) {
6240 case BuiltinType::Char_S:
6241 case BuiltinType::SChar:
6242 return UnsignedCharTy;
6243 case BuiltinType::Short:
6244 return UnsignedShortTy;
6245 case BuiltinType::Int:
6246 return UnsignedIntTy;
6247 case BuiltinType::Long:
6248 return UnsignedLongTy;
6249 case BuiltinType::LongLong:
6250 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00006251 case BuiltinType::Int128:
6252 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00006253 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00006254 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006255 }
6256}
6257
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00006258ASTMutationListener::~ASTMutationListener() { }
6259
Chris Lattner86df27b2009-06-14 00:45:47 +00006260
6261//===----------------------------------------------------------------------===//
6262// Builtin Type Computation
6263//===----------------------------------------------------------------------===//
6264
6265/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00006266/// pointer over the consumed characters. This returns the resultant type. If
6267/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6268/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6269/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00006270///
6271/// RequiresICE is filled in on return to indicate whether the value is required
6272/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00006273static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00006274 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00006275 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00006276 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00006277 // Modifiers.
6278 int HowLong = 0;
6279 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00006280 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006281
Chris Lattner33daae62010-10-01 22:42:38 +00006282 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00006283 bool Done = false;
6284 while (!Done) {
6285 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00006286 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006287 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00006288 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006289 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006290 case 'S':
6291 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6292 assert(!Signed && "Can't use 'S' modifier multiple times!");
6293 Signed = true;
6294 break;
6295 case 'U':
6296 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6297 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6298 Unsigned = true;
6299 break;
6300 case 'L':
6301 assert(HowLong <= 2 && "Can't have LLLL modifier");
6302 ++HowLong;
6303 break;
6304 }
6305 }
6306
6307 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00006308
Chris Lattner86df27b2009-06-14 00:45:47 +00006309 // Read the base type.
6310 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00006311 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00006312 case 'v':
6313 assert(HowLong == 0 && !Signed && !Unsigned &&
6314 "Bad modifiers used with 'v'!");
6315 Type = Context.VoidTy;
6316 break;
6317 case 'f':
6318 assert(HowLong == 0 && !Signed && !Unsigned &&
6319 "Bad modifiers used with 'f'!");
6320 Type = Context.FloatTy;
6321 break;
6322 case 'd':
6323 assert(HowLong < 2 && !Signed && !Unsigned &&
6324 "Bad modifiers used with 'd'!");
6325 if (HowLong)
6326 Type = Context.LongDoubleTy;
6327 else
6328 Type = Context.DoubleTy;
6329 break;
6330 case 's':
6331 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6332 if (Unsigned)
6333 Type = Context.UnsignedShortTy;
6334 else
6335 Type = Context.ShortTy;
6336 break;
6337 case 'i':
6338 if (HowLong == 3)
6339 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6340 else if (HowLong == 2)
6341 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6342 else if (HowLong == 1)
6343 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6344 else
6345 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6346 break;
6347 case 'c':
6348 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6349 if (Signed)
6350 Type = Context.SignedCharTy;
6351 else if (Unsigned)
6352 Type = Context.UnsignedCharTy;
6353 else
6354 Type = Context.CharTy;
6355 break;
6356 case 'b': // boolean
6357 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6358 Type = Context.BoolTy;
6359 break;
6360 case 'z': // size_t.
6361 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6362 Type = Context.getSizeType();
6363 break;
6364 case 'F':
6365 Type = Context.getCFConstantStringType();
6366 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00006367 case 'G':
6368 Type = Context.getObjCIdType();
6369 break;
6370 case 'H':
6371 Type = Context.getObjCSelType();
6372 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006373 case 'a':
6374 Type = Context.getBuiltinVaListType();
6375 assert(!Type.isNull() && "builtin va list type not initialized!");
6376 break;
6377 case 'A':
6378 // This is a "reference" to a va_list; however, what exactly
6379 // this means depends on how va_list is defined. There are two
6380 // different kinds of va_list: ones passed by value, and ones
6381 // passed by reference. An example of a by-value va_list is
6382 // x86, where va_list is a char*. An example of by-ref va_list
6383 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6384 // we want this argument to be a char*&; for x86-64, we want
6385 // it to be a __va_list_tag*.
6386 Type = Context.getBuiltinVaListType();
6387 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00006388 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00006389 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00006390 else
Chris Lattner86df27b2009-06-14 00:45:47 +00006391 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00006392 break;
6393 case 'V': {
6394 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00006395 unsigned NumElements = strtoul(Str, &End, 10);
6396 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00006397 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00006398
Chris Lattner14e0e742010-10-01 22:53:11 +00006399 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6400 RequiresICE, false);
6401 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00006402
6403 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00006404 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00006405 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00006406 break;
6407 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00006408 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00006409 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6410 false);
6411 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00006412 Type = Context.getComplexType(ElementType);
6413 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00006414 }
6415 case 'Y' : {
6416 Type = Context.getPointerDiffType();
6417 break;
6418 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006419 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00006420 Type = Context.getFILEType();
6421 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006422 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00006423 return QualType();
6424 }
Mike Stumpfd612db2009-07-28 23:47:15 +00006425 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006426 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00006427 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00006428 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00006429 else
6430 Type = Context.getjmp_bufType();
6431
Mike Stumpfd612db2009-07-28 23:47:15 +00006432 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006433 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00006434 return QualType();
6435 }
6436 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00006437 case 'K':
6438 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6439 Type = Context.getucontext_tType();
6440
6441 if (Type.isNull()) {
6442 Error = ASTContext::GE_Missing_ucontext;
6443 return QualType();
6444 }
6445 break;
Mike Stump782fa302009-07-28 02:25:19 +00006446 }
Mike Stump1eb44332009-09-09 15:08:12 +00006447
Chris Lattner33daae62010-10-01 22:42:38 +00006448 // If there are modifiers and if we're allowed to parse them, go for it.
6449 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00006450 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00006451 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00006452 default: Done = true; --Str; break;
6453 case '*':
6454 case '&': {
6455 // Both pointers and references can have their pointee types
6456 // qualified with an address space.
6457 char *End;
6458 unsigned AddrSpace = strtoul(Str, &End, 10);
6459 if (End != Str && AddrSpace != 0) {
6460 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6461 Str = End;
6462 }
6463 if (c == '*')
6464 Type = Context.getPointerType(Type);
6465 else
6466 Type = Context.getLValueReferenceType(Type);
6467 break;
6468 }
6469 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6470 case 'C':
6471 Type = Type.withConst();
6472 break;
6473 case 'D':
6474 Type = Context.getVolatileType(Type);
6475 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00006476 case 'R':
6477 Type = Type.withRestrict();
6478 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006479 }
6480 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00006481
Chris Lattner14e0e742010-10-01 22:53:11 +00006482 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00006483 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00006484
Chris Lattner86df27b2009-06-14 00:45:47 +00006485 return Type;
6486}
6487
6488/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00006489QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00006490 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00006491 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00006492 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00006493
Chris Lattner5f9e2722011-07-23 10:55:15 +00006494 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00006495
Chris Lattner14e0e742010-10-01 22:53:11 +00006496 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00006497 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00006498 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6499 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006500 if (Error != GE_None)
6501 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00006502
6503 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6504
Chris Lattner86df27b2009-06-14 00:45:47 +00006505 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00006506 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006507 if (Error != GE_None)
6508 return QualType();
6509
Chris Lattner14e0e742010-10-01 22:53:11 +00006510 // If this argument is required to be an IntegerConstantExpression and the
6511 // caller cares, fill in the bitmask we return.
6512 if (RequiresICE && IntegerConstantArgs)
6513 *IntegerConstantArgs |= 1 << ArgTypes.size();
6514
Chris Lattner86df27b2009-06-14 00:45:47 +00006515 // Do array -> pointer decay. The builtin should use the decayed type.
6516 if (Ty->isArrayType())
6517 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00006518
Chris Lattner86df27b2009-06-14 00:45:47 +00006519 ArgTypes.push_back(Ty);
6520 }
6521
6522 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6523 "'.' should only occur at end of builtin type list!");
6524
John McCall00ccbef2010-12-21 00:44:39 +00006525 FunctionType::ExtInfo EI;
6526 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6527
6528 bool Variadic = (TypeStr[0] == '.');
6529
6530 // We really shouldn't be making a no-proto type here, especially in C++.
6531 if (ArgTypes.empty() && Variadic)
6532 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00006533
John McCalle23cf432010-12-14 08:05:40 +00006534 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00006535 EPI.ExtInfo = EI;
6536 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00006537
6538 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00006539}
Eli Friedmana95d7572009-08-19 07:44:53 +00006540
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006541GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6542 GVALinkage External = GVA_StrongExternal;
6543
6544 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006545 switch (L) {
6546 case NoLinkage:
6547 case InternalLinkage:
6548 case UniqueExternalLinkage:
6549 return GVA_Internal;
6550
6551 case ExternalLinkage:
6552 switch (FD->getTemplateSpecializationKind()) {
6553 case TSK_Undeclared:
6554 case TSK_ExplicitSpecialization:
6555 External = GVA_StrongExternal;
6556 break;
6557
6558 case TSK_ExplicitInstantiationDefinition:
6559 return GVA_ExplicitTemplateInstantiation;
6560
6561 case TSK_ExplicitInstantiationDeclaration:
6562 case TSK_ImplicitInstantiation:
6563 External = GVA_TemplateInstantiation;
6564 break;
6565 }
6566 }
6567
6568 if (!FD->isInlined())
6569 return External;
6570
6571 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6572 // GNU or C99 inline semantics. Determine whether this symbol should be
6573 // externally visible.
6574 if (FD->isInlineDefinitionExternallyVisible())
6575 return External;
6576
6577 // C99 inline semantics, where the symbol is not externally visible.
6578 return GVA_C99Inline;
6579 }
6580
6581 // C++0x [temp.explicit]p9:
6582 // [ Note: The intent is that an inline function that is the subject of
6583 // an explicit instantiation declaration will still be implicitly
6584 // instantiated when used so that the body can be considered for
6585 // inlining, but that no out-of-line copy of the inline function would be
6586 // generated in the translation unit. -- end note ]
6587 if (FD->getTemplateSpecializationKind()
6588 == TSK_ExplicitInstantiationDeclaration)
6589 return GVA_C99Inline;
6590
6591 return GVA_CXXInline;
6592}
6593
6594GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6595 // If this is a static data member, compute the kind of template
6596 // specialization. Otherwise, this variable is not part of a
6597 // template.
6598 TemplateSpecializationKind TSK = TSK_Undeclared;
6599 if (VD->isStaticDataMember())
6600 TSK = VD->getTemplateSpecializationKind();
6601
6602 Linkage L = VD->getLinkage();
6603 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6604 VD->getType()->getLinkage() == UniqueExternalLinkage)
6605 L = UniqueExternalLinkage;
6606
6607 switch (L) {
6608 case NoLinkage:
6609 case InternalLinkage:
6610 case UniqueExternalLinkage:
6611 return GVA_Internal;
6612
6613 case ExternalLinkage:
6614 switch (TSK) {
6615 case TSK_Undeclared:
6616 case TSK_ExplicitSpecialization:
6617 return GVA_StrongExternal;
6618
6619 case TSK_ExplicitInstantiationDeclaration:
6620 llvm_unreachable("Variable should not be instantiated");
6621 // Fall through to treat this like any other instantiation.
6622
6623 case TSK_ExplicitInstantiationDefinition:
6624 return GVA_ExplicitTemplateInstantiation;
6625
6626 case TSK_ImplicitInstantiation:
6627 return GVA_TemplateInstantiation;
6628 }
6629 }
6630
David Blaikie7530c032012-01-17 06:56:22 +00006631 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006632}
6633
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00006634bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006635 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6636 if (!VD->isFileVarDecl())
6637 return false;
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00006638 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006639 return false;
6640
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006641 // Weak references don't produce any output by themselves.
6642 if (D->hasAttr<WeakRefAttr>())
6643 return false;
6644
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006645 // Aliases and used decls are required.
6646 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6647 return true;
6648
6649 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6650 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00006651 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00006652 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006653
6654 // Constructors and destructors are required.
6655 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6656 return true;
6657
6658 // The key function for a class is required.
6659 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6660 const CXXRecordDecl *RD = MD->getParent();
6661 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6662 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6663 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6664 return true;
6665 }
6666 }
6667
6668 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6669
6670 // static, static inline, always_inline, and extern inline functions can
6671 // always be deferred. Normal inline functions can be deferred in C99/C++.
6672 // Implicit template instantiations can also be deferred in C++.
6673 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00006674 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006675 return false;
6676 return true;
6677 }
Douglas Gregor94da1582011-09-10 00:22:34 +00006678
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006679 const VarDecl *VD = cast<VarDecl>(D);
6680 assert(VD->isFileVarDecl() && "Expected file scoped var");
6681
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006682 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6683 return false;
6684
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006685 // Structs that have non-trivial constructors or destructors are required.
6686
6687 // FIXME: Handle references.
Sean Hunt023df372011-05-09 18:22:59 +00006688 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006689 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6690 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Sean Hunt023df372011-05-09 18:22:59 +00006691 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6692 RD->hasTrivialCopyConstructor() &&
6693 RD->hasTrivialMoveConstructor() &&
6694 RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006695 return true;
6696 }
6697 }
6698
6699 GVALinkage L = GetGVALinkageForVariable(VD);
6700 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6701 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6702 return false;
6703 }
6704
6705 return true;
6706}
Charles Davis071cc7d2010-08-16 03:33:14 +00006707
Charles Davisee743f92010-11-09 18:04:24 +00006708CallingConv ASTContext::getDefaultMethodCallConv() {
6709 // Pass through to the C++ ABI object
6710 return ABI->getDefaultMethodCallConv();
6711}
6712
Jay Foad4ba2a172011-01-12 09:06:06 +00006713bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00006714 // Pass through to the C++ ABI object
6715 return ABI->isNearlyEmpty(RD);
6716}
6717
Peter Collingbourne14110472011-01-13 18:57:25 +00006718MangleContext *ASTContext::createMangleContext() {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00006719 switch (Target->getCXXABI()) {
Peter Collingbourne14110472011-01-13 18:57:25 +00006720 case CXXABI_ARM:
6721 case CXXABI_Itanium:
6722 return createItaniumMangleContext(*this, getDiagnostics());
6723 case CXXABI_Microsoft:
6724 return createMicrosoftMangleContext(*this, getDiagnostics());
6725 }
David Blaikieb219cfc2011-09-23 05:06:16 +00006726 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00006727}
6728
Charles Davis071cc7d2010-08-16 03:33:14 +00006729CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00006730
6731size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00006732 return ASTRecordLayouts.getMemorySize()
6733 + llvm::capacity_in_bytes(ObjCLayouts)
6734 + llvm::capacity_in_bytes(KeyFunctions)
6735 + llvm::capacity_in_bytes(ObjCImpls)
6736 + llvm::capacity_in_bytes(BlockVarCopyInits)
6737 + llvm::capacity_in_bytes(DeclAttrs)
6738 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6739 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6740 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6741 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6742 + llvm::capacity_in_bytes(OverriddenMethods)
6743 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00006744 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00006745 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00006746}
Ted Kremenekd211cb72011-10-06 05:00:56 +00006747
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00006748unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
6749 CXXRecordDecl *Lambda = CallOperator->getParent();
6750 return LambdaMangleContexts[Lambda->getDeclContext()]
6751 .getManglingNumber(CallOperator);
6752}
6753
6754
Ted Kremenekd211cb72011-10-06 05:00:56 +00006755void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6756 ParamIndices[D] = index;
6757}
6758
6759unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6760 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6761 assert(I != ParamIndices.end() &&
6762 "ParmIndices lacks entry set by ParmVarDecl");
6763 return I->second;
6764}