blob: bd68d8325009bd6103d8e14fa181dadd956359ff [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
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +0000209 3, // opencl_constant
210 4, // cuda_device
211 5, // cuda_constant
212 6 // cuda_shared
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000213 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000214 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000215 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000216 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000217 }
218}
219
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000220ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000221 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000222 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000223 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000224 unsigned size_reserve,
225 bool DelayInitialization)
226 : FunctionProtoTypes(this_()),
227 TemplateSpecializationTypes(this_()),
228 DependentTemplateSpecializationTypes(this_()),
229 SubstTemplateTemplateParmPacks(this_()),
230 GlobalNestedNameSpecifier(0),
231 Int128Decl(0), UInt128Decl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000232 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000233 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000234 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000235 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
236 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
237 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000238 NullTypeSourceInfo(QualType()),
239 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000240 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000241 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000242 Idents(idents), Selectors(sels),
243 BuiltinInfo(builtins),
244 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000245 ExternalSource(0), Listener(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000246 LastSDM(0, 0),
247 UniqueBlockByRefTypeID(0)
248{
Mike Stump1eb44332009-09-09 15:08:12 +0000249 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000250 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000251
252 if (!DelayInitialization) {
253 assert(t && "No target supplied for ASTContext initialization");
254 InitBuiltinTypes(*t);
255 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000256}
257
Reid Spencer5f016e22007-07-11 17:01:13 +0000258ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000259 // Release the DenseMaps associated with DeclContext objects.
260 // FIXME: Is this the ideal solution?
261 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000262
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000263 // Call all of the deallocation functions.
264 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
265 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000266
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000267 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000268 // because they can contain DenseMaps.
269 for (llvm::DenseMap<const ObjCContainerDecl*,
270 const ASTRecordLayout*>::iterator
271 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
272 // Increment in loop to prevent using deallocated memory.
273 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
274 R->Destroy(*this);
275
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000276 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
277 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
278 // Increment in loop to prevent using deallocated memory.
279 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
280 R->Destroy(*this);
281 }
Douglas Gregor63200642010-08-30 16:49:28 +0000282
283 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
284 AEnd = DeclAttrs.end();
285 A != AEnd; ++A)
286 A->second->~AttrVec();
287}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000288
Douglas Gregor00545312010-05-23 18:26:36 +0000289void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
290 Deallocations.push_back(std::make_pair(Callback, Data));
291}
292
Mike Stump1eb44332009-09-09 15:08:12 +0000293void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000294ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000295 ExternalSource.reset(Source.take());
296}
297
Reid Spencer5f016e22007-07-11 17:01:13 +0000298void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000299 llvm::errs() << "\n*** AST Context Stats:\n";
300 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000301
Douglas Gregordbe833d2009-05-26 14:40:08 +0000302 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000303#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000304#define ABSTRACT_TYPE(Name, Parent)
305#include "clang/AST/TypeNodes.def"
306 0 // Extra
307 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000308
Reid Spencer5f016e22007-07-11 17:01:13 +0000309 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
310 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000311 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000312 }
313
Douglas Gregordbe833d2009-05-26 14:40:08 +0000314 unsigned Idx = 0;
315 unsigned TotalBytes = 0;
316#define TYPE(Name, Parent) \
317 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000318 llvm::errs() << " " << counts[Idx] << " " << #Name \
319 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000320 TotalBytes += counts[Idx] * sizeof(Name##Type); \
321 ++Idx;
322#define ABSTRACT_TYPE(Name, Parent)
323#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000324
Chandler Carruthcd92a652011-07-04 05:32:14 +0000325 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
326
Douglas Gregor4923aa22010-07-02 20:37:36 +0000327 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000328 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
329 << NumImplicitDefaultConstructors
330 << " implicit default constructors created\n";
331 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
332 << NumImplicitCopyConstructors
333 << " implicit copy constructors created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000334 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000335 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
336 << NumImplicitMoveConstructors
337 << " implicit move constructors created\n";
338 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
339 << NumImplicitCopyAssignmentOperators
340 << " implicit copy assignment operators created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000341 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000342 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
343 << NumImplicitMoveAssignmentOperators
344 << " implicit move assignment operators created\n";
345 llvm::errs() << NumImplicitDestructorsDeclared << "/"
346 << NumImplicitDestructors
347 << " implicit destructors created\n";
348
Douglas Gregor2cf26342009-04-09 22:27:44 +0000349 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000350 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000351 ExternalSource->PrintStats();
352 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000353
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000354 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000355}
356
Douglas Gregor772eeae2011-08-12 06:49:56 +0000357TypedefDecl *ASTContext::getInt128Decl() const {
358 if (!Int128Decl) {
359 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
360 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
361 getTranslationUnitDecl(),
362 SourceLocation(),
363 SourceLocation(),
364 &Idents.get("__int128_t"),
365 TInfo);
366 }
367
368 return Int128Decl;
369}
370
371TypedefDecl *ASTContext::getUInt128Decl() const {
372 if (!UInt128Decl) {
373 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
374 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
375 getTranslationUnitDecl(),
376 SourceLocation(),
377 SourceLocation(),
378 &Idents.get("__uint128_t"),
379 TInfo);
380 }
381
382 return UInt128Decl;
383}
Reid Spencer5f016e22007-07-11 17:01:13 +0000384
John McCalle27ec8a2009-10-23 23:03:21 +0000385void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000386 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000387 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000388 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000389}
390
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000391void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
392 assert((!this->Target || this->Target == &Target) &&
393 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000394 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000396 this->Target = &Target;
397
398 ABI.reset(createCXXABI(Target));
399 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
400
Reid Spencer5f016e22007-07-11 17:01:13 +0000401 // C99 6.2.5p19.
402 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Reid Spencer5f016e22007-07-11 17:01:13 +0000404 // C99 6.2.5p2.
405 InitBuiltinType(BoolTy, BuiltinType::Bool);
406 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000407 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000408 InitBuiltinType(CharTy, BuiltinType::Char_S);
409 else
410 InitBuiltinType(CharTy, BuiltinType::Char_U);
411 // C99 6.2.5p4.
412 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
413 InitBuiltinType(ShortTy, BuiltinType::Short);
414 InitBuiltinType(IntTy, BuiltinType::Int);
415 InitBuiltinType(LongTy, BuiltinType::Long);
416 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Reid Spencer5f016e22007-07-11 17:01:13 +0000418 // C99 6.2.5p6.
419 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
420 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
421 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
422 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
423 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Reid Spencer5f016e22007-07-11 17:01:13 +0000425 // C99 6.2.5p10.
426 InitBuiltinType(FloatTy, BuiltinType::Float);
427 InitBuiltinType(DoubleTy, BuiltinType::Double);
428 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000429
Chris Lattner2df9ced2009-04-30 02:43:43 +0000430 // GNU extension, 128-bit integers.
431 InitBuiltinType(Int128Ty, BuiltinType::Int128);
432 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
433
Chris Lattner3f59c972010-12-25 23:25:43 +0000434 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedmand3d77cd2011-04-30 19:24:24 +0000435 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattner3f59c972010-12-25 23:25:43 +0000436 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
437 else // -fshort-wchar makes wchar_t be unsigned.
438 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
439 } else // C99
Chris Lattner3a250322009-02-26 23:43:47 +0000440 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000441
James Molloy392da482012-05-04 10:55:22 +0000442 WIntTy = getFromTargetType(Target.getWIntType());
443
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000444 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
445 InitBuiltinType(Char16Ty, BuiltinType::Char16);
446 else // C99
447 Char16Ty = getFromTargetType(Target.getChar16Type());
448
449 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
450 InitBuiltinType(Char32Ty, BuiltinType::Char32);
451 else // C99
452 Char32Ty = getFromTargetType(Target.getChar32Type());
453
Douglas Gregor898574e2008-12-05 23:32:09 +0000454 // Placeholder type for type-dependent expressions whose type is
455 // completely unknown. No code should ever check a type against
456 // DependentTy and users should never see it; however, it is here to
457 // help diagnose failures to properly check for type-dependent
458 // expressions.
459 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000460
John McCall2a984ca2010-10-12 00:20:44 +0000461 // Placeholder type for functions.
462 InitBuiltinType(OverloadTy, BuiltinType::Overload);
463
John McCall864c0412011-04-26 20:42:42 +0000464 // Placeholder type for bound members.
465 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
466
John McCall3c3b7f92011-10-25 17:37:35 +0000467 // Placeholder type for pseudo-objects.
468 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
469
John McCall1de4d4e2011-04-07 08:22:57 +0000470 // "any" type; useful for debugger-like clients.
471 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
472
John McCall0ddaeb92011-10-17 18:09:15 +0000473 // Placeholder type for unbridged ARC casts.
474 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
475
Reid Spencer5f016e22007-07-11 17:01:13 +0000476 // C99 6.2.5p11.
477 FloatComplexTy = getComplexType(FloatTy);
478 DoubleComplexTy = getComplexType(DoubleTy);
479 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000480
Steve Naroff7e219e42007-10-15 14:41:52 +0000481 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000482
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000483 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000484 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
485 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000486 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000487
488 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +0000489 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
490 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000491
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000492 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000494 // void * type
495 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000496
497 // nullptr type (C++0x 2.14.7)
498 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000499
500 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
501 InitBuiltinType(HalfTy, BuiltinType::Half);
Reid Spencer5f016e22007-07-11 17:01:13 +0000502}
503
David Blaikied6471f72011-09-25 23:23:43 +0000504DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000505 return SourceMgr.getDiagnostics();
506}
507
Douglas Gregor63200642010-08-30 16:49:28 +0000508AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
509 AttrVec *&Result = DeclAttrs[D];
510 if (!Result) {
511 void *Mem = Allocate(sizeof(AttrVec));
512 Result = new (Mem) AttrVec;
513 }
514
515 return *Result;
516}
517
518/// \brief Erase the attributes corresponding to the given declaration.
519void ASTContext::eraseDeclAttrs(const Decl *D) {
520 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
521 if (Pos != DeclAttrs.end()) {
522 Pos->second->~AttrVec();
523 DeclAttrs.erase(Pos);
524 }
525}
526
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000527MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000528ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000529 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000530 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000531 = InstantiatedFromStaticDataMember.find(Var);
532 if (Pos == InstantiatedFromStaticDataMember.end())
533 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000534
Douglas Gregor7caa6822009-07-24 20:34:43 +0000535 return Pos->second;
536}
537
Mike Stump1eb44332009-09-09 15:08:12 +0000538void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000539ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000540 TemplateSpecializationKind TSK,
541 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000542 assert(Inst->isStaticDataMember() && "Not a static data member");
543 assert(Tmpl->isStaticDataMember() && "Not a static data member");
544 assert(!InstantiatedFromStaticDataMember[Inst] &&
545 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000546 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000547 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000548}
549
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000550FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
551 const FunctionDecl *FD){
552 assert(FD && "Specialization is 0");
553 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000554 = ClassScopeSpecializationPattern.find(FD);
555 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000556 return 0;
557
558 return Pos->second;
559}
560
561void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
562 FunctionDecl *Pattern) {
563 assert(FD && "Specialization is 0");
564 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000565 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000566}
567
John McCall7ba107a2009-11-18 02:36:19 +0000568NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000569ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000570 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000571 = InstantiatedFromUsingDecl.find(UUD);
572 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000573 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Anders Carlsson0d8df782009-08-29 19:37:28 +0000575 return Pos->second;
576}
577
578void
John McCalled976492009-12-04 22:46:56 +0000579ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
580 assert((isa<UsingDecl>(Pattern) ||
581 isa<UnresolvedUsingValueDecl>(Pattern) ||
582 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
583 "pattern decl is not a using decl");
584 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
585 InstantiatedFromUsingDecl[Inst] = Pattern;
586}
587
588UsingShadowDecl *
589ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
590 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
591 = InstantiatedFromUsingShadowDecl.find(Inst);
592 if (Pos == InstantiatedFromUsingShadowDecl.end())
593 return 0;
594
595 return Pos->second;
596}
597
598void
599ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
600 UsingShadowDecl *Pattern) {
601 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
602 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000603}
604
Anders Carlssond8b285f2009-09-01 04:26:58 +0000605FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
606 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
607 = InstantiatedFromUnnamedFieldDecl.find(Field);
608 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
609 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000610
Anders Carlssond8b285f2009-09-01 04:26:58 +0000611 return Pos->second;
612}
613
614void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
615 FieldDecl *Tmpl) {
616 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
617 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
618 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
619 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000620
Anders Carlssond8b285f2009-09-01 04:26:58 +0000621 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
622}
623
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000624bool ASTContext::ZeroBitfieldFollowsNonBitfield(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);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000628}
629
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000630bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
631 const FieldDecl *LastFD) const {
632 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000633 FD->getBitWidthValue(*this) == 0 &&
634 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000635}
636
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000637bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
638 const FieldDecl *LastFD) const {
639 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000640 FD->getBitWidthValue(*this) &&
641 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000642}
643
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000644bool ASTContext::NonBitfieldFollowsBitfield(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 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000648}
649
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000650bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000651 const FieldDecl *LastFD) const {
652 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000653 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000654}
655
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000656ASTContext::overridden_cxx_method_iterator
657ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
658 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
659 = OverriddenMethods.find(Method);
660 if (Pos == OverriddenMethods.end())
661 return 0;
662
663 return Pos->second.begin();
664}
665
666ASTContext::overridden_cxx_method_iterator
667ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
668 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
669 = OverriddenMethods.find(Method);
670 if (Pos == OverriddenMethods.end())
671 return 0;
672
673 return Pos->second.end();
674}
675
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000676unsigned
677ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
678 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
679 = OverriddenMethods.find(Method);
680 if (Pos == OverriddenMethods.end())
681 return 0;
682
683 return Pos->second.size();
684}
685
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000686void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
687 const CXXMethodDecl *Overridden) {
688 OverriddenMethods[Method].push_back(Overridden);
689}
690
Douglas Gregore6649772011-12-03 00:30:27 +0000691void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
692 assert(!Import->NextLocalImport && "Import declaration already in the chain");
693 assert(!Import->isFromASTFile() && "Non-local import declaration");
694 if (!FirstLocalImport) {
695 FirstLocalImport = Import;
696 LastLocalImport = Import;
697 return;
698 }
699
700 LastLocalImport->NextLocalImport = Import;
701 LastLocalImport = Import;
702}
703
Chris Lattner464175b2007-07-18 17:52:12 +0000704//===----------------------------------------------------------------------===//
705// Type Sizing and Analysis
706//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000707
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000708/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
709/// scalar floating point type.
710const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000711 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000712 assert(BT && "Not a floating point type!");
713 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000714 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000715 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000716 case BuiltinType::Float: return Target->getFloatFormat();
717 case BuiltinType::Double: return Target->getDoubleFormat();
718 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000719 }
720}
721
Ken Dyck8b752f12010-01-27 17:10:57 +0000722/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000723/// specified decl. Note that bitfields do not have a valid alignment, so
724/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000725/// If @p RefAsPointee, references are treated like their underlying type
726/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +0000727CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000728 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +0000729
John McCall4081a5c2010-10-08 18:24:19 +0000730 bool UseAlignAttrOnly = false;
731 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
732 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +0000733
John McCall4081a5c2010-10-08 18:24:19 +0000734 // __attribute__((aligned)) can increase or decrease alignment
735 // *except* on a struct or struct member, where it only increases
736 // alignment unless 'packed' is also specified.
737 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +0000738 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +0000739 // ignore that possibility; Sema should diagnose it.
740 if (isa<FieldDecl>(D)) {
741 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
742 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
743 } else {
744 UseAlignAttrOnly = true;
745 }
746 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +0000747 else if (isa<FieldDecl>(D))
748 UseAlignAttrOnly =
749 D->hasAttr<PackedAttr>() ||
750 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +0000751
John McCallba4f5d52011-01-20 07:57:12 +0000752 // If we're using the align attribute only, just ignore everything
753 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +0000754 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +0000755 // do nothing
756
John McCall4081a5c2010-10-08 18:24:19 +0000757 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +0000758 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000759 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000760 if (RefAsPointee)
761 T = RT->getPointeeType();
762 else
763 T = getPointerType(RT->getPointeeType());
764 }
765 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +0000766 // Adjust alignments of declarations with array type by the
767 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000768 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +0000769 const ArrayType *arrayType;
770 if (MinWidth && (arrayType = getAsArrayType(T))) {
771 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000772 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +0000773 else if (isa<ConstantArrayType>(arrayType) &&
774 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000775 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000776
John McCall3b657512011-01-19 10:06:00 +0000777 // Walk through any array types while we're at it.
778 T = getBaseElementType(arrayType);
779 }
Chad Rosier9f1210c2011-07-26 07:03:04 +0000780 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedmandcdafb62009-02-22 02:56:25 +0000781 }
John McCallba4f5d52011-01-20 07:57:12 +0000782
783 // Fields can be subject to extra alignment constraints, like if
784 // the field is packed, the struct is packed, or the struct has a
785 // a max-field-alignment constraint (#pragma pack). So calculate
786 // the actual alignment of the field within the struct, and then
787 // (as we're expected to) constrain that by the alignment of the type.
788 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
789 // So calculate the alignment of the field.
790 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
791
792 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +0000793 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +0000794
795 // Use the GCD of that and the offset within the record.
796 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
797 if (offset > 0) {
798 // Alignment is always a power of 2, so the GCD will be a power of 2,
799 // which means we get to do this crazy thing instead of Euclid's.
800 uint64_t lowBitOfOffset = offset & (~offset + 1);
801 if (lowBitOfOffset < fieldAlign)
802 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
803 }
804
805 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +0000806 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000807 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000808
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000809 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +0000810}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000811
John McCallea1471e2010-05-20 01:18:31 +0000812std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000813ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +0000814 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000815 return std::make_pair(toCharUnitsFromBits(Info.first),
816 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +0000817}
818
819std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000820ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +0000821 return getTypeInfoInChars(T.getTypePtr());
822}
823
Daniel Dunbarbc5419a2012-03-09 04:12:54 +0000824std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
825 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
826 if (it != MemoizedTypeInfo.end())
827 return it->second;
828
829 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
830 MemoizedTypeInfo.insert(std::make_pair(T, Info));
831 return Info;
832}
833
834/// getTypeInfoImpl - Return the size of the specified type, in bits. This
835/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000836///
837/// FIXME: Pointers into different addr spaces could have different sizes and
838/// alignment requirements: getPointerInfo should take an AddrSpace, this
839/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000840std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +0000841ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +0000842 uint64_t Width=0;
843 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000844 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000845#define TYPE(Class, Base)
846#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000847#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000848#define DEPENDENT_TYPE(Class, Base) case Type::Class:
849#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +0000850 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000851
Chris Lattner692233e2007-07-13 22:27:08 +0000852 case Type::FunctionNoProto:
853 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000854 // GCC extension: alignof(function) = 32 bits
855 Width = 0;
856 Align = 32;
857 break;
858
Douglas Gregor72564e72009-02-26 23:50:07 +0000859 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000860 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000861 Width = 0;
862 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
863 break;
864
Steve Narofffb22d962007-08-30 01:06:46 +0000865 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000866 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000867
Chris Lattner98be4942008-03-05 18:54:05 +0000868 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +0000869 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +0000870 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
871 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +0000872 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +0000873 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +0000874 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000875 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000876 }
Nate Begeman213541a2008-04-18 23:10:10 +0000877 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000878 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000879 const VectorType *VT = cast<VectorType>(T);
880 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
881 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000882 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000883 // If the alignment is not a power of 2, round up to the next power of 2.
884 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000885 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000886 Align = llvm::NextPowerOf2(Align);
887 Width = llvm::RoundUpToAlignment(Width, Align);
888 }
Chris Lattner030d8842007-07-19 22:06:24 +0000889 break;
890 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000891
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000892 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000893 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000894 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000895 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000896 // GCC extension: alignof(void) = 8 bits.
897 Width = 0;
898 Align = 8;
899 break;
900
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000901 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000902 Width = Target->getBoolWidth();
903 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000904 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000905 case BuiltinType::Char_S:
906 case BuiltinType::Char_U:
907 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000908 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000909 Width = Target->getCharWidth();
910 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000911 break;
Chris Lattner3f59c972010-12-25 23:25:43 +0000912 case BuiltinType::WChar_S:
913 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000914 Width = Target->getWCharWidth();
915 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000916 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000917 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000918 Width = Target->getChar16Width();
919 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000920 break;
921 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000922 Width = Target->getChar32Width();
923 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000924 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000925 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000926 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000927 Width = Target->getShortWidth();
928 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000929 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000930 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000931 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000932 Width = Target->getIntWidth();
933 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000934 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000935 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000936 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000937 Width = Target->getLongWidth();
938 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000939 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000940 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000941 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000942 Width = Target->getLongLongWidth();
943 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000944 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000945 case BuiltinType::Int128:
946 case BuiltinType::UInt128:
947 Width = 128;
948 Align = 128; // int128_t is 128-bit aligned on all targets.
949 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000950 case BuiltinType::Half:
951 Width = Target->getHalfWidth();
952 Align = Target->getHalfAlign();
953 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000954 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000955 Width = Target->getFloatWidth();
956 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000957 break;
958 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000959 Width = Target->getDoubleWidth();
960 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000961 break;
962 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000963 Width = Target->getLongDoubleWidth();
964 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000965 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000966 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000967 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
968 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000969 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000970 case BuiltinType::ObjCId:
971 case BuiltinType::ObjCClass:
972 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000973 Width = Target->getPointerWidth(0);
974 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000975 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000976 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000977 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000978 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000979 Width = Target->getPointerWidth(0);
980 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000981 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000982 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000983 unsigned AS = getTargetAddressSpace(
984 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000985 Width = Target->getPointerWidth(AS);
986 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +0000987 break;
988 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000989 case Type::LValueReference:
990 case Type::RValueReference: {
991 // alignof and sizeof should never enter this code path here, so we go
992 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000993 unsigned AS = getTargetAddressSpace(
994 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000995 Width = Target->getPointerWidth(AS);
996 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +0000997 break;
998 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000999 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001000 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001001 Width = Target->getPointerWidth(AS);
1002 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001003 break;
1004 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001005 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001006 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001007 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001008 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +00001009 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001010 Align = PtrDiffInfo.second;
1011 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001012 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001013 case Type::Complex: {
1014 // Complex types have the same alignment as their elements, but twice the
1015 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001016 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001017 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001018 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001019 Align = EltInfo.second;
1020 break;
1021 }
John McCallc12c5bb2010-05-15 11:32:37 +00001022 case Type::ObjCObject:
1023 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001024 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001025 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001026 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001027 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001028 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001029 break;
1030 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001031 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001032 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001033 const TagType *TT = cast<TagType>(T);
1034
1035 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001036 Width = 8;
1037 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001038 break;
1039 }
Mike Stump1eb44332009-09-09 15:08:12 +00001040
Daniel Dunbar1d751182008-11-08 05:48:37 +00001041 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001042 return getTypeInfo(ET->getDecl()->getIntegerType());
1043
Daniel Dunbar1d751182008-11-08 05:48:37 +00001044 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001045 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001046 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001047 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001048 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001049 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001050
Chris Lattner9fcfe922009-10-22 05:17:15 +00001051 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001052 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1053 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001054
Richard Smith34b41d92011-02-20 03:19:35 +00001055 case Type::Auto: {
1056 const AutoType *A = cast<AutoType>(T);
1057 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001058 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001059 }
1060
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001061 case Type::Paren:
1062 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1063
Douglas Gregor18857642009-04-30 17:32:17 +00001064 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001065 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001066 std::pair<uint64_t, unsigned> Info
1067 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001068 // If the typedef has an aligned attribute on it, it overrides any computed
1069 // alignment we have. This violates the GCC documentation (which says that
1070 // attribute(aligned) can only round up) but matches its implementation.
1071 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1072 Align = AttrAlign;
1073 else
1074 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001075 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001076 break;
Chris Lattner71763312008-04-06 22:05:18 +00001077 }
Douglas Gregor18857642009-04-30 17:32:17 +00001078
1079 case Type::TypeOfExpr:
1080 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1081 .getTypePtr());
1082
1083 case Type::TypeOf:
1084 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1085
Anders Carlsson395b4752009-06-24 19:06:50 +00001086 case Type::Decltype:
1087 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1088 .getTypePtr());
1089
Sean Huntca63c202011-05-24 22:41:36 +00001090 case Type::UnaryTransform:
1091 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1092
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001093 case Type::Elaborated:
1094 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001095
John McCall9d156a72011-01-06 01:58:22 +00001096 case Type::Attributed:
1097 return getTypeInfo(
1098 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1099
Richard Smith3e4c6c42011-05-05 21:57:07 +00001100 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001101 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001102 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001103 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1104 // A type alias template specialization may refer to a typedef with the
1105 // aligned attribute on it.
1106 if (TST->isTypeAlias())
1107 return getTypeInfo(TST->getAliasedType().getTypePtr());
1108 else
1109 return getTypeInfo(getCanonicalType(T));
1110 }
1111
Eli Friedmanb001de72011-10-06 23:00:33 +00001112 case Type::Atomic: {
Eli Friedman2be46072011-10-14 20:59:01 +00001113 std::pair<uint64_t, unsigned> Info
1114 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1115 Width = Info.first;
1116 Align = Info.second;
1117 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1118 llvm::isPowerOf2_64(Width)) {
1119 // We can potentially perform lock-free atomic operations for this
1120 // type; promote the alignment appropriately.
1121 // FIXME: We could potentially promote the width here as well...
1122 // is that worthwhile? (Non-struct atomic types generally have
1123 // power-of-two size anyway, but structs might not. Requires a bit
1124 // of implementation work to make sure we zero out the extra bits.)
1125 Align = static_cast<unsigned>(Width);
1126 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001127 }
1128
Douglas Gregor18857642009-04-30 17:32:17 +00001129 }
Mike Stump1eb44332009-09-09 15:08:12 +00001130
Eli Friedman2be46072011-10-14 20:59:01 +00001131 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001132 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001133}
1134
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001135/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1136CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1137 return CharUnits::fromQuantity(BitSize / getCharWidth());
1138}
1139
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001140/// toBits - Convert a size in characters to a size in characters.
1141int64_t ASTContext::toBits(CharUnits CharSize) const {
1142 return CharSize.getQuantity() * getCharWidth();
1143}
1144
Ken Dyckbdc601b2009-12-22 14:23:30 +00001145/// getTypeSizeInChars - Return the size of the specified type, in characters.
1146/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001147CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001148 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001149}
Jay Foad4ba2a172011-01-12 09:06:06 +00001150CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001151 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001152}
1153
Ken Dyck16e20cc2010-01-26 17:25:18 +00001154/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001155/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001156CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001157 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001158}
Jay Foad4ba2a172011-01-12 09:06:06 +00001159CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001160 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001161}
1162
Chris Lattner34ebde42009-01-27 18:08:34 +00001163/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1164/// type for the current target in bits. This can be different than the ABI
1165/// alignment in cases where it is beneficial for performance to overalign
1166/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001167unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001168 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001169
1170 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001171 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001172 T = CT->getElementType().getTypePtr();
1173 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001174 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1175 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001176 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1177
Chris Lattner34ebde42009-01-27 18:08:34 +00001178 return ABIAlign;
1179}
1180
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001181/// DeepCollectObjCIvars -
1182/// This routine first collects all declared, but not synthesized, ivars in
1183/// super class and then collects all ivars, including those synthesized for
1184/// current class. This routine is used for implementation of current class
1185/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001186///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001187void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1188 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001189 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001190 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1191 DeepCollectObjCIvars(SuperClass, false, Ivars);
1192 if (!leafClass) {
1193 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1194 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001195 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001196 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001197 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001198 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001199 Iv= Iv->getNextIvar())
1200 Ivars.push_back(Iv);
1201 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001202}
1203
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001204/// CollectInheritedProtocols - Collect all protocols in current class and
1205/// those inherited by it.
1206void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001207 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001208 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001209 // We can use protocol_iterator here instead of
1210 // all_referenced_protocol_iterator since we are walking all categories.
1211 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1212 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001213 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001214 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001215 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001216 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001217 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001218 CollectInheritedProtocols(*P, Protocols);
1219 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001220 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001221
1222 // Categories of this Interface.
1223 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1224 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1225 CollectInheritedProtocols(CDeclChain, Protocols);
1226 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1227 while (SD) {
1228 CollectInheritedProtocols(SD, Protocols);
1229 SD = SD->getSuperClass();
1230 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001231 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001232 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001233 PE = OC->protocol_end(); P != PE; ++P) {
1234 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001235 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001236 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1237 PE = Proto->protocol_end(); P != PE; ++P)
1238 CollectInheritedProtocols(*P, Protocols);
1239 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001240 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001241 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1242 PE = OP->protocol_end(); P != PE; ++P) {
1243 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001244 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001245 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1246 PE = Proto->protocol_end(); P != PE; ++P)
1247 CollectInheritedProtocols(*P, Protocols);
1248 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001249 }
1250}
1251
Jay Foad4ba2a172011-01-12 09:06:06 +00001252unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001253 unsigned count = 0;
1254 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001255 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1256 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001257 count += CDecl->ivar_size();
1258
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001259 // Count ivar defined in this class's implementation. This
1260 // includes synthesized ivars.
1261 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001262 count += ImplDecl->ivar_size();
1263
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001264 return count;
1265}
1266
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001267bool ASTContext::isSentinelNullExpr(const Expr *E) {
1268 if (!E)
1269 return false;
1270
1271 // nullptr_t is always treated as null.
1272 if (E->getType()->isNullPtrType()) return true;
1273
1274 if (E->getType()->isAnyPointerType() &&
1275 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1276 Expr::NPC_ValueDependentIsNull))
1277 return true;
1278
1279 // Unfortunately, __null has type 'int'.
1280 if (isa<GNUNullExpr>(E)) return true;
1281
1282 return false;
1283}
1284
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001285/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1286ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1287 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1288 I = ObjCImpls.find(D);
1289 if (I != ObjCImpls.end())
1290 return cast<ObjCImplementationDecl>(I->second);
1291 return 0;
1292}
1293/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1294ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1295 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1296 I = ObjCImpls.find(D);
1297 if (I != ObjCImpls.end())
1298 return cast<ObjCCategoryImplDecl>(I->second);
1299 return 0;
1300}
1301
1302/// \brief Set the implementation of ObjCInterfaceDecl.
1303void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1304 ObjCImplementationDecl *ImplD) {
1305 assert(IFaceD && ImplD && "Passed null params");
1306 ObjCImpls[IFaceD] = ImplD;
1307}
1308/// \brief Set the implementation of ObjCCategoryDecl.
1309void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1310 ObjCCategoryImplDecl *ImplD) {
1311 assert(CatD && ImplD && "Passed null params");
1312 ObjCImpls[CatD] = ImplD;
1313}
1314
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001315ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1316 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1317 return ID;
1318 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1319 return CD->getClassInterface();
1320 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1321 return IMD->getClassInterface();
1322
1323 return 0;
1324}
1325
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001326/// \brief Get the copy initialization expression of VarDecl,or NULL if
1327/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001328Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001329 assert(VD && "Passed null params");
1330 assert(VD->hasAttr<BlocksAttr>() &&
1331 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001332 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001333 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001334 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1335}
1336
1337/// \brief Set the copy inialization expression of a block var decl.
1338void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1339 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001340 assert(VD->hasAttr<BlocksAttr>() &&
1341 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001342 BlockVarCopyInits[VD] = Init;
1343}
1344
John McCalla93c9342009-12-07 02:54:59 +00001345/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001346///
John McCalla93c9342009-12-07 02:54:59 +00001347/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001348/// the TypeLoc wrappers.
1349///
1350/// \param T the type that will be the basis for type source info. This type
1351/// should refer to how the declarator was written in source code, not to
1352/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001353TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001354 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001355 if (!DataSize)
1356 DataSize = TypeLoc::getFullDataSizeForType(T);
1357 else
1358 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001359 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001360
John McCalla93c9342009-12-07 02:54:59 +00001361 TypeSourceInfo *TInfo =
1362 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1363 new (TInfo) TypeSourceInfo(T);
1364 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001365}
1366
John McCalla93c9342009-12-07 02:54:59 +00001367TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001368 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001369 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001370 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001371 return DI;
1372}
1373
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001374const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001375ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001376 return getObjCLayout(D, 0);
1377}
1378
1379const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001380ASTContext::getASTObjCImplementationLayout(
1381 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001382 return getObjCLayout(D->getClassInterface(), D);
1383}
1384
Chris Lattnera7674d82007-07-13 22:13:22 +00001385//===----------------------------------------------------------------------===//
1386// Type creation/memoization methods
1387//===----------------------------------------------------------------------===//
1388
Jay Foad4ba2a172011-01-12 09:06:06 +00001389QualType
John McCall3b657512011-01-19 10:06:00 +00001390ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1391 unsigned fastQuals = quals.getFastQualifiers();
1392 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001393
1394 // Check if we've already instantiated this type.
1395 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001396 ExtQuals::Profile(ID, baseType, quals);
1397 void *insertPos = 0;
1398 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1399 assert(eq->getQualifiers() == quals);
1400 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001401 }
1402
John McCall3b657512011-01-19 10:06:00 +00001403 // If the base type is not canonical, make the appropriate canonical type.
1404 QualType canon;
1405 if (!baseType->isCanonicalUnqualified()) {
1406 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00001407 canonSplit.Quals.addConsistentQualifiers(quals);
1408 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001409
1410 // Re-find the insert position.
1411 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1412 }
1413
1414 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1415 ExtQualNodes.InsertNode(eq, insertPos);
1416 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001417}
1418
Jay Foad4ba2a172011-01-12 09:06:06 +00001419QualType
1420ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001421 QualType CanT = getCanonicalType(T);
1422 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001423 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001424
John McCall0953e762009-09-24 19:53:00 +00001425 // If we are composing extended qualifiers together, merge together
1426 // into one ExtQuals node.
1427 QualifierCollector Quals;
1428 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001429
John McCall0953e762009-09-24 19:53:00 +00001430 // If this type already has an address space specified, it cannot get
1431 // another one.
1432 assert(!Quals.hasAddressSpace() &&
1433 "Type cannot be in multiple addr spaces!");
1434 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001435
John McCall0953e762009-09-24 19:53:00 +00001436 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001437}
1438
Chris Lattnerb7d25532009-02-18 22:53:11 +00001439QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001440 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001441 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001442 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001443 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001444
John McCall7f040a92010-12-24 02:08:15 +00001445 if (const PointerType *ptr = T->getAs<PointerType>()) {
1446 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001447 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001448 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1449 return getPointerType(ResultType);
1450 }
1451 }
Mike Stump1eb44332009-09-09 15:08:12 +00001452
John McCall0953e762009-09-24 19:53:00 +00001453 // If we are composing extended qualifiers together, merge together
1454 // into one ExtQuals node.
1455 QualifierCollector Quals;
1456 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001457
John McCall0953e762009-09-24 19:53:00 +00001458 // If this type already has an ObjCGC specified, it cannot get
1459 // another one.
1460 assert(!Quals.hasObjCGCAttr() &&
1461 "Type cannot have multiple ObjCGCs!");
1462 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001463
John McCall0953e762009-09-24 19:53:00 +00001464 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001465}
Chris Lattnera7674d82007-07-13 22:13:22 +00001466
John McCalle6a365d2010-12-19 02:44:49 +00001467const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1468 FunctionType::ExtInfo Info) {
1469 if (T->getExtInfo() == Info)
1470 return T;
1471
1472 QualType Result;
1473 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1474 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1475 } else {
1476 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1477 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1478 EPI.ExtInfo = Info;
1479 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1480 FPT->getNumArgs(), EPI);
1481 }
1482
1483 return cast<FunctionType>(Result.getTypePtr());
1484}
1485
Reid Spencer5f016e22007-07-11 17:01:13 +00001486/// getComplexType - Return the uniqued reference to the type for a complex
1487/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001488QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001489 // Unique pointers, to guarantee there is only one pointer of a particular
1490 // structure.
1491 llvm::FoldingSetNodeID ID;
1492 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001493
Reid Spencer5f016e22007-07-11 17:01:13 +00001494 void *InsertPos = 0;
1495 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1496 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001497
Reid Spencer5f016e22007-07-11 17:01:13 +00001498 // If the pointee type isn't canonical, this won't be a canonical type either,
1499 // so fill in the canonical type field.
1500 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001501 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001502 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001503
Reid Spencer5f016e22007-07-11 17:01:13 +00001504 // Get the new insert position for the node we care about.
1505 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001506 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001507 }
John McCall6b304a02009-09-24 23:30:46 +00001508 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001509 Types.push_back(New);
1510 ComplexTypes.InsertNode(New, InsertPos);
1511 return QualType(New, 0);
1512}
1513
Reid Spencer5f016e22007-07-11 17:01:13 +00001514/// getPointerType - Return the uniqued reference to the type for a pointer to
1515/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001516QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001517 // Unique pointers, to guarantee there is only one pointer of a particular
1518 // structure.
1519 llvm::FoldingSetNodeID ID;
1520 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001521
Reid Spencer5f016e22007-07-11 17:01:13 +00001522 void *InsertPos = 0;
1523 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1524 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001525
Reid Spencer5f016e22007-07-11 17:01:13 +00001526 // If the pointee type isn't canonical, this won't be a canonical type either,
1527 // so fill in the canonical type field.
1528 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001529 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001530 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001531
Reid Spencer5f016e22007-07-11 17:01:13 +00001532 // Get the new insert position for the node we care about.
1533 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001534 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001535 }
John McCall6b304a02009-09-24 23:30:46 +00001536 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001537 Types.push_back(New);
1538 PointerTypes.InsertNode(New, InsertPos);
1539 return QualType(New, 0);
1540}
1541
Mike Stump1eb44332009-09-09 15:08:12 +00001542/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001543/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001544QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001545 assert(T->isFunctionType() && "block of function types only");
1546 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001547 // structure.
1548 llvm::FoldingSetNodeID ID;
1549 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001550
Steve Naroff5618bd42008-08-27 16:04:49 +00001551 void *InsertPos = 0;
1552 if (BlockPointerType *PT =
1553 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1554 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001555
1556 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001557 // type either so fill in the canonical type field.
1558 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001559 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001560 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001561
Steve Naroff5618bd42008-08-27 16:04:49 +00001562 // Get the new insert position for the node we care about.
1563 BlockPointerType *NewIP =
1564 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001565 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001566 }
John McCall6b304a02009-09-24 23:30:46 +00001567 BlockPointerType *New
1568 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001569 Types.push_back(New);
1570 BlockPointerTypes.InsertNode(New, InsertPos);
1571 return QualType(New, 0);
1572}
1573
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001574/// getLValueReferenceType - Return the uniqued reference to the type for an
1575/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001576QualType
1577ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00001578 assert(getCanonicalType(T) != OverloadTy &&
1579 "Unresolved overloaded function type");
1580
Reid Spencer5f016e22007-07-11 17:01:13 +00001581 // Unique pointers, to guarantee there is only one pointer of a particular
1582 // structure.
1583 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001584 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001585
1586 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001587 if (LValueReferenceType *RT =
1588 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001589 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001590
John McCall54e14c42009-10-22 22:37:11 +00001591 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1592
Reid Spencer5f016e22007-07-11 17:01:13 +00001593 // If the referencee type isn't canonical, this won't be a canonical type
1594 // either, so fill in the canonical type field.
1595 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001596 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1597 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1598 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001599
Reid Spencer5f016e22007-07-11 17:01:13 +00001600 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001601 LValueReferenceType *NewIP =
1602 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001603 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001604 }
1605
John McCall6b304a02009-09-24 23:30:46 +00001606 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001607 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1608 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001609 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001610 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001611
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001612 return QualType(New, 0);
1613}
1614
1615/// getRValueReferenceType - Return the uniqued reference to the type for an
1616/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001617QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001618 // Unique pointers, to guarantee there is only one pointer of a particular
1619 // structure.
1620 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001621 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001622
1623 void *InsertPos = 0;
1624 if (RValueReferenceType *RT =
1625 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1626 return QualType(RT, 0);
1627
John McCall54e14c42009-10-22 22:37:11 +00001628 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1629
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001630 // If the referencee type isn't canonical, this won't be a canonical type
1631 // either, so fill in the canonical type field.
1632 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001633 if (InnerRef || !T.isCanonical()) {
1634 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1635 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001636
1637 // Get the new insert position for the node we care about.
1638 RValueReferenceType *NewIP =
1639 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001640 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001641 }
1642
John McCall6b304a02009-09-24 23:30:46 +00001643 RValueReferenceType *New
1644 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001645 Types.push_back(New);
1646 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001647 return QualType(New, 0);
1648}
1649
Sebastian Redlf30208a2009-01-24 21:16:55 +00001650/// getMemberPointerType - Return the uniqued reference to the type for a
1651/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00001652QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001653 // Unique pointers, to guarantee there is only one pointer of a particular
1654 // structure.
1655 llvm::FoldingSetNodeID ID;
1656 MemberPointerType::Profile(ID, T, Cls);
1657
1658 void *InsertPos = 0;
1659 if (MemberPointerType *PT =
1660 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1661 return QualType(PT, 0);
1662
1663 // If the pointee or class type isn't canonical, this won't be a canonical
1664 // type either, so fill in the canonical type field.
1665 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001666 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001667 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1668
1669 // Get the new insert position for the node we care about.
1670 MemberPointerType *NewIP =
1671 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001672 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001673 }
John McCall6b304a02009-09-24 23:30:46 +00001674 MemberPointerType *New
1675 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001676 Types.push_back(New);
1677 MemberPointerTypes.InsertNode(New, InsertPos);
1678 return QualType(New, 0);
1679}
1680
Mike Stump1eb44332009-09-09 15:08:12 +00001681/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001682/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001683QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001684 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001685 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001686 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001687 assert((EltTy->isDependentType() ||
1688 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001689 "Constant array of VLAs is illegal!");
1690
Chris Lattner38aeec72009-05-13 04:12:56 +00001691 // Convert the array size into a canonical width matching the pointer size for
1692 // the target.
1693 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001694 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001695 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00001696
Reid Spencer5f016e22007-07-11 17:01:13 +00001697 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001698 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001699
Reid Spencer5f016e22007-07-11 17:01:13 +00001700 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001701 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001702 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001703 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001704
John McCall3b657512011-01-19 10:06:00 +00001705 // If the element type isn't canonical or has qualifiers, this won't
1706 // be a canonical type either, so fill in the canonical type field.
1707 QualType Canon;
1708 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1709 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00001710 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001711 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00001712 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001713
Reid Spencer5f016e22007-07-11 17:01:13 +00001714 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001715 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001716 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001717 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001718 }
Mike Stump1eb44332009-09-09 15:08:12 +00001719
John McCall6b304a02009-09-24 23:30:46 +00001720 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001721 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001722 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001723 Types.push_back(New);
1724 return QualType(New, 0);
1725}
1726
John McCallce889032011-01-18 08:40:38 +00001727/// getVariableArrayDecayedType - Turns the given type, which may be
1728/// variably-modified, into the corresponding type with all the known
1729/// sizes replaced with [*].
1730QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1731 // Vastly most common case.
1732 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001733
John McCallce889032011-01-18 08:40:38 +00001734 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001735
John McCallce889032011-01-18 08:40:38 +00001736 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00001737 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00001738 switch (ty->getTypeClass()) {
1739#define TYPE(Class, Base)
1740#define ABSTRACT_TYPE(Class, Base)
1741#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1742#include "clang/AST/TypeNodes.def"
1743 llvm_unreachable("didn't desugar past all non-canonical types?");
1744
1745 // These types should never be variably-modified.
1746 case Type::Builtin:
1747 case Type::Complex:
1748 case Type::Vector:
1749 case Type::ExtVector:
1750 case Type::DependentSizedExtVector:
1751 case Type::ObjCObject:
1752 case Type::ObjCInterface:
1753 case Type::ObjCObjectPointer:
1754 case Type::Record:
1755 case Type::Enum:
1756 case Type::UnresolvedUsing:
1757 case Type::TypeOfExpr:
1758 case Type::TypeOf:
1759 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00001760 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00001761 case Type::DependentName:
1762 case Type::InjectedClassName:
1763 case Type::TemplateSpecialization:
1764 case Type::DependentTemplateSpecialization:
1765 case Type::TemplateTypeParm:
1766 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00001767 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00001768 case Type::PackExpansion:
1769 llvm_unreachable("type should never be variably-modified");
1770
1771 // These types can be variably-modified but should never need to
1772 // further decay.
1773 case Type::FunctionNoProto:
1774 case Type::FunctionProto:
1775 case Type::BlockPointer:
1776 case Type::MemberPointer:
1777 return type;
1778
1779 // These types can be variably-modified. All these modifications
1780 // preserve structure except as noted by comments.
1781 // TODO: if we ever care about optimizing VLAs, there are no-op
1782 // optimizations available here.
1783 case Type::Pointer:
1784 result = getPointerType(getVariableArrayDecayedType(
1785 cast<PointerType>(ty)->getPointeeType()));
1786 break;
1787
1788 case Type::LValueReference: {
1789 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1790 result = getLValueReferenceType(
1791 getVariableArrayDecayedType(lv->getPointeeType()),
1792 lv->isSpelledAsLValue());
1793 break;
1794 }
1795
1796 case Type::RValueReference: {
1797 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1798 result = getRValueReferenceType(
1799 getVariableArrayDecayedType(lv->getPointeeType()));
1800 break;
1801 }
1802
Eli Friedmanb001de72011-10-06 23:00:33 +00001803 case Type::Atomic: {
1804 const AtomicType *at = cast<AtomicType>(ty);
1805 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1806 break;
1807 }
1808
John McCallce889032011-01-18 08:40:38 +00001809 case Type::ConstantArray: {
1810 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1811 result = getConstantArrayType(
1812 getVariableArrayDecayedType(cat->getElementType()),
1813 cat->getSize(),
1814 cat->getSizeModifier(),
1815 cat->getIndexTypeCVRQualifiers());
1816 break;
1817 }
1818
1819 case Type::DependentSizedArray: {
1820 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1821 result = getDependentSizedArrayType(
1822 getVariableArrayDecayedType(dat->getElementType()),
1823 dat->getSizeExpr(),
1824 dat->getSizeModifier(),
1825 dat->getIndexTypeCVRQualifiers(),
1826 dat->getBracketsRange());
1827 break;
1828 }
1829
1830 // Turn incomplete types into [*] types.
1831 case Type::IncompleteArray: {
1832 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1833 result = getVariableArrayType(
1834 getVariableArrayDecayedType(iat->getElementType()),
1835 /*size*/ 0,
1836 ArrayType::Normal,
1837 iat->getIndexTypeCVRQualifiers(),
1838 SourceRange());
1839 break;
1840 }
1841
1842 // Turn VLA types into [*] types.
1843 case Type::VariableArray: {
1844 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1845 result = getVariableArrayType(
1846 getVariableArrayDecayedType(vat->getElementType()),
1847 /*size*/ 0,
1848 ArrayType::Star,
1849 vat->getIndexTypeCVRQualifiers(),
1850 vat->getBracketsRange());
1851 break;
1852 }
1853 }
1854
1855 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00001856 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00001857}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001858
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001859/// getVariableArrayType - Returns a non-unique reference to the type for a
1860/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001861QualType ASTContext::getVariableArrayType(QualType EltTy,
1862 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001863 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001864 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00001865 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001866 // Since we don't unique expressions, it isn't possible to unique VLA's
1867 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00001868 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00001869
John McCall3b657512011-01-19 10:06:00 +00001870 // Be sure to pull qualifiers off the element type.
1871 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1872 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00001873 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001874 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00001875 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00001876 }
1877
John McCall6b304a02009-09-24 23:30:46 +00001878 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001879 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001880
1881 VariableArrayTypes.push_back(New);
1882 Types.push_back(New);
1883 return QualType(New, 0);
1884}
1885
Douglas Gregor898574e2008-12-05 23:32:09 +00001886/// getDependentSizedArrayType - Returns a non-unique reference to
1887/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001888/// type.
John McCall3b657512011-01-19 10:06:00 +00001889QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1890 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00001891 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001892 unsigned elementTypeQuals,
1893 SourceRange brackets) const {
1894 assert((!numElements || numElements->isTypeDependent() ||
1895 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001896 "Size must be type- or value-dependent!");
1897
John McCall3b657512011-01-19 10:06:00 +00001898 // Dependently-sized array types that do not have a specified number
1899 // of elements will have their sizes deduced from a dependent
1900 // initializer. We do no canonicalization here at all, which is okay
1901 // because they can't be used in most locations.
1902 if (!numElements) {
1903 DependentSizedArrayType *newType
1904 = new (*this, TypeAlignment)
1905 DependentSizedArrayType(*this, elementType, QualType(),
1906 numElements, ASM, elementTypeQuals,
1907 brackets);
1908 Types.push_back(newType);
1909 return QualType(newType, 0);
1910 }
1911
1912 // Otherwise, we actually build a new type every time, but we
1913 // also build a canonical type.
1914
1915 SplitQualType canonElementType = getCanonicalType(elementType).split();
1916
1917 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001918 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001919 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00001920 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00001921 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001922
John McCall3b657512011-01-19 10:06:00 +00001923 // Look for an existing type with these properties.
1924 DependentSizedArrayType *canonTy =
1925 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001926
John McCall3b657512011-01-19 10:06:00 +00001927 // If we don't have one, build one.
1928 if (!canonTy) {
1929 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00001930 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00001931 QualType(), numElements, ASM, elementTypeQuals,
1932 brackets);
1933 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1934 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001935 }
1936
John McCall3b657512011-01-19 10:06:00 +00001937 // Apply qualifiers from the element type to the array.
1938 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00001939 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00001940
John McCall3b657512011-01-19 10:06:00 +00001941 // If we didn't need extra canonicalization for the element type,
1942 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00001943 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00001944 return canon;
1945
1946 // Otherwise, we need to build a type which follows the spelling
1947 // of the element type.
1948 DependentSizedArrayType *sugaredType
1949 = new (*this, TypeAlignment)
1950 DependentSizedArrayType(*this, elementType, canon, numElements,
1951 ASM, elementTypeQuals, brackets);
1952 Types.push_back(sugaredType);
1953 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00001954}
1955
John McCall3b657512011-01-19 10:06:00 +00001956QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00001957 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001958 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001959 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001960 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001961
John McCall3b657512011-01-19 10:06:00 +00001962 void *insertPos = 0;
1963 if (IncompleteArrayType *iat =
1964 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1965 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001966
1967 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00001968 // either, so fill in the canonical type field. We also have to pull
1969 // qualifiers off the element type.
1970 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00001971
John McCall3b657512011-01-19 10:06:00 +00001972 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1973 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00001974 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00001975 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00001976 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001977
1978 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00001979 IncompleteArrayType *existing =
1980 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1981 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001982 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001983
John McCall3b657512011-01-19 10:06:00 +00001984 IncompleteArrayType *newType = new (*this, TypeAlignment)
1985 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001986
John McCall3b657512011-01-19 10:06:00 +00001987 IncompleteArrayTypes.InsertNode(newType, insertPos);
1988 Types.push_back(newType);
1989 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001990}
1991
Steve Naroff73322922007-07-18 18:00:27 +00001992/// getVectorType - Return the unique reference to a vector type of
1993/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001994QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00001995 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00001996 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001997
Reid Spencer5f016e22007-07-11 17:01:13 +00001998 // Check if we've already instantiated a vector of this type.
1999 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002000 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002001
Reid Spencer5f016e22007-07-11 17:01:13 +00002002 void *InsertPos = 0;
2003 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2004 return QualType(VTP, 0);
2005
2006 // If the element type isn't canonical, this won't be a canonical type either,
2007 // so fill in the canonical type field.
2008 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002009 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002010 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002011
Reid Spencer5f016e22007-07-11 17:01:13 +00002012 // Get the new insert position for the node we care about.
2013 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002014 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002015 }
John McCall6b304a02009-09-24 23:30:46 +00002016 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002017 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002018 VectorTypes.InsertNode(New, InsertPos);
2019 Types.push_back(New);
2020 return QualType(New, 0);
2021}
2022
Nate Begeman213541a2008-04-18 23:10:10 +00002023/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002024/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002025QualType
2026ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002027 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002028
Steve Naroff73322922007-07-18 18:00:27 +00002029 // Check if we've already instantiated a vector of this type.
2030 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002031 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002032 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002033 void *InsertPos = 0;
2034 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2035 return QualType(VTP, 0);
2036
2037 // If the element type isn't canonical, this won't be a canonical type either,
2038 // so fill in the canonical type field.
2039 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002040 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002041 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002042
Steve Naroff73322922007-07-18 18:00:27 +00002043 // Get the new insert position for the node we care about.
2044 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002045 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002046 }
John McCall6b304a02009-09-24 23:30:46 +00002047 ExtVectorType *New = new (*this, TypeAlignment)
2048 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002049 VectorTypes.InsertNode(New, InsertPos);
2050 Types.push_back(New);
2051 return QualType(New, 0);
2052}
2053
Jay Foad4ba2a172011-01-12 09:06:06 +00002054QualType
2055ASTContext::getDependentSizedExtVectorType(QualType vecType,
2056 Expr *SizeExpr,
2057 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002058 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002059 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002060 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002061
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002062 void *InsertPos = 0;
2063 DependentSizedExtVectorType *Canon
2064 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2065 DependentSizedExtVectorType *New;
2066 if (Canon) {
2067 // We already have a canonical version of this array type; use it as
2068 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002069 New = new (*this, TypeAlignment)
2070 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2071 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002072 } else {
2073 QualType CanonVecTy = getCanonicalType(vecType);
2074 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002075 New = new (*this, TypeAlignment)
2076 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2077 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002078
2079 DependentSizedExtVectorType *CanonCheck
2080 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2081 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2082 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002083 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2084 } else {
2085 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2086 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002087 New = new (*this, TypeAlignment)
2088 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002089 }
2090 }
Mike Stump1eb44332009-09-09 15:08:12 +00002091
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002092 Types.push_back(New);
2093 return QualType(New, 0);
2094}
2095
Douglas Gregor72564e72009-02-26 23:50:07 +00002096/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002097///
Jay Foad4ba2a172011-01-12 09:06:06 +00002098QualType
2099ASTContext::getFunctionNoProtoType(QualType ResultTy,
2100 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002101 const CallingConv DefaultCC = Info.getCC();
2102 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2103 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002104 // Unique functions, to guarantee there is only one function of a particular
2105 // structure.
2106 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002107 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002108
Reid Spencer5f016e22007-07-11 17:01:13 +00002109 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002110 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002111 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002112 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002113
Reid Spencer5f016e22007-07-11 17:01:13 +00002114 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002115 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002116 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002117 Canonical =
2118 getFunctionNoProtoType(getCanonicalType(ResultTy),
2119 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002120
Reid Spencer5f016e22007-07-11 17:01:13 +00002121 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002122 FunctionNoProtoType *NewIP =
2123 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002124 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002125 }
Mike Stump1eb44332009-09-09 15:08:12 +00002126
Roman Divackycfe9af22011-03-01 17:40:53 +00002127 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002128 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002129 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002130 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002131 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002132 return QualType(New, 0);
2133}
2134
2135/// getFunctionType - Return a normal function type with a typed argument
2136/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002137QualType
2138ASTContext::getFunctionType(QualType ResultTy,
2139 const QualType *ArgArray, unsigned NumArgs,
2140 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002141 // Unique functions, to guarantee there is only one function of a particular
2142 // structure.
2143 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002144 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002145
2146 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002147 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002148 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002149 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002150
2151 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002152 bool isCanonical =
2153 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2154 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002155 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002156 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002157 isCanonical = false;
2158
Roman Divackycfe9af22011-03-01 17:40:53 +00002159 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2160 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2161 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002162
Reid Spencer5f016e22007-07-11 17:01:13 +00002163 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002164 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002165 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002166 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002167 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002168 CanonicalArgs.reserve(NumArgs);
2169 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002170 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002171
John McCalle23cf432010-12-14 08:05:40 +00002172 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002173 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002174 CanonicalEPI.ExceptionSpecType = EST_None;
2175 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002176 CanonicalEPI.ExtInfo
2177 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2178
Chris Lattnerf52ab252008-04-06 22:59:24 +00002179 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00002180 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002181 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002182
Reid Spencer5f016e22007-07-11 17:01:13 +00002183 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002184 FunctionProtoType *NewIP =
2185 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002186 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002187 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002188
John McCallf85e1932011-06-15 23:02:42 +00002189 // FunctionProtoType objects are allocated with extra bytes after
2190 // them for three variable size arrays at the end:
2191 // - parameter types
2192 // - exception types
2193 // - consumed-arguments flags
2194 // Instead of the exception types, there could be a noexcept
2195 // expression.
John McCalle23cf432010-12-14 08:05:40 +00002196 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002197 NumArgs * sizeof(QualType);
2198 if (EPI.ExceptionSpecType == EST_Dynamic)
2199 Size += EPI.NumExceptions * sizeof(QualType);
2200 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002201 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002202 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002203 Size += 2 * sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002204 }
John McCallf85e1932011-06-15 23:02:42 +00002205 if (EPI.ConsumedArguments)
2206 Size += NumArgs * sizeof(bool);
2207
John McCalle23cf432010-12-14 08:05:40 +00002208 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002209 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2210 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002211 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002212 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002213 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002214 return QualType(FTP, 0);
2215}
2216
John McCall3cb0ebd2010-03-10 03:28:59 +00002217#ifndef NDEBUG
2218static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2219 if (!isa<CXXRecordDecl>(D)) return false;
2220 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2221 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2222 return true;
2223 if (RD->getDescribedClassTemplate() &&
2224 !isa<ClassTemplateSpecializationDecl>(RD))
2225 return true;
2226 return false;
2227}
2228#endif
2229
2230/// getInjectedClassNameType - Return the unique reference to the
2231/// injected class name type for the specified templated declaration.
2232QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002233 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002234 assert(NeedsInjectedClassNameType(Decl));
2235 if (Decl->TypeForDecl) {
2236 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002237 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002238 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2239 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2240 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2241 } else {
John McCallf4c73712011-01-19 06:33:43 +00002242 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002243 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002244 Decl->TypeForDecl = newType;
2245 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002246 }
2247 return QualType(Decl->TypeForDecl, 0);
2248}
2249
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002250/// getTypeDeclType - Return the unique reference to the type for the
2251/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002252QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002253 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002254 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002255
Richard Smith162e1c12011-04-15 14:24:37 +00002256 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002257 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002258
John McCallbecb8d52010-03-10 06:48:02 +00002259 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2260 "Template type parameter types are always available.");
2261
John McCall19c85762010-02-16 03:57:14 +00002262 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002263 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002264 "struct/union has previous declaration");
2265 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002266 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002267 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002268 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002269 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002270 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002271 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002272 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002273 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2274 Decl->TypeForDecl = newType;
2275 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002276 } else
John McCallbecb8d52010-03-10 06:48:02 +00002277 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002278
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002279 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002280}
2281
Reid Spencer5f016e22007-07-11 17:01:13 +00002282/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002283/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002284QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002285ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2286 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002287 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002288
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002289 if (Canonical.isNull())
2290 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002291 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002292 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002293 Decl->TypeForDecl = newType;
2294 Types.push_back(newType);
2295 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002296}
2297
Jay Foad4ba2a172011-01-12 09:06:06 +00002298QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002299 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2300
Douglas Gregoref96ee02012-01-14 16:38:05 +00002301 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002302 if (PrevDecl->TypeForDecl)
2303 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2304
John McCallf4c73712011-01-19 06:33:43 +00002305 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2306 Decl->TypeForDecl = newType;
2307 Types.push_back(newType);
2308 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002309}
2310
Jay Foad4ba2a172011-01-12 09:06:06 +00002311QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002312 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2313
Douglas Gregoref96ee02012-01-14 16:38:05 +00002314 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002315 if (PrevDecl->TypeForDecl)
2316 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2317
John McCallf4c73712011-01-19 06:33:43 +00002318 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2319 Decl->TypeForDecl = newType;
2320 Types.push_back(newType);
2321 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002322}
2323
John McCall9d156a72011-01-06 01:58:22 +00002324QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2325 QualType modifiedType,
2326 QualType equivalentType) {
2327 llvm::FoldingSetNodeID id;
2328 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2329
2330 void *insertPos = 0;
2331 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2332 if (type) return QualType(type, 0);
2333
2334 QualType canon = getCanonicalType(equivalentType);
2335 type = new (*this, TypeAlignment)
2336 AttributedType(canon, attrKind, modifiedType, equivalentType);
2337
2338 Types.push_back(type);
2339 AttributedTypes.InsertNode(type, insertPos);
2340
2341 return QualType(type, 0);
2342}
2343
2344
John McCall49a832b2009-10-18 09:09:24 +00002345/// \brief Retrieve a substitution-result type.
2346QualType
2347ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002348 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002349 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002350 && "replacement types must always be canonical");
2351
2352 llvm::FoldingSetNodeID ID;
2353 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2354 void *InsertPos = 0;
2355 SubstTemplateTypeParmType *SubstParm
2356 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2357
2358 if (!SubstParm) {
2359 SubstParm = new (*this, TypeAlignment)
2360 SubstTemplateTypeParmType(Parm, Replacement);
2361 Types.push_back(SubstParm);
2362 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2363 }
2364
2365 return QualType(SubstParm, 0);
2366}
2367
Douglas Gregorc3069d62011-01-14 02:55:32 +00002368/// \brief Retrieve a
2369QualType ASTContext::getSubstTemplateTypeParmPackType(
2370 const TemplateTypeParmType *Parm,
2371 const TemplateArgument &ArgPack) {
2372#ifndef NDEBUG
2373 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2374 PEnd = ArgPack.pack_end();
2375 P != PEnd; ++P) {
2376 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2377 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2378 }
2379#endif
2380
2381 llvm::FoldingSetNodeID ID;
2382 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2383 void *InsertPos = 0;
2384 if (SubstTemplateTypeParmPackType *SubstParm
2385 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2386 return QualType(SubstParm, 0);
2387
2388 QualType Canon;
2389 if (!Parm->isCanonicalUnqualified()) {
2390 Canon = getCanonicalType(QualType(Parm, 0));
2391 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2392 ArgPack);
2393 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2394 }
2395
2396 SubstTemplateTypeParmPackType *SubstParm
2397 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2398 ArgPack);
2399 Types.push_back(SubstParm);
2400 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2401 return QualType(SubstParm, 0);
2402}
2403
Douglas Gregorfab9d672009-02-05 23:33:38 +00002404/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002405/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002406/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002407QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002408 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002409 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002410 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002411 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002412 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002413 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002414 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2415
2416 if (TypeParm)
2417 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002418
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002419 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002420 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002421 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002422
2423 TemplateTypeParmType *TypeCheck
2424 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2425 assert(!TypeCheck && "Template type parameter canonical type broken");
2426 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002427 } else
John McCall6b304a02009-09-24 23:30:46 +00002428 TypeParm = new (*this, TypeAlignment)
2429 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002430
2431 Types.push_back(TypeParm);
2432 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2433
2434 return QualType(TypeParm, 0);
2435}
2436
John McCall3cb0ebd2010-03-10 03:28:59 +00002437TypeSourceInfo *
2438ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2439 SourceLocation NameLoc,
2440 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002441 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002442 assert(!Name.getAsDependentTemplateName() &&
2443 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002444 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002445
2446 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2447 TemplateSpecializationTypeLoc TL
2448 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002449 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00002450 TL.setTemplateNameLoc(NameLoc);
2451 TL.setLAngleLoc(Args.getLAngleLoc());
2452 TL.setRAngleLoc(Args.getRAngleLoc());
2453 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2454 TL.setArgLocInfo(i, Args[i].getLocInfo());
2455 return DI;
2456}
2457
Mike Stump1eb44332009-09-09 15:08:12 +00002458QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002459ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002460 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002461 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002462 assert(!Template.getAsDependentTemplateName() &&
2463 "No dependent template names here!");
2464
John McCalld5532b62009-11-23 01:53:49 +00002465 unsigned NumArgs = Args.size();
2466
Chris Lattner5f9e2722011-07-23 10:55:15 +00002467 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002468 ArgVec.reserve(NumArgs);
2469 for (unsigned i = 0; i != NumArgs; ++i)
2470 ArgVec.push_back(Args[i].getArgument());
2471
John McCall31f17ec2010-04-27 00:57:59 +00002472 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002473 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002474}
2475
Douglas Gregorb70126a2012-02-03 17:16:23 +00002476#ifndef NDEBUG
2477static bool hasAnyPackExpansions(const TemplateArgument *Args,
2478 unsigned NumArgs) {
2479 for (unsigned I = 0; I != NumArgs; ++I)
2480 if (Args[I].isPackExpansion())
2481 return true;
2482
2483 return true;
2484}
2485#endif
2486
John McCall833ca992009-10-29 08:12:44 +00002487QualType
2488ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002489 const TemplateArgument *Args,
2490 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002491 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002492 assert(!Template.getAsDependentTemplateName() &&
2493 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002494 // Look through qualified template names.
2495 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2496 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002497
Douglas Gregorb70126a2012-02-03 17:16:23 +00002498 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00002499 Template.getAsTemplateDecl() &&
2500 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00002501 QualType CanonType;
2502 if (!Underlying.isNull())
2503 CanonType = getCanonicalType(Underlying);
2504 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00002505 // We can get here with an alias template when the specialization contains
2506 // a pack expansion that does not match up with a parameter pack.
2507 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2508 "Caller must compute aliased type");
2509 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00002510 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2511 NumArgs);
2512 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002513
Douglas Gregor1275ae02009-07-28 23:00:59 +00002514 // Allocate the (non-canonical) template specialization type, but don't
2515 // try to unique it: these types typically have location information that
2516 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002517 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2518 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00002519 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00002520 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002521 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00002522 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2523 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00002524
Douglas Gregor55f6b142009-02-09 18:46:07 +00002525 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002526 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002527}
2528
Mike Stump1eb44332009-09-09 15:08:12 +00002529QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002530ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2531 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002532 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002533 assert(!Template.getAsDependentTemplateName() &&
2534 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002535
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002536 // Look through qualified template names.
2537 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2538 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002539
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002540 // Build the canonical template specialization type.
2541 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002542 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002543 CanonArgs.reserve(NumArgs);
2544 for (unsigned I = 0; I != NumArgs; ++I)
2545 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2546
2547 // Determine whether this canonical template specialization type already
2548 // exists.
2549 llvm::FoldingSetNodeID ID;
2550 TemplateSpecializationType::Profile(ID, CanonTemplate,
2551 CanonArgs.data(), NumArgs, *this);
2552
2553 void *InsertPos = 0;
2554 TemplateSpecializationType *Spec
2555 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2556
2557 if (!Spec) {
2558 // Allocate a new canonical template specialization type.
2559 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2560 sizeof(TemplateArgument) * NumArgs),
2561 TypeAlignment);
2562 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2563 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002564 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002565 Types.push_back(Spec);
2566 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2567 }
2568
2569 assert(Spec->isDependentType() &&
2570 "Non-dependent template-id type must have a canonical type");
2571 return QualType(Spec, 0);
2572}
2573
2574QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002575ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2576 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002577 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002578 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002579 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002580
2581 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002582 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002583 if (T)
2584 return QualType(T, 0);
2585
Douglas Gregor789b1f62010-02-04 18:10:26 +00002586 QualType Canon = NamedType;
2587 if (!Canon.isCanonical()) {
2588 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002589 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2590 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002591 (void)CheckT;
2592 }
2593
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002594 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002595 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002596 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002597 return QualType(T, 0);
2598}
2599
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002600QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002601ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002602 llvm::FoldingSetNodeID ID;
2603 ParenType::Profile(ID, InnerType);
2604
2605 void *InsertPos = 0;
2606 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2607 if (T)
2608 return QualType(T, 0);
2609
2610 QualType Canon = InnerType;
2611 if (!Canon.isCanonical()) {
2612 Canon = getCanonicalType(InnerType);
2613 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2614 assert(!CheckT && "Paren canonical type broken");
2615 (void)CheckT;
2616 }
2617
2618 T = new (*this) ParenType(InnerType, Canon);
2619 Types.push_back(T);
2620 ParenTypes.InsertNode(T, InsertPos);
2621 return QualType(T, 0);
2622}
2623
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002624QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2625 NestedNameSpecifier *NNS,
2626 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002627 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002628 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2629
2630 if (Canon.isNull()) {
2631 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002632 ElaboratedTypeKeyword CanonKeyword = Keyword;
2633 if (Keyword == ETK_None)
2634 CanonKeyword = ETK_Typename;
2635
2636 if (CanonNNS != NNS || CanonKeyword != Keyword)
2637 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002638 }
2639
2640 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002641 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002642
2643 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002644 DependentNameType *T
2645 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002646 if (T)
2647 return QualType(T, 0);
2648
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002649 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002650 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002651 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002652 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002653}
2654
Mike Stump1eb44332009-09-09 15:08:12 +00002655QualType
John McCall33500952010-06-11 00:33:02 +00002656ASTContext::getDependentTemplateSpecializationType(
2657 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002658 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002659 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002660 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00002661 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00002662 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00002663 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2664 ArgCopy.push_back(Args[I].getArgument());
2665 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2666 ArgCopy.size(),
2667 ArgCopy.data());
2668}
2669
2670QualType
2671ASTContext::getDependentTemplateSpecializationType(
2672 ElaboratedTypeKeyword Keyword,
2673 NestedNameSpecifier *NNS,
2674 const IdentifierInfo *Name,
2675 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002676 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00002677 assert((!NNS || NNS->isDependent()) &&
2678 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00002679
Douglas Gregor789b1f62010-02-04 18:10:26 +00002680 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002681 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2682 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002683
2684 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002685 DependentTemplateSpecializationType *T
2686 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002687 if (T)
2688 return QualType(T, 0);
2689
John McCall33500952010-06-11 00:33:02 +00002690 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002691
John McCall33500952010-06-11 00:33:02 +00002692 ElaboratedTypeKeyword CanonKeyword = Keyword;
2693 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2694
2695 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002696 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00002697 for (unsigned I = 0; I != NumArgs; ++I) {
2698 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2699 if (!CanonArgs[I].structurallyEquals(Args[I]))
2700 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002701 }
2702
John McCall33500952010-06-11 00:33:02 +00002703 QualType Canon;
2704 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2705 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2706 Name, NumArgs,
2707 CanonArgs.data());
2708
2709 // Find the insert position again.
2710 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2711 }
2712
2713 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2714 sizeof(TemplateArgument) * NumArgs),
2715 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002716 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002717 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002718 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002719 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002720 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002721}
2722
Douglas Gregorcded4f62011-01-14 17:04:44 +00002723QualType ASTContext::getPackExpansionType(QualType Pattern,
2724 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00002725 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002726 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002727
2728 assert(Pattern->containsUnexpandedParameterPack() &&
2729 "Pack expansions must expand one or more parameter packs");
2730 void *InsertPos = 0;
2731 PackExpansionType *T
2732 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2733 if (T)
2734 return QualType(T, 0);
2735
2736 QualType Canon;
2737 if (!Pattern.isCanonical()) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002738 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002739
2740 // Find the insert position again.
2741 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2742 }
2743
Douglas Gregorcded4f62011-01-14 17:04:44 +00002744 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002745 Types.push_back(T);
2746 PackExpansionTypes.InsertNode(T, InsertPos);
2747 return QualType(T, 0);
2748}
2749
Chris Lattner88cb27a2008-04-07 04:56:42 +00002750/// CmpProtocolNames - Comparison predicate for sorting protocols
2751/// alphabetically.
2752static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2753 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002754 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002755}
2756
John McCallc12c5bb2010-05-15 11:32:37 +00002757static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002758 unsigned NumProtocols) {
2759 if (NumProtocols == 0) return true;
2760
Douglas Gregor61cc2962012-01-02 02:00:30 +00002761 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2762 return false;
2763
John McCall54e14c42009-10-22 22:37:11 +00002764 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00002765 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2766 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00002767 return false;
2768 return true;
2769}
2770
2771static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002772 unsigned &NumProtocols) {
2773 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002774
Chris Lattner88cb27a2008-04-07 04:56:42 +00002775 // Sort protocols, keyed by name.
2776 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2777
Douglas Gregor61cc2962012-01-02 02:00:30 +00002778 // Canonicalize.
2779 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2780 Protocols[I] = Protocols[I]->getCanonicalDecl();
2781
Chris Lattner88cb27a2008-04-07 04:56:42 +00002782 // Remove duplicates.
2783 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2784 NumProtocols = ProtocolsEnd-Protocols;
2785}
2786
John McCallc12c5bb2010-05-15 11:32:37 +00002787QualType ASTContext::getObjCObjectType(QualType BaseType,
2788 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00002789 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002790 // If the base type is an interface and there aren't any protocols
2791 // to add, then the interface type will do just fine.
2792 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2793 return BaseType;
2794
2795 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002796 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002797 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002798 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002799 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2800 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002801
John McCallc12c5bb2010-05-15 11:32:37 +00002802 // Build the canonical type, which has the canonical base type and
2803 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002804 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002805 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2806 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2807 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002808 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00002809 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002810 unsigned UniqueCount = NumProtocols;
2811
John McCall54e14c42009-10-22 22:37:11 +00002812 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002813 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2814 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002815 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002816 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2817 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002818 }
2819
2820 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002821 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2822 }
2823
2824 unsigned Size = sizeof(ObjCObjectTypeImpl);
2825 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2826 void *Mem = Allocate(Size, TypeAlignment);
2827 ObjCObjectTypeImpl *T =
2828 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2829
2830 Types.push_back(T);
2831 ObjCObjectTypes.InsertNode(T, InsertPos);
2832 return QualType(T, 0);
2833}
2834
2835/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2836/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002837QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002838 llvm::FoldingSetNodeID ID;
2839 ObjCObjectPointerType::Profile(ID, ObjectT);
2840
2841 void *InsertPos = 0;
2842 if (ObjCObjectPointerType *QT =
2843 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2844 return QualType(QT, 0);
2845
2846 // Find the canonical object type.
2847 QualType Canonical;
2848 if (!ObjectT.isCanonical()) {
2849 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2850
2851 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002852 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2853 }
2854
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002855 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002856 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2857 ObjCObjectPointerType *QType =
2858 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002859
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002860 Types.push_back(QType);
2861 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002862 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002863}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002864
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002865/// getObjCInterfaceType - Return the unique reference to the type for the
2866/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00002867QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
2868 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002869 if (Decl->TypeForDecl)
2870 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002871
Douglas Gregor0af55012011-12-16 03:12:41 +00002872 if (PrevDecl) {
2873 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
2874 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2875 return QualType(PrevDecl->TypeForDecl, 0);
2876 }
2877
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00002878 // Prefer the definition, if there is one.
2879 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
2880 Decl = Def;
2881
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002882 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2883 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2884 Decl->TypeForDecl = T;
2885 Types.push_back(T);
2886 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002887}
2888
Douglas Gregor72564e72009-02-26 23:50:07 +00002889/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2890/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002891/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002892/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002893/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002894QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002895 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002896 if (tofExpr->isTypeDependent()) {
2897 llvm::FoldingSetNodeID ID;
2898 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002899
Douglas Gregorb1975722009-07-30 23:18:24 +00002900 void *InsertPos = 0;
2901 DependentTypeOfExprType *Canon
2902 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2903 if (Canon) {
2904 // We already have a "canonical" version of an identical, dependent
2905 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002906 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002907 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00002908 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00002909 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002910 Canon
2911 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002912 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2913 toe = Canon;
2914 }
2915 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002916 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002917 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002918 }
Steve Naroff9752f252007-08-01 18:02:17 +00002919 Types.push_back(toe);
2920 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002921}
2922
Steve Naroff9752f252007-08-01 18:02:17 +00002923/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2924/// TypeOfType AST's. The only motivation to unique these nodes would be
2925/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002926/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002927/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002928QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002929 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002930 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002931 Types.push_back(tot);
2932 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002933}
2934
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002935
Anders Carlsson395b4752009-06-24 19:06:50 +00002936/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2937/// DecltypeType AST's. The only motivation to unique these nodes would be
2938/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002939/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00002940/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00002941QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002942 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00002943
2944 // C++0x [temp.type]p2:
2945 // If an expression e involves a template parameter, decltype(e) denotes a
2946 // unique dependent type. Two such decltype-specifiers refer to the same
2947 // type only if their expressions are equivalent (14.5.6.1).
2948 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002949 llvm::FoldingSetNodeID ID;
2950 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002951
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002952 void *InsertPos = 0;
2953 DependentDecltypeType *Canon
2954 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2955 if (Canon) {
2956 // We already have a "canonical" version of an equivalent, dependent
2957 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002958 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002959 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00002960 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002961 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002962 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002963 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2964 dt = Canon;
2965 }
2966 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00002967 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
2968 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002969 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002970 Types.push_back(dt);
2971 return QualType(dt, 0);
2972}
2973
Sean Huntca63c202011-05-24 22:41:36 +00002974/// getUnaryTransformationType - We don't unique these, since the memory
2975/// savings are minimal and these are rare.
2976QualType ASTContext::getUnaryTransformType(QualType BaseType,
2977 QualType UnderlyingType,
2978 UnaryTransformType::UTTKind Kind)
2979 const {
2980 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00002981 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2982 Kind,
2983 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00002984 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00002985 Types.push_back(Ty);
2986 return QualType(Ty, 0);
2987}
2988
Richard Smith483b9f32011-02-21 20:05:19 +00002989/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00002990QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00002991 void *InsertPos = 0;
2992 if (!DeducedType.isNull()) {
2993 // Look in the folding set for an existing type.
2994 llvm::FoldingSetNodeID ID;
2995 AutoType::Profile(ID, DeducedType);
2996 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2997 return QualType(AT, 0);
2998 }
2999
3000 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3001 Types.push_back(AT);
3002 if (InsertPos)
3003 AutoTypes.InsertNode(AT, InsertPos);
3004 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003005}
3006
Eli Friedmanb001de72011-10-06 23:00:33 +00003007/// getAtomicType - Return the uniqued reference to the atomic type for
3008/// the given value type.
3009QualType ASTContext::getAtomicType(QualType T) const {
3010 // Unique pointers, to guarantee there is only one pointer of a particular
3011 // structure.
3012 llvm::FoldingSetNodeID ID;
3013 AtomicType::Profile(ID, T);
3014
3015 void *InsertPos = 0;
3016 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3017 return QualType(AT, 0);
3018
3019 // If the atomic value type isn't canonical, this won't be a canonical type
3020 // either, so fill in the canonical type field.
3021 QualType Canonical;
3022 if (!T.isCanonical()) {
3023 Canonical = getAtomicType(getCanonicalType(T));
3024
3025 // Get the new insert position for the node we care about.
3026 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3027 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3028 }
3029 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3030 Types.push_back(New);
3031 AtomicTypes.InsertNode(New, InsertPos);
3032 return QualType(New, 0);
3033}
3034
Richard Smithad762fc2011-04-14 22:09:26 +00003035/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3036QualType ASTContext::getAutoDeductType() const {
3037 if (AutoDeductTy.isNull())
3038 AutoDeductTy = getAutoType(QualType());
3039 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3040 return AutoDeductTy;
3041}
3042
3043/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3044QualType ASTContext::getAutoRRefDeductType() const {
3045 if (AutoRRefDeductTy.isNull())
3046 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3047 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3048 return AutoRRefDeductTy;
3049}
3050
Reid Spencer5f016e22007-07-11 17:01:13 +00003051/// getTagDeclType - Return the unique reference to the type for the
3052/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003053QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003054 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003055 // FIXME: What is the design on getTagDeclType when it requires casting
3056 // away const? mutable?
3057 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003058}
3059
Mike Stump1eb44332009-09-09 15:08:12 +00003060/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3061/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3062/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003063CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003064 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003065}
3066
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003067/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3068CanQualType ASTContext::getIntMaxType() const {
3069 return getFromTargetType(Target->getIntMaxType());
3070}
3071
3072/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3073CanQualType ASTContext::getUIntMaxType() const {
3074 return getFromTargetType(Target->getUIntMaxType());
3075}
3076
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003077/// getSignedWCharType - Return the type of "signed wchar_t".
3078/// Used when in C++, as a GCC extension.
3079QualType ASTContext::getSignedWCharType() const {
3080 // FIXME: derive from "Target" ?
3081 return WCharTy;
3082}
3083
3084/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3085/// Used when in C++, as a GCC extension.
3086QualType ASTContext::getUnsignedWCharType() const {
3087 // FIXME: derive from "Target" ?
3088 return UnsignedIntTy;
3089}
3090
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003091/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003092/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3093QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003094 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003095}
3096
Chris Lattnere6327742008-04-02 05:18:44 +00003097//===----------------------------------------------------------------------===//
3098// Type Operators
3099//===----------------------------------------------------------------------===//
3100
Jay Foad4ba2a172011-01-12 09:06:06 +00003101CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003102 // Push qualifiers into arrays, and then discard any remaining
3103 // qualifiers.
3104 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003105 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003106 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003107 QualType Result;
3108 if (isa<ArrayType>(Ty)) {
3109 Result = getArrayDecayedType(QualType(Ty,0));
3110 } else if (isa<FunctionType>(Ty)) {
3111 Result = getPointerType(QualType(Ty, 0));
3112 } else {
3113 Result = QualType(Ty, 0);
3114 }
3115
3116 return CanQualType::CreateUnsafe(Result);
3117}
3118
John McCall62c28c82011-01-18 07:41:22 +00003119QualType ASTContext::getUnqualifiedArrayType(QualType type,
3120 Qualifiers &quals) {
3121 SplitQualType splitType = type.getSplitUnqualifiedType();
3122
3123 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3124 // the unqualified desugared type and then drops it on the floor.
3125 // We then have to strip that sugar back off with
3126 // getUnqualifiedDesugaredType(), which is silly.
3127 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003128 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003129
3130 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003131 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003132 quals = splitType.Quals;
3133 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003134 }
3135
John McCall62c28c82011-01-18 07:41:22 +00003136 // Otherwise, recurse on the array's element type.
3137 QualType elementType = AT->getElementType();
3138 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3139
3140 // If that didn't change the element type, AT has no qualifiers, so we
3141 // can just use the results in splitType.
3142 if (elementType == unqualElementType) {
3143 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003144 quals = splitType.Quals;
3145 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003146 }
3147
3148 // Otherwise, add in the qualifiers from the outermost type, then
3149 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003150 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003151
Douglas Gregor9dadd942010-05-17 18:45:21 +00003152 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003153 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003154 CAT->getSizeModifier(), 0);
3155 }
3156
Douglas Gregor9dadd942010-05-17 18:45:21 +00003157 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003158 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003159 }
3160
Douglas Gregor9dadd942010-05-17 18:45:21 +00003161 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003162 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003163 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003164 VAT->getSizeModifier(),
3165 VAT->getIndexTypeCVRQualifiers(),
3166 VAT->getBracketsRange());
3167 }
3168
3169 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003170 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003171 DSAT->getSizeModifier(), 0,
3172 SourceRange());
3173}
3174
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003175/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3176/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3177/// they point to and return true. If T1 and T2 aren't pointer types
3178/// or pointer-to-member types, or if they are not similar at this
3179/// level, returns false and leaves T1 and T2 unchanged. Top-level
3180/// qualifiers on T1 and T2 are ignored. This function will typically
3181/// be called in a loop that successively "unwraps" pointer and
3182/// pointer-to-member types to compare them at each level.
3183bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3184 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3185 *T2PtrType = T2->getAs<PointerType>();
3186 if (T1PtrType && T2PtrType) {
3187 T1 = T1PtrType->getPointeeType();
3188 T2 = T2PtrType->getPointeeType();
3189 return true;
3190 }
3191
3192 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3193 *T2MPType = T2->getAs<MemberPointerType>();
3194 if (T1MPType && T2MPType &&
3195 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3196 QualType(T2MPType->getClass(), 0))) {
3197 T1 = T1MPType->getPointeeType();
3198 T2 = T2MPType->getPointeeType();
3199 return true;
3200 }
3201
David Blaikie4e4d0842012-03-11 07:00:24 +00003202 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003203 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3204 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3205 if (T1OPType && T2OPType) {
3206 T1 = T1OPType->getPointeeType();
3207 T2 = T2OPType->getPointeeType();
3208 return true;
3209 }
3210 }
3211
3212 // FIXME: Block pointers, too?
3213
3214 return false;
3215}
3216
Jay Foad4ba2a172011-01-12 09:06:06 +00003217DeclarationNameInfo
3218ASTContext::getNameForTemplate(TemplateName Name,
3219 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003220 switch (Name.getKind()) {
3221 case TemplateName::QualifiedTemplate:
3222 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003223 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003224 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3225 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003226
John McCall14606042011-06-30 08:33:18 +00003227 case TemplateName::OverloadedTemplate: {
3228 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3229 // DNInfo work in progress: CHECKME: what about DNLoc?
3230 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3231 }
3232
3233 case TemplateName::DependentTemplate: {
3234 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003235 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003236 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003237 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3238 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003239 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003240 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3241 // DNInfo work in progress: FIXME: source locations?
3242 DeclarationNameLoc DNLoc;
3243 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3244 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3245 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003246 }
3247 }
3248
John McCall14606042011-06-30 08:33:18 +00003249 case TemplateName::SubstTemplateTemplateParm: {
3250 SubstTemplateTemplateParmStorage *subst
3251 = Name.getAsSubstTemplateTemplateParm();
3252 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3253 NameLoc);
3254 }
3255
3256 case TemplateName::SubstTemplateTemplateParmPack: {
3257 SubstTemplateTemplateParmPackStorage *subst
3258 = Name.getAsSubstTemplateTemplateParmPack();
3259 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3260 NameLoc);
3261 }
3262 }
3263
3264 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003265}
3266
Jay Foad4ba2a172011-01-12 09:06:06 +00003267TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003268 switch (Name.getKind()) {
3269 case TemplateName::QualifiedTemplate:
3270 case TemplateName::Template: {
3271 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003272 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003273 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003274 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3275
3276 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003277 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003278 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003279
John McCall14606042011-06-30 08:33:18 +00003280 case TemplateName::OverloadedTemplate:
3281 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003282
John McCall14606042011-06-30 08:33:18 +00003283 case TemplateName::DependentTemplate: {
3284 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3285 assert(DTN && "Non-dependent template names must refer to template decls.");
3286 return DTN->CanonicalTemplateName;
3287 }
3288
3289 case TemplateName::SubstTemplateTemplateParm: {
3290 SubstTemplateTemplateParmStorage *subst
3291 = Name.getAsSubstTemplateTemplateParm();
3292 return getCanonicalTemplateName(subst->getReplacement());
3293 }
3294
3295 case TemplateName::SubstTemplateTemplateParmPack: {
3296 SubstTemplateTemplateParmPackStorage *subst
3297 = Name.getAsSubstTemplateTemplateParmPack();
3298 TemplateTemplateParmDecl *canonParameter
3299 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3300 TemplateArgument canonArgPack
3301 = getCanonicalTemplateArgument(subst->getArgumentPack());
3302 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3303 }
3304 }
3305
3306 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003307}
3308
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003309bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3310 X = getCanonicalTemplateName(X);
3311 Y = getCanonicalTemplateName(Y);
3312 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3313}
3314
Mike Stump1eb44332009-09-09 15:08:12 +00003315TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003316ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003317 switch (Arg.getKind()) {
3318 case TemplateArgument::Null:
3319 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003320
Douglas Gregor1275ae02009-07-28 23:00:59 +00003321 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003322 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003323
Douglas Gregord2008e22012-04-06 22:40:38 +00003324 case TemplateArgument::Declaration: {
3325 if (Decl *D = Arg.getAsDecl())
3326 return TemplateArgument(D->getCanonicalDecl());
3327 return TemplateArgument((Decl*)0);
3328 }
Mike Stump1eb44332009-09-09 15:08:12 +00003329
Douglas Gregor788cd062009-11-11 01:00:40 +00003330 case TemplateArgument::Template:
3331 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003332
3333 case TemplateArgument::TemplateExpansion:
3334 return TemplateArgument(getCanonicalTemplateName(
3335 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003336 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003337
Douglas Gregor1275ae02009-07-28 23:00:59 +00003338 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00003339 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003340
Douglas Gregor1275ae02009-07-28 23:00:59 +00003341 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003342 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003343
Douglas Gregor1275ae02009-07-28 23:00:59 +00003344 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003345 if (Arg.pack_size() == 0)
3346 return Arg;
3347
Douglas Gregor910f8002010-11-07 23:05:16 +00003348 TemplateArgument *CanonArgs
3349 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003350 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003351 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003352 AEnd = Arg.pack_end();
3353 A != AEnd; (void)++A, ++Idx)
3354 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003355
Douglas Gregor910f8002010-11-07 23:05:16 +00003356 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003357 }
3358 }
3359
3360 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00003361 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00003362}
3363
Douglas Gregord57959a2009-03-27 23:10:48 +00003364NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003365ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003366 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003367 return 0;
3368
3369 switch (NNS->getKind()) {
3370 case NestedNameSpecifier::Identifier:
3371 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003372 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003373 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3374 NNS->getAsIdentifier());
3375
3376 case NestedNameSpecifier::Namespace:
3377 // A namespace is canonical; build a nested-name-specifier with
3378 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003379 return NestedNameSpecifier::Create(*this, 0,
3380 NNS->getAsNamespace()->getOriginalNamespace());
3381
3382 case NestedNameSpecifier::NamespaceAlias:
3383 // A namespace is canonical; build a nested-name-specifier with
3384 // this namespace and no prefix.
3385 return NestedNameSpecifier::Create(*this, 0,
3386 NNS->getAsNamespaceAlias()->getNamespace()
3387 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003388
3389 case NestedNameSpecifier::TypeSpec:
3390 case NestedNameSpecifier::TypeSpecWithTemplate: {
3391 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003392
3393 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3394 // break it apart into its prefix and identifier, then reconsititute those
3395 // as the canonical nested-name-specifier. This is required to canonicalize
3396 // a dependent nested-name-specifier involving typedefs of dependent-name
3397 // types, e.g.,
3398 // typedef typename T::type T1;
3399 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00003400 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3401 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00003402 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00003403
Eli Friedman16412ef2012-03-03 04:09:56 +00003404 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3405 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3406 // first place?
John McCall3b657512011-01-19 10:06:00 +00003407 return NestedNameSpecifier::Create(*this, 0, false,
3408 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003409 }
3410
3411 case NestedNameSpecifier::Global:
3412 // The global specifier is canonical and unique.
3413 return NNS;
3414 }
3415
David Blaikie7530c032012-01-17 06:56:22 +00003416 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00003417}
3418
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003419
Jay Foad4ba2a172011-01-12 09:06:06 +00003420const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003421 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003422 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003423 // Handle the common positive case fast.
3424 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3425 return AT;
3426 }
Mike Stump1eb44332009-09-09 15:08:12 +00003427
John McCall0953e762009-09-24 19:53:00 +00003428 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003429 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003430 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003431
John McCall0953e762009-09-24 19:53:00 +00003432 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003433 // implements C99 6.7.3p8: "If the specification of an array type includes
3434 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003435
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003436 // If we get here, we either have type qualifiers on the type, or we have
3437 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003438 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003439
John McCall3b657512011-01-19 10:06:00 +00003440 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00003441 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00003442
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003443 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00003444 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00003445 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003446 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003447
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003448 // Otherwise, we have an array and we have qualifiers on it. Push the
3449 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003450 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003451
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003452 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3453 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3454 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003455 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003456 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3457 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3458 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003459 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003460
Mike Stump1eb44332009-09-09 15:08:12 +00003461 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003462 = dyn_cast<DependentSizedArrayType>(ATy))
3463 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003464 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003465 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003466 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003467 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003468 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003469
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003470 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003471 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003472 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003473 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003474 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003475 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003476}
3477
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00003478QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003479 // C99 6.7.5.3p7:
3480 // A declaration of a parameter as "array of type" shall be
3481 // adjusted to "qualified pointer to type", where the type
3482 // qualifiers (if any) are those specified within the [ and ] of
3483 // the array type derivation.
3484 if (T->isArrayType())
3485 return getArrayDecayedType(T);
3486
3487 // C99 6.7.5.3p8:
3488 // A declaration of a parameter as "function returning type"
3489 // shall be adjusted to "pointer to function returning type", as
3490 // in 6.3.2.1.
3491 if (T->isFunctionType())
3492 return getPointerType(T);
3493
3494 return T;
3495}
3496
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00003497QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003498 T = getVariableArrayDecayedType(T);
3499 T = getAdjustedParameterType(T);
3500 return T.getUnqualifiedType();
3501}
3502
Chris Lattnere6327742008-04-02 05:18:44 +00003503/// getArrayDecayedType - Return the properly qualified result of decaying the
3504/// specified array type to a pointer. This operation is non-trivial when
3505/// handling typedefs etc. The canonical type of "T" must be an array type,
3506/// this returns a pointer to a properly qualified element of the array.
3507///
3508/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003509QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003510 // Get the element type with 'getAsArrayType' so that we don't lose any
3511 // typedefs in the element type of the array. This also handles propagation
3512 // of type qualifiers from the array type into the element type if present
3513 // (C99 6.7.3p8).
3514 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3515 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003516
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003517 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003518
3519 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003520 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003521}
3522
John McCall3b657512011-01-19 10:06:00 +00003523QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3524 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003525}
3526
John McCall3b657512011-01-19 10:06:00 +00003527QualType ASTContext::getBaseElementType(QualType type) const {
3528 Qualifiers qs;
3529 while (true) {
3530 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00003531 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00003532 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003533
John McCall3b657512011-01-19 10:06:00 +00003534 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00003535 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00003536 }
Mike Stump1eb44332009-09-09 15:08:12 +00003537
John McCall3b657512011-01-19 10:06:00 +00003538 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003539}
3540
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003541/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003542uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003543ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3544 uint64_t ElementCount = 1;
3545 do {
3546 ElementCount *= CA->getSize().getZExtValue();
3547 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3548 } while (CA);
3549 return ElementCount;
3550}
3551
Reid Spencer5f016e22007-07-11 17:01:13 +00003552/// getFloatingRank - Return a relative rank for floating point types.
3553/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003554static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003555 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003556 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003557
John McCall183700f2009-09-21 23:43:11 +00003558 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3559 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003560 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00003561 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00003562 case BuiltinType::Float: return FloatRank;
3563 case BuiltinType::Double: return DoubleRank;
3564 case BuiltinType::LongDouble: return LongDoubleRank;
3565 }
3566}
3567
Mike Stump1eb44332009-09-09 15:08:12 +00003568/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3569/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003570/// 'typeDomain' is a real floating point or complex type.
3571/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003572QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3573 QualType Domain) const {
3574 FloatingRank EltRank = getFloatingRank(Size);
3575 if (Domain->isComplexType()) {
3576 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00003577 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00003578 case FloatRank: return FloatComplexTy;
3579 case DoubleRank: return DoubleComplexTy;
3580 case LongDoubleRank: return LongDoubleComplexTy;
3581 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003582 }
Chris Lattner1361b112008-04-06 23:58:54 +00003583
3584 assert(Domain->isRealFloatingType() && "Unknown domain!");
3585 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00003586 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattner1361b112008-04-06 23:58:54 +00003587 case FloatRank: return FloatTy;
3588 case DoubleRank: return DoubleTy;
3589 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003590 }
David Blaikie561d3ab2012-01-17 02:30:50 +00003591 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00003592}
3593
Chris Lattner7cfeb082008-04-06 23:55:33 +00003594/// getFloatingTypeOrder - Compare the rank of the two specified floating
3595/// point types, ignoring the domain of the type (i.e. 'double' ==
3596/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003597/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003598int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003599 FloatingRank LHSR = getFloatingRank(LHS);
3600 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003601
Chris Lattnera75cea32008-04-06 23:38:49 +00003602 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003603 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003604 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003605 return 1;
3606 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003607}
3608
Chris Lattnerf52ab252008-04-06 22:59:24 +00003609/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3610/// routine will assert if passed a built-in type that isn't an integer or enum,
3611/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003612unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003613 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003614
Chris Lattnerf52ab252008-04-06 22:59:24 +00003615 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003616 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00003617 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003618 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003619 case BuiltinType::Char_S:
3620 case BuiltinType::Char_U:
3621 case BuiltinType::SChar:
3622 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003623 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003624 case BuiltinType::Short:
3625 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003626 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003627 case BuiltinType::Int:
3628 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003629 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003630 case BuiltinType::Long:
3631 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003632 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003633 case BuiltinType::LongLong:
3634 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003635 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003636 case BuiltinType::Int128:
3637 case BuiltinType::UInt128:
3638 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003639 }
3640}
3641
Eli Friedman04e83572009-08-20 04:21:42 +00003642/// \brief Whether this is a promotable bitfield reference according
3643/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3644///
3645/// \returns the type this bit-field will promote to, or NULL if no
3646/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00003647QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003648 if (E->isTypeDependent() || E->isValueDependent())
3649 return QualType();
3650
Eli Friedman04e83572009-08-20 04:21:42 +00003651 FieldDecl *Field = E->getBitField();
3652 if (!Field)
3653 return QualType();
3654
3655 QualType FT = Field->getType();
3656
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003657 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00003658 uint64_t IntSize = getTypeSize(IntTy);
3659 // GCC extension compatibility: if the bit-field size is less than or equal
3660 // to the size of int, it gets promoted no matter what its type is.
3661 // For instance, unsigned long bf : 4 gets promoted to signed int.
3662 if (BitWidth < IntSize)
3663 return IntTy;
3664
3665 if (BitWidth == IntSize)
3666 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3667
3668 // Types bigger than int are not subject to promotions, and therefore act
3669 // like the base type.
3670 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3671 // is ridiculous.
3672 return QualType();
3673}
3674
Eli Friedmana95d7572009-08-19 07:44:53 +00003675/// getPromotedIntegerType - Returns the type that Promotable will
3676/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3677/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003678QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003679 assert(!Promotable.isNull());
3680 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003681 if (const EnumType *ET = Promotable->getAs<EnumType>())
3682 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00003683
3684 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3685 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3686 // (3.9.1) can be converted to a prvalue of the first of the following
3687 // types that can represent all the values of its underlying type:
3688 // int, unsigned int, long int, unsigned long int, long long int, or
3689 // unsigned long long int [...]
3690 // FIXME: Is there some better way to compute this?
3691 if (BT->getKind() == BuiltinType::WChar_S ||
3692 BT->getKind() == BuiltinType::WChar_U ||
3693 BT->getKind() == BuiltinType::Char16 ||
3694 BT->getKind() == BuiltinType::Char32) {
3695 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3696 uint64_t FromSize = getTypeSize(BT);
3697 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3698 LongLongTy, UnsignedLongLongTy };
3699 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3700 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3701 if (FromSize < ToSize ||
3702 (FromSize == ToSize &&
3703 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3704 return PromoteTypes[Idx];
3705 }
3706 llvm_unreachable("char type should fit into long long");
3707 }
3708 }
3709
3710 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00003711 if (Promotable->isSignedIntegerType())
3712 return IntTy;
3713 uint64_t PromotableSize = getTypeSize(Promotable);
3714 uint64_t IntSize = getTypeSize(IntTy);
3715 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3716 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3717}
3718
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003719/// \brief Recurses in pointer/array types until it finds an objc retainable
3720/// type and returns its ownership.
3721Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3722 while (!T.isNull()) {
3723 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3724 return T.getObjCLifetime();
3725 if (T->isArrayType())
3726 T = getBaseElementType(T);
3727 else if (const PointerType *PT = T->getAs<PointerType>())
3728 T = PT->getPointeeType();
3729 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00003730 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003731 else
3732 break;
3733 }
3734
3735 return Qualifiers::OCL_None;
3736}
3737
Mike Stump1eb44332009-09-09 15:08:12 +00003738/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003739/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003740/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003741int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00003742 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3743 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003744 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003745
Chris Lattnerf52ab252008-04-06 22:59:24 +00003746 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3747 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003748
Chris Lattner7cfeb082008-04-06 23:55:33 +00003749 unsigned LHSRank = getIntegerRank(LHSC);
3750 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003751
Chris Lattner7cfeb082008-04-06 23:55:33 +00003752 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3753 if (LHSRank == RHSRank) return 0;
3754 return LHSRank > RHSRank ? 1 : -1;
3755 }
Mike Stump1eb44332009-09-09 15:08:12 +00003756
Chris Lattner7cfeb082008-04-06 23:55:33 +00003757 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3758 if (LHSUnsigned) {
3759 // If the unsigned [LHS] type is larger, return it.
3760 if (LHSRank >= RHSRank)
3761 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003762
Chris Lattner7cfeb082008-04-06 23:55:33 +00003763 // If the signed type can represent all values of the unsigned type, it
3764 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003765 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003766 return -1;
3767 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003768
Chris Lattner7cfeb082008-04-06 23:55:33 +00003769 // If the unsigned [RHS] type is larger, return it.
3770 if (RHSRank >= LHSRank)
3771 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003772
Chris Lattner7cfeb082008-04-06 23:55:33 +00003773 // If the signed type can represent all values of the unsigned type, it
3774 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003775 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003776 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003777}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003778
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003779static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003780CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3781 DeclContext *DC, IdentifierInfo *Id) {
3782 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00003783 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003784 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003785 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003786 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003787}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003788
Mike Stump1eb44332009-09-09 15:08:12 +00003789// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003790QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003791 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003792 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003793 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003794 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003795 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003796
Anders Carlssonf06273f2007-11-19 00:25:30 +00003797 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003798
Anders Carlsson71993dd2007-08-17 05:31:46 +00003799 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003800 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003801 // int flags;
3802 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003803 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003804 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003805 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003806 FieldTypes[3] = LongTy;
3807
Anders Carlsson71993dd2007-08-17 05:31:46 +00003808 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003809 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003810 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003811 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00003812 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003813 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003814 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003815 /*Mutable=*/false,
3816 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003817 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003818 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003819 }
3820
Douglas Gregor838db382010-02-11 01:19:42 +00003821 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003822 }
Mike Stump1eb44332009-09-09 15:08:12 +00003823
Anders Carlsson71993dd2007-08-17 05:31:46 +00003824 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003825}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003826
Douglas Gregor319ac892009-04-23 22:29:11 +00003827void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003828 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003829 assert(Rec && "Invalid CFConstantStringType");
3830 CFConstantStringTypeDecl = Rec->getDecl();
3831}
3832
Jay Foad4ba2a172011-01-12 09:06:06 +00003833QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00003834 if (BlockDescriptorType)
3835 return getTagDeclType(BlockDescriptorType);
3836
3837 RecordDecl *T;
3838 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003839 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003840 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003841 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003842
3843 QualType FieldTypes[] = {
3844 UnsignedLongTy,
3845 UnsignedLongTy,
3846 };
3847
3848 const char *FieldNames[] = {
3849 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003850 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003851 };
3852
3853 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003854 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003855 SourceLocation(),
3856 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003857 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003858 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003859 /*Mutable=*/false,
3860 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003861 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003862 T->addDecl(Field);
3863 }
3864
Douglas Gregor838db382010-02-11 01:19:42 +00003865 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003866
3867 BlockDescriptorType = T;
3868
3869 return getTagDeclType(BlockDescriptorType);
3870}
3871
Jay Foad4ba2a172011-01-12 09:06:06 +00003872QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00003873 if (BlockDescriptorExtendedType)
3874 return getTagDeclType(BlockDescriptorExtendedType);
3875
3876 RecordDecl *T;
3877 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003878 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003879 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003880 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003881
3882 QualType FieldTypes[] = {
3883 UnsignedLongTy,
3884 UnsignedLongTy,
3885 getPointerType(VoidPtrTy),
3886 getPointerType(VoidPtrTy)
3887 };
3888
3889 const char *FieldNames[] = {
3890 "reserved",
3891 "Size",
3892 "CopyFuncPtr",
3893 "DestroyFuncPtr"
3894 };
3895
3896 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003897 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00003898 SourceLocation(),
3899 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003900 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003901 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003902 /*Mutable=*/false,
3903 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003904 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003905 T->addDecl(Field);
3906 }
3907
Douglas Gregor838db382010-02-11 01:19:42 +00003908 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003909
3910 BlockDescriptorExtendedType = T;
3911
3912 return getTagDeclType(BlockDescriptorExtendedType);
3913}
3914
Jay Foad4ba2a172011-01-12 09:06:06 +00003915bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCallf85e1932011-06-15 23:02:42 +00003916 if (Ty->isObjCRetainableType())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003917 return true;
David Blaikie4e4d0842012-03-11 07:00:24 +00003918 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003919 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3920 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Huntffe37fd2011-05-25 20:50:04 +00003921 return RD->hasConstCopyConstructor();
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003922
3923 }
3924 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003925 return false;
3926}
3927
Jay Foad4ba2a172011-01-12 09:06:06 +00003928QualType
Chris Lattner5f9e2722011-07-23 10:55:15 +00003929ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003930 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003931 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003932 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003933 // unsigned int __flags;
3934 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003935 // void *__copy_helper; // as needed
3936 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003937 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003938 // } *
3939
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003940 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3941
3942 // FIXME: Move up
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003943 SmallString<36> Name;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003944 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3945 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003946 RecordDecl *T;
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003947 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003948 T->startDefinition();
3949 QualType Int32Ty = IntTy;
3950 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3951 QualType FieldTypes[] = {
3952 getPointerType(VoidPtrTy),
3953 getPointerType(getTagDeclType(T)),
3954 Int32Ty,
3955 Int32Ty,
3956 getPointerType(VoidPtrTy),
3957 getPointerType(VoidPtrTy),
3958 Ty
3959 };
3960
Chris Lattner5f9e2722011-07-23 10:55:15 +00003961 StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003962 "__isa",
3963 "__forwarding",
3964 "__flags",
3965 "__size",
3966 "__copy_helper",
3967 "__destroy_helper",
3968 DeclName,
3969 };
3970
3971 for (size_t i = 0; i < 7; ++i) {
3972 if (!HasCopyAndDispose && i >=4 && i <= 5)
3973 continue;
3974 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003975 SourceLocation(),
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003976 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003977 FieldTypes[i], /*TInfo=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003978 /*BitWidth=*/0, /*Mutable=*/false,
3979 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003980 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003981 T->addDecl(Field);
3982 }
3983
Douglas Gregor838db382010-02-11 01:19:42 +00003984 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003985
3986 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003987}
3988
Douglas Gregore97179c2011-09-08 01:46:34 +00003989TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
3990 if (!ObjCInstanceTypeDecl)
3991 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
3992 getTranslationUnitDecl(),
3993 SourceLocation(),
3994 SourceLocation(),
3995 &Idents.get("instancetype"),
3996 getTrivialTypeSourceInfo(getObjCIdType()));
3997 return ObjCInstanceTypeDecl;
3998}
3999
Anders Carlssone8c49532007-10-29 06:33:42 +00004000// This returns true if a type has been typedefed to BOOL:
4001// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004002static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004003 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004004 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4005 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004006
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004007 return false;
4008}
4009
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004010/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004011/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004012CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004013 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4014 return CharUnits::Zero();
4015
Ken Dyck199c3d62010-01-11 17:06:35 +00004016 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004017
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004018 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004019 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004020 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004021 // Treat arrays as pointers, since that's how they're passed in.
4022 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004023 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004024 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004025}
4026
4027static inline
4028std::string charUnitsToString(const CharUnits &CU) {
4029 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004030}
4031
John McCall6b5a61b2011-02-07 10:33:21 +00004032/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004033/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004034std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4035 std::string S;
4036
David Chisnall5e530af2009-11-17 19:33:30 +00004037 const BlockDecl *Decl = Expr->getBlockDecl();
4038 QualType BlockTy =
4039 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4040 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00004041 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00004042 // Compute size of all parameters.
4043 // Start with computing size of a pointer in number of bytes.
4044 // FIXME: There might(should) be a better way of doing this computation!
4045 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004046 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4047 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004048 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004049 E = Decl->param_end(); PI != E; ++PI) {
4050 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004051 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00004052 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004053 ParmOffset += sz;
4054 }
4055 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004056 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004057 // Block pointer and offset.
4058 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004059
4060 // Argument types.
4061 ParmOffset = PtrSize;
4062 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4063 Decl->param_end(); PI != E; ++PI) {
4064 ParmVarDecl *PVDecl = *PI;
4065 QualType PType = PVDecl->getOriginalType();
4066 if (const ArrayType *AT =
4067 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4068 // Use array's original type only if it has known number of
4069 // elements.
4070 if (!isa<ConstantArrayType>(AT))
4071 PType = PVDecl->getType();
4072 } else if (PType->isFunctionType())
4073 PType = PVDecl->getType();
4074 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004075 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004076 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004077 }
John McCall6b5a61b2011-02-07 10:33:21 +00004078
4079 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004080}
4081
Douglas Gregorf968d832011-05-27 01:19:52 +00004082bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004083 std::string& S) {
4084 // Encode result type.
4085 getObjCEncodingForType(Decl->getResultType(), S);
4086 CharUnits ParmOffset;
4087 // Compute size of all parameters.
4088 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4089 E = Decl->param_end(); PI != E; ++PI) {
4090 QualType PType = (*PI)->getType();
4091 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004092 if (sz.isZero())
4093 return true;
4094
David Chisnall5389f482010-12-30 14:05:53 +00004095 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004096 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004097 ParmOffset += sz;
4098 }
4099 S += charUnitsToString(ParmOffset);
4100 ParmOffset = CharUnits::Zero();
4101
4102 // Argument types.
4103 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4104 E = Decl->param_end(); PI != E; ++PI) {
4105 ParmVarDecl *PVDecl = *PI;
4106 QualType PType = PVDecl->getOriginalType();
4107 if (const ArrayType *AT =
4108 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4109 // Use array's original type only if it has known number of
4110 // elements.
4111 if (!isa<ConstantArrayType>(AT))
4112 PType = PVDecl->getType();
4113 } else if (PType->isFunctionType())
4114 PType = PVDecl->getType();
4115 getObjCEncodingForType(PType, S);
4116 S += charUnitsToString(ParmOffset);
4117 ParmOffset += getObjCEncodingTypeSize(PType);
4118 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004119
4120 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004121}
4122
Bob Wilsondc8dab62011-11-30 01:57:58 +00004123/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4124/// method parameter or return type. If Extended, include class names and
4125/// block object types.
4126void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4127 QualType T, std::string& S,
4128 bool Extended) const {
4129 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4130 getObjCEncodingForTypeQualifier(QT, S);
4131 // Encode parameter type.
4132 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4133 true /*OutermostType*/,
4134 false /*EncodingProperty*/,
4135 false /*StructField*/,
4136 Extended /*EncodeBlockParameters*/,
4137 Extended /*EncodeClassNames*/);
4138}
4139
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004140/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004141/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004142bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004143 std::string& S,
4144 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004145 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004146 // Encode return type.
4147 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4148 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004149 // Compute size of all parameters.
4150 // Start with computing size of a pointer in number of bytes.
4151 // FIXME: There might(should) be a better way of doing this computation!
4152 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004153 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004154 // The first two arguments (self and _cmd) are pointers; account for
4155 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004156 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004157 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004158 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004159 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004160 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004161 if (sz.isZero())
4162 return true;
4163
Ken Dyck199c3d62010-01-11 17:06:35 +00004164 assert (sz.isPositive() &&
4165 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004166 ParmOffset += sz;
4167 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004168 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004169 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004170 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004171
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004172 // Argument types.
4173 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004174 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004175 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004176 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004177 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004178 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004179 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4180 // Use array's original type only if it has known number of
4181 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004182 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004183 PType = PVDecl->getType();
4184 } else if (PType->isFunctionType())
4185 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004186 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4187 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004188 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004189 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004190 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004191
4192 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004193}
4194
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004195/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004196/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004197/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4198/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004199/// Property attributes are stored as a comma-delimited C string. The simple
4200/// attributes readonly and bycopy are encoded as single characters. The
4201/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4202/// encoded as single characters, followed by an identifier. Property types
4203/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004204/// these attributes are defined by the following enumeration:
4205/// @code
4206/// enum PropertyAttributes {
4207/// kPropertyReadOnly = 'R', // property is read-only.
4208/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4209/// kPropertyByref = '&', // property is a reference to the value last assigned
4210/// kPropertyDynamic = 'D', // property is dynamic
4211/// kPropertyGetter = 'G', // followed by getter selector name
4212/// kPropertySetter = 'S', // followed by setter selector name
4213/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004214/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004215/// kPropertyWeak = 'W' // 'weak' property
4216/// kPropertyStrong = 'P' // property GC'able
4217/// kPropertyNonAtomic = 'N' // property non-atomic
4218/// };
4219/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004220void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004221 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004222 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004223 // Collect information from the property implementation decl(s).
4224 bool Dynamic = false;
4225 ObjCPropertyImplDecl *SynthesizePID = 0;
4226
4227 // FIXME: Duplicated code due to poor abstraction.
4228 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004229 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004230 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4231 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004232 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004233 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004234 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004235 if (PID->getPropertyDecl() == PD) {
4236 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4237 Dynamic = true;
4238 } else {
4239 SynthesizePID = PID;
4240 }
4241 }
4242 }
4243 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004244 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004245 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004246 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004247 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004248 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004249 if (PID->getPropertyDecl() == PD) {
4250 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4251 Dynamic = true;
4252 } else {
4253 SynthesizePID = PID;
4254 }
4255 }
Mike Stump1eb44332009-09-09 15:08:12 +00004256 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004257 }
4258 }
4259
4260 // FIXME: This is not very efficient.
4261 S = "T";
4262
4263 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004264 // GCC has some special rules regarding encoding of properties which
4265 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004266 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004267 true /* outermost type */,
4268 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004269
4270 if (PD->isReadOnly()) {
4271 S += ",R";
4272 } else {
4273 switch (PD->getSetterKind()) {
4274 case ObjCPropertyDecl::Assign: break;
4275 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004276 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004277 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004278 }
4279 }
4280
4281 // It really isn't clear at all what this means, since properties
4282 // are "dynamic by default".
4283 if (Dynamic)
4284 S += ",D";
4285
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004286 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4287 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004288
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004289 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4290 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004291 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004292 }
4293
4294 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4295 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004296 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004297 }
4298
4299 if (SynthesizePID) {
4300 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4301 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004302 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004303 }
4304
4305 // FIXME: OBJCGC: weak & strong
4306}
4307
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004308/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004309/// Another legacy compatibility encoding: 32-bit longs are encoded as
4310/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004311/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4312///
4313void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004314 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004315 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004316 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004317 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004318 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004319 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004320 PointeeTy = IntTy;
4321 }
4322 }
4323}
4324
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004325void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004326 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004327 // We follow the behavior of gcc, expanding structures which are
4328 // directly pointed to, and expanding embedded structures. Note that
4329 // these rules are sufficient to prevent recursive encoding of the
4330 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004331 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004332 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004333}
4334
David Chisnall64fd7e82010-06-04 01:10:52 +00004335static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4336 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004337 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnall64fd7e82010-06-04 01:10:52 +00004338 case BuiltinType::Void: return 'v';
4339 case BuiltinType::Bool: return 'B';
4340 case BuiltinType::Char_U:
4341 case BuiltinType::UChar: return 'C';
4342 case BuiltinType::UShort: return 'S';
4343 case BuiltinType::UInt: return 'I';
4344 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00004345 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004346 case BuiltinType::UInt128: return 'T';
4347 case BuiltinType::ULongLong: return 'Q';
4348 case BuiltinType::Char_S:
4349 case BuiltinType::SChar: return 'c';
4350 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004351 case BuiltinType::WChar_S:
4352 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004353 case BuiltinType::Int: return 'i';
4354 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00004355 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004356 case BuiltinType::LongLong: return 'q';
4357 case BuiltinType::Int128: return 't';
4358 case BuiltinType::Float: return 'f';
4359 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004360 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004361 }
4362}
4363
Douglas Gregor5471bc82011-09-08 17:18:35 +00004364static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4365 EnumDecl *Enum = ET->getDecl();
4366
4367 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4368 if (!Enum->isFixed())
4369 return 'i';
4370
4371 // The encoding of a fixed enum type matches its fixed underlying type.
4372 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4373}
4374
Jay Foad4ba2a172011-01-12 09:06:06 +00004375static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004376 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004377 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004378 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004379 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4380 // The GNU runtime requires more information; bitfields are encoded as b,
4381 // then the offset (in bits) of the first element, then the type of the
4382 // bitfield, then the size in bits. For example, in this structure:
4383 //
4384 // struct
4385 // {
4386 // int integer;
4387 // int flags:2;
4388 // };
4389 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4390 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4391 // information is not especially sensible, but we're stuck with it for
4392 // compatibility with GCC, although providing it breaks anything that
4393 // actually uses runtime introspection and wants to work on both runtimes...
David Blaikie4e4d0842012-03-11 07:00:24 +00004394 if (!Ctx->getLangOpts().NeXTRuntime) {
David Chisnall64fd7e82010-06-04 01:10:52 +00004395 const RecordDecl *RD = FD->getParent();
4396 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004397 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00004398 if (const EnumType *ET = T->getAs<EnumType>())
4399 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnallc7ff82c2010-12-26 20:12:30 +00004400 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004401 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004402 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004403 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004404}
4405
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004406// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004407void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4408 bool ExpandPointedToStructures,
4409 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004410 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004411 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004412 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004413 bool StructField,
4414 bool EncodeBlockParameters,
4415 bool EncodeClassNames) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004416 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004417 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004418 return EncodeBitField(this, S, T, FD);
4419 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004420 return;
4421 }
Mike Stump1eb44332009-09-09 15:08:12 +00004422
John McCall183700f2009-09-21 23:43:11 +00004423 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004424 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004425 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004426 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004427 return;
4428 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004429
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004430 // encoding for pointer or r3eference types.
4431 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004432 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004433 if (PT->isObjCSelType()) {
4434 S += ':';
4435 return;
4436 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004437 PointeeTy = PT->getPointeeType();
4438 }
4439 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4440 PointeeTy = RT->getPointeeType();
4441 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004442 bool isReadOnly = false;
4443 // For historical/compatibility reasons, the read-only qualifier of the
4444 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4445 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004446 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004447 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004448 if (OutermostType && T.isConstQualified()) {
4449 isReadOnly = true;
4450 S += 'r';
4451 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004452 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004453 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004454 while (P->getAs<PointerType>())
4455 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004456 if (P.isConstQualified()) {
4457 isReadOnly = true;
4458 S += 'r';
4459 }
4460 }
4461 if (isReadOnly) {
4462 // Another legacy compatibility encoding. Some ObjC qualifier and type
4463 // combinations need to be rearranged.
4464 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00004465 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00004466 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004467 }
Mike Stump1eb44332009-09-09 15:08:12 +00004468
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004469 if (PointeeTy->isCharType()) {
4470 // char pointer types should be encoded as '*' unless it is a
4471 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004472 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004473 S += '*';
4474 return;
4475 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004476 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004477 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4478 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4479 S += '#';
4480 return;
4481 }
4482 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4483 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4484 S += '@';
4485 return;
4486 }
4487 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004488 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004489 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004490 getLegacyIntegralTypeEncoding(PointeeTy);
4491
Mike Stump1eb44332009-09-09 15:08:12 +00004492 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004493 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004494 return;
4495 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004496
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004497 if (const ArrayType *AT =
4498 // Ignore type qualifiers etc.
4499 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004500 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004501 // Incomplete arrays are encoded as a pointer to the array element.
4502 S += '^';
4503
Mike Stump1eb44332009-09-09 15:08:12 +00004504 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004505 false, ExpandStructures, FD);
4506 } else {
4507 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004508
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004509 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4510 if (getTypeSize(CAT->getElementType()) == 0)
4511 S += '0';
4512 else
4513 S += llvm::utostr(CAT->getSize().getZExtValue());
4514 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00004515 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004516 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4517 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00004518 S += '0';
4519 }
Mike Stump1eb44332009-09-09 15:08:12 +00004520
4521 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004522 false, ExpandStructures, FD);
4523 S += ']';
4524 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004525 return;
4526 }
Mike Stump1eb44332009-09-09 15:08:12 +00004527
John McCall183700f2009-09-21 23:43:11 +00004528 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004529 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004530 return;
4531 }
Mike Stump1eb44332009-09-09 15:08:12 +00004532
Ted Kremenek6217b802009-07-29 21:53:49 +00004533 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004534 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004535 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004536 // Anonymous structures print as '?'
4537 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4538 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004539 if (ClassTemplateSpecializationDecl *Spec
4540 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4541 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4542 std::string TemplateArgsStr
4543 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004544 TemplateArgs.data(),
4545 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00004546 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004547
4548 S += TemplateArgsStr;
4549 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004550 } else {
4551 S += '?';
4552 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004553 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004554 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004555 if (!RDecl->isUnion()) {
4556 getObjCEncodingForStructureImpl(RDecl, S, FD);
4557 } else {
4558 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4559 FieldEnd = RDecl->field_end();
4560 Field != FieldEnd; ++Field) {
4561 if (FD) {
4562 S += '"';
4563 S += Field->getNameAsString();
4564 S += '"';
4565 }
Mike Stump1eb44332009-09-09 15:08:12 +00004566
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004567 // Special case bit-fields.
4568 if (Field->isBitField()) {
4569 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00004570 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004571 } else {
4572 QualType qt = Field->getType();
4573 getLegacyIntegralTypeEncoding(qt);
4574 getObjCEncodingForTypeImpl(qt, S, false, true,
4575 FD, /*OutermostType*/false,
4576 /*EncodingProperty*/false,
4577 /*StructField*/true);
4578 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004579 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004580 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004581 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004582 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004583 return;
4584 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004585
Douglas Gregor5471bc82011-09-08 17:18:35 +00004586 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004587 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004588 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004589 else
Douglas Gregor5471bc82011-09-08 17:18:35 +00004590 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004591 return;
4592 }
Mike Stump1eb44332009-09-09 15:08:12 +00004593
Bob Wilsondc8dab62011-11-30 01:57:58 +00004594 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004595 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00004596 if (EncodeBlockParameters) {
4597 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4598
4599 S += '<';
4600 // Block return type
4601 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4602 ExpandPointedToStructures, ExpandStructures,
4603 FD,
4604 false /* OutermostType */,
4605 EncodingProperty,
4606 false /* StructField */,
4607 EncodeBlockParameters,
4608 EncodeClassNames);
4609 // Block self
4610 S += "@?";
4611 // Block parameters
4612 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4613 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4614 E = FPT->arg_type_end(); I && (I != E); ++I) {
4615 getObjCEncodingForTypeImpl(*I, S,
4616 ExpandPointedToStructures,
4617 ExpandStructures,
4618 FD,
4619 false /* OutermostType */,
4620 EncodingProperty,
4621 false /* StructField */,
4622 EncodeBlockParameters,
4623 EncodeClassNames);
4624 }
4625 }
4626 S += '>';
4627 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004628 return;
4629 }
Mike Stump1eb44332009-09-09 15:08:12 +00004630
John McCallc12c5bb2010-05-15 11:32:37 +00004631 // Ignore protocol qualifiers when mangling at this level.
4632 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4633 T = OT->getBaseType();
4634
John McCall0953e762009-09-24 19:53:00 +00004635 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004636 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004637 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004638 S += '{';
4639 const IdentifierInfo *II = OI->getIdentifier();
4640 S += II->getName();
4641 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00004642 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004643 DeepCollectObjCIvars(OI, true, Ivars);
4644 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00004645 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004646 if (Field->isBitField())
4647 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004648 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004649 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004650 }
4651 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004652 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004653 }
Mike Stump1eb44332009-09-09 15:08:12 +00004654
John McCall183700f2009-09-21 23:43:11 +00004655 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004656 if (OPT->isObjCIdType()) {
4657 S += '@';
4658 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004659 }
Mike Stump1eb44332009-09-09 15:08:12 +00004660
Steve Naroff27d20a22009-10-28 22:03:49 +00004661 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4662 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4663 // Since this is a binary compatibility issue, need to consult with runtime
4664 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004665 S += '#';
4666 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004667 }
Mike Stump1eb44332009-09-09 15:08:12 +00004668
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004669 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004670 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004671 ExpandPointedToStructures,
4672 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00004673 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00004674 // Note that we do extended encoding of protocol qualifer list
4675 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004676 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004677 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4678 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004679 S += '<';
4680 S += (*I)->getNameAsString();
4681 S += '>';
4682 }
4683 S += '"';
4684 }
4685 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004686 }
Mike Stump1eb44332009-09-09 15:08:12 +00004687
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004688 QualType PointeeTy = OPT->getPointeeType();
4689 if (!EncodingProperty &&
4690 isa<TypedefType>(PointeeTy.getTypePtr())) {
4691 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004692 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004693 // {...};
4694 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004695 getObjCEncodingForTypeImpl(PointeeTy, S,
4696 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004697 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004698 return;
4699 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004700
4701 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00004702 if (OPT->getInterfaceDecl() &&
4703 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004704 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004705 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004706 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4707 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004708 S += '<';
4709 S += (*I)->getNameAsString();
4710 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004711 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004712 S += '"';
4713 }
4714 return;
4715 }
Mike Stump1eb44332009-09-09 15:08:12 +00004716
John McCall532ec7b2010-05-17 23:56:34 +00004717 // gcc just blithely ignores member pointers.
4718 // TODO: maybe there should be a mangling for these
4719 if (T->getAs<MemberPointerType>())
4720 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004721
4722 if (T->isVectorType()) {
4723 // This matches gcc's encoding, even though technically it is
4724 // insufficient.
4725 // FIXME. We should do a better job than gcc.
4726 return;
4727 }
4728
David Blaikieb219cfc2011-09-23 05:06:16 +00004729 llvm_unreachable("@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004730}
4731
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004732void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4733 std::string &S,
4734 const FieldDecl *FD,
4735 bool includeVBases) const {
4736 assert(RDecl && "Expected non-null RecordDecl");
4737 assert(!RDecl->isUnion() && "Should not be called for unions");
4738 if (!RDecl->getDefinition())
4739 return;
4740
4741 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4742 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4743 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4744
4745 if (CXXRec) {
4746 for (CXXRecordDecl::base_class_iterator
4747 BI = CXXRec->bases_begin(),
4748 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4749 if (!BI->isVirtual()) {
4750 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004751 if (base->isEmpty())
4752 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004753 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4754 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4755 std::make_pair(offs, base));
4756 }
4757 }
4758 }
4759
4760 unsigned i = 0;
4761 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4762 FieldEnd = RDecl->field_end();
4763 Field != FieldEnd; ++Field, ++i) {
4764 uint64_t offs = layout.getFieldOffset(i);
4765 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00004766 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004767 }
4768
4769 if (CXXRec && includeVBases) {
4770 for (CXXRecordDecl::base_class_iterator
4771 BI = CXXRec->vbases_begin(),
4772 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4773 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004774 if (base->isEmpty())
4775 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004776 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00004777 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4778 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4779 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004780 }
4781 }
4782
4783 CharUnits size;
4784 if (CXXRec) {
4785 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4786 } else {
4787 size = layout.getSize();
4788 }
4789
4790 uint64_t CurOffs = 0;
4791 std::multimap<uint64_t, NamedDecl *>::iterator
4792 CurLayObj = FieldOrBaseOffsets.begin();
4793
Douglas Gregor58db7a52012-04-27 22:30:01 +00004794 if (CXXRec && CXXRec->isDynamicClass() &&
4795 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004796 if (FD) {
4797 S += "\"_vptr$";
4798 std::string recname = CXXRec->getNameAsString();
4799 if (recname.empty()) recname = "?";
4800 S += recname;
4801 S += '"';
4802 }
4803 S += "^^?";
4804 CurOffs += getTypeSize(VoidPtrTy);
4805 }
4806
4807 if (!RDecl->hasFlexibleArrayMember()) {
4808 // Mark the end of the structure.
4809 uint64_t offs = toBits(size);
4810 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4811 std::make_pair(offs, (NamedDecl*)0));
4812 }
4813
4814 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4815 assert(CurOffs <= CurLayObj->first);
4816
4817 if (CurOffs < CurLayObj->first) {
4818 uint64_t padding = CurLayObj->first - CurOffs;
4819 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4820 // packing/alignment of members is different that normal, in which case
4821 // the encoding will be out-of-sync with the real layout.
4822 // If the runtime switches to just consider the size of types without
4823 // taking into account alignment, we could make padding explicit in the
4824 // encoding (e.g. using arrays of chars). The encoding strings would be
4825 // longer then though.
4826 CurOffs += padding;
4827 }
4828
4829 NamedDecl *dcl = CurLayObj->second;
4830 if (dcl == 0)
4831 break; // reached end of structure.
4832
4833 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4834 // We expand the bases without their virtual bases since those are going
4835 // in the initial structure. Note that this differs from gcc which
4836 // expands virtual bases each time one is encountered in the hierarchy,
4837 // making the encoding type bigger than it really is.
4838 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004839 assert(!base->isEmpty());
4840 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004841 } else {
4842 FieldDecl *field = cast<FieldDecl>(dcl);
4843 if (FD) {
4844 S += '"';
4845 S += field->getNameAsString();
4846 S += '"';
4847 }
4848
4849 if (field->isBitField()) {
4850 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004851 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004852 } else {
4853 QualType qt = field->getType();
4854 getLegacyIntegralTypeEncoding(qt);
4855 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4856 /*OutermostType*/false,
4857 /*EncodingProperty*/false,
4858 /*StructField*/true);
4859 CurOffs += getTypeSize(field->getType());
4860 }
4861 }
4862 }
4863}
4864
Mike Stump1eb44332009-09-09 15:08:12 +00004865void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004866 std::string& S) const {
4867 if (QT & Decl::OBJC_TQ_In)
4868 S += 'n';
4869 if (QT & Decl::OBJC_TQ_Inout)
4870 S += 'N';
4871 if (QT & Decl::OBJC_TQ_Out)
4872 S += 'o';
4873 if (QT & Decl::OBJC_TQ_Bycopy)
4874 S += 'O';
4875 if (QT & Decl::OBJC_TQ_Byref)
4876 S += 'R';
4877 if (QT & Decl::OBJC_TQ_Oneway)
4878 S += 'V';
4879}
4880
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004881void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004882 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004883
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004884 BuiltinVaListType = T;
4885}
4886
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00004887TypedefDecl *ASTContext::getObjCIdDecl() const {
4888 if (!ObjCIdDecl) {
4889 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4890 T = getObjCObjectPointerType(T);
4891 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4892 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4893 getTranslationUnitDecl(),
4894 SourceLocation(), SourceLocation(),
4895 &Idents.get("id"), IdInfo);
4896 }
4897
4898 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00004899}
4900
Douglas Gregor7a27ea52011-08-12 06:17:30 +00004901TypedefDecl *ASTContext::getObjCSelDecl() const {
4902 if (!ObjCSelDecl) {
4903 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4904 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4905 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4906 getTranslationUnitDecl(),
4907 SourceLocation(), SourceLocation(),
4908 &Idents.get("SEL"), SelInfo);
4909 }
4910 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004911}
4912
Douglas Gregor79d67262011-08-12 05:59:41 +00004913TypedefDecl *ASTContext::getObjCClassDecl() const {
4914 if (!ObjCClassDecl) {
4915 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4916 T = getObjCObjectPointerType(T);
4917 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4918 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4919 getTranslationUnitDecl(),
4920 SourceLocation(), SourceLocation(),
4921 &Idents.get("Class"), ClassInfo);
4922 }
4923
4924 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004925}
4926
Douglas Gregora6ea10e2012-01-17 18:09:05 +00004927ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
4928 if (!ObjCProtocolClassDecl) {
4929 ObjCProtocolClassDecl
4930 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
4931 SourceLocation(),
4932 &Idents.get("Protocol"),
4933 /*PrevDecl=*/0,
4934 SourceLocation(), true);
4935 }
4936
4937 return ObjCProtocolClassDecl;
4938}
4939
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004940void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004941 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004942 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004943
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004944 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004945}
4946
John McCall0bd6feb2009-12-02 08:04:21 +00004947/// \brief Retrieve the template name that corresponds to a non-empty
4948/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00004949TemplateName
4950ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4951 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00004952 unsigned size = End - Begin;
4953 assert(size > 1 && "set is not overloaded!");
4954
4955 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4956 size * sizeof(FunctionTemplateDecl*));
4957 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4958
4959 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004960 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004961 NamedDecl *D = *I;
4962 assert(isa<FunctionTemplateDecl>(D) ||
4963 (isa<UsingShadowDecl>(D) &&
4964 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4965 *Storage++ = D;
4966 }
4967
4968 return TemplateName(OT);
4969}
4970
Douglas Gregor7532dc62009-03-30 22:58:21 +00004971/// \brief Retrieve the template name that represents a qualified
4972/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00004973TemplateName
4974ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4975 bool TemplateKeyword,
4976 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00004977 assert(NNS && "Missing nested-name-specifier in qualified template name");
4978
Douglas Gregor789b1f62010-02-04 18:10:26 +00004979 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004980 llvm::FoldingSetNodeID ID;
4981 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4982
4983 void *InsertPos = 0;
4984 QualifiedTemplateName *QTN =
4985 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4986 if (!QTN) {
4987 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4988 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4989 }
4990
4991 return TemplateName(QTN);
4992}
4993
4994/// \brief Retrieve the template name that represents a dependent
4995/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00004996TemplateName
4997ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4998 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004999 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00005000 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00005001
5002 llvm::FoldingSetNodeID ID;
5003 DependentTemplateName::Profile(ID, NNS, Name);
5004
5005 void *InsertPos = 0;
5006 DependentTemplateName *QTN =
5007 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5008
5009 if (QTN)
5010 return TemplateName(QTN);
5011
5012 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5013 if (CanonNNS == NNS) {
5014 QTN = new (*this,4) DependentTemplateName(NNS, Name);
5015 } else {
5016 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5017 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005018 DependentTemplateName *CheckQTN =
5019 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5020 assert(!CheckQTN && "Dependent type name canonicalization broken");
5021 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00005022 }
5023
5024 DependentTemplateNames.InsertNode(QTN, InsertPos);
5025 return TemplateName(QTN);
5026}
5027
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005028/// \brief Retrieve the template name that represents a dependent
5029/// template name such as \c MetaFun::template operator+.
5030TemplateName
5031ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00005032 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005033 assert((!NNS || NNS->isDependent()) &&
5034 "Nested name specifier must be dependent");
5035
5036 llvm::FoldingSetNodeID ID;
5037 DependentTemplateName::Profile(ID, NNS, Operator);
5038
5039 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00005040 DependentTemplateName *QTN
5041 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005042
5043 if (QTN)
5044 return TemplateName(QTN);
5045
5046 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5047 if (CanonNNS == NNS) {
5048 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5049 } else {
5050 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5051 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005052
5053 DependentTemplateName *CheckQTN
5054 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5055 assert(!CheckQTN && "Dependent template name canonicalization broken");
5056 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005057 }
5058
5059 DependentTemplateNames.InsertNode(QTN, InsertPos);
5060 return TemplateName(QTN);
5061}
5062
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005063TemplateName
John McCall14606042011-06-30 08:33:18 +00005064ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5065 TemplateName replacement) const {
5066 llvm::FoldingSetNodeID ID;
5067 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5068
5069 void *insertPos = 0;
5070 SubstTemplateTemplateParmStorage *subst
5071 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5072
5073 if (!subst) {
5074 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5075 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5076 }
5077
5078 return TemplateName(subst);
5079}
5080
5081TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005082ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5083 const TemplateArgument &ArgPack) const {
5084 ASTContext &Self = const_cast<ASTContext &>(*this);
5085 llvm::FoldingSetNodeID ID;
5086 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5087
5088 void *InsertPos = 0;
5089 SubstTemplateTemplateParmPackStorage *Subst
5090 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5091
5092 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00005093 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005094 ArgPack.pack_size(),
5095 ArgPack.pack_begin());
5096 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5097 }
5098
5099 return TemplateName(Subst);
5100}
5101
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005102/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00005103/// TargetInfo, produce the corresponding type. The unsigned @p Type
5104/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00005105CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005106 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00005107 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005108 case TargetInfo::SignedShort: return ShortTy;
5109 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5110 case TargetInfo::SignedInt: return IntTy;
5111 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5112 case TargetInfo::SignedLong: return LongTy;
5113 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5114 case TargetInfo::SignedLongLong: return LongLongTy;
5115 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5116 }
5117
David Blaikieb219cfc2011-09-23 05:06:16 +00005118 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005119}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00005120
5121//===----------------------------------------------------------------------===//
5122// Type Predicates.
5123//===----------------------------------------------------------------------===//
5124
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005125/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5126/// garbage collection attribute.
5127///
John McCallae278a32011-01-12 00:34:59 +00005128Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00005129 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00005130 return Qualifiers::GCNone;
5131
David Blaikie4e4d0842012-03-11 07:00:24 +00005132 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00005133 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5134
5135 // Default behaviour under objective-C's gc is for ObjC pointers
5136 // (or pointers to them) be treated as though they were declared
5137 // as __strong.
5138 if (GCAttrs == Qualifiers::GCNone) {
5139 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5140 return Qualifiers::Strong;
5141 else if (Ty->isPointerType())
5142 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5143 } else {
5144 // It's not valid to set GC attributes on anything that isn't a
5145 // pointer.
5146#ifndef NDEBUG
5147 QualType CT = Ty->getCanonicalTypeInternal();
5148 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5149 CT = AT->getElementType();
5150 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5151#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005152 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00005153 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005154}
5155
Chris Lattner6ac46a42008-04-07 06:51:04 +00005156//===----------------------------------------------------------------------===//
5157// Type Compatibility Testing
5158//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00005159
Mike Stump1eb44332009-09-09 15:08:12 +00005160/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005161/// compatible.
5162static bool areCompatVectorTypes(const VectorType *LHS,
5163 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00005164 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00005165 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00005166 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00005167}
5168
Douglas Gregor255210e2010-08-06 10:14:59 +00005169bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5170 QualType SecondVec) {
5171 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5172 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5173
5174 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5175 return true;
5176
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005177 // Treat Neon vector types and most AltiVec vector types as if they are the
5178 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00005179 const VectorType *First = FirstVec->getAs<VectorType>();
5180 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005181 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00005182 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005183 First->getVectorKind() != VectorType::AltiVecPixel &&
5184 First->getVectorKind() != VectorType::AltiVecBool &&
5185 Second->getVectorKind() != VectorType::AltiVecPixel &&
5186 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00005187 return true;
5188
5189 return false;
5190}
5191
Steve Naroff4084c302009-07-23 01:01:38 +00005192//===----------------------------------------------------------------------===//
5193// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5194//===----------------------------------------------------------------------===//
5195
5196/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5197/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00005198bool
5199ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5200 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005201 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00005202 return true;
5203 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5204 E = rProto->protocol_end(); PI != E; ++PI)
5205 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5206 return true;
5207 return false;
5208}
5209
Steve Naroff4084c302009-07-23 01:01:38 +00005210/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5211/// return true if lhs's protocols conform to rhs's protocol; false
5212/// otherwise.
5213bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5214 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5215 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5216 return false;
5217}
5218
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005219/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5220/// Class<p1, ...>.
5221bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5222 QualType rhs) {
5223 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5224 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5225 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5226
5227 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5228 E = lhsQID->qual_end(); I != E; ++I) {
5229 bool match = false;
5230 ObjCProtocolDecl *lhsProto = *I;
5231 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5232 E = rhsOPT->qual_end(); J != E; ++J) {
5233 ObjCProtocolDecl *rhsProto = *J;
5234 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5235 match = true;
5236 break;
5237 }
5238 }
5239 if (!match)
5240 return false;
5241 }
5242 return true;
5243}
5244
Steve Naroff4084c302009-07-23 01:01:38 +00005245/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5246/// ObjCQualifiedIDType.
5247bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5248 bool compare) {
5249 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00005250 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005251 lhs->isObjCIdType() || lhs->isObjCClassType())
5252 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005253 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005254 rhs->isObjCIdType() || rhs->isObjCClassType())
5255 return true;
5256
5257 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00005258 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005259
Steve Naroff4084c302009-07-23 01:01:38 +00005260 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005261
Steve Naroff4084c302009-07-23 01:01:38 +00005262 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005263 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00005264 // make sure we check the class hierarchy.
5265 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5266 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5267 E = lhsQID->qual_end(); I != E; ++I) {
5268 // when comparing an id<P> on lhs with a static type on rhs,
5269 // see if static class implements all of id's protocols, directly or
5270 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005271 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00005272 return false;
5273 }
5274 }
5275 // If there are no qualifiers and no interface, we have an 'id'.
5276 return true;
5277 }
Mike Stump1eb44332009-09-09 15:08:12 +00005278 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005279 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5280 E = lhsQID->qual_end(); I != E; ++I) {
5281 ObjCProtocolDecl *lhsProto = *I;
5282 bool match = false;
5283
5284 // when comparing an id<P> on lhs with a static type on rhs,
5285 // see if static class implements all of id's protocols, directly or
5286 // through its super class and categories.
5287 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5288 E = rhsOPT->qual_end(); J != E; ++J) {
5289 ObjCProtocolDecl *rhsProto = *J;
5290 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5291 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5292 match = true;
5293 break;
5294 }
5295 }
Mike Stump1eb44332009-09-09 15:08:12 +00005296 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00005297 // make sure we check the class hierarchy.
5298 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5299 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5300 E = lhsQID->qual_end(); I != E; ++I) {
5301 // when comparing an id<P> on lhs with a static type on rhs,
5302 // see if static class implements all of id's protocols, directly or
5303 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005304 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00005305 match = true;
5306 break;
5307 }
5308 }
5309 }
5310 if (!match)
5311 return false;
5312 }
Mike Stump1eb44332009-09-09 15:08:12 +00005313
Steve Naroff4084c302009-07-23 01:01:38 +00005314 return true;
5315 }
Mike Stump1eb44332009-09-09 15:08:12 +00005316
Steve Naroff4084c302009-07-23 01:01:38 +00005317 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5318 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5319
Mike Stump1eb44332009-09-09 15:08:12 +00005320 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00005321 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005322 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005323 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5324 E = lhsOPT->qual_end(); I != E; ++I) {
5325 ObjCProtocolDecl *lhsProto = *I;
5326 bool match = false;
5327
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005328 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00005329 // see if static class implements all of id's protocols, directly or
5330 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005331 // First, lhs protocols in the qualifier list must be found, direct
5332 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00005333 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5334 E = rhsQID->qual_end(); J != E; ++J) {
5335 ObjCProtocolDecl *rhsProto = *J;
5336 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5337 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5338 match = true;
5339 break;
5340 }
5341 }
5342 if (!match)
5343 return false;
5344 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005345
5346 // Static class's protocols, or its super class or category protocols
5347 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5348 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5349 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5350 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5351 // This is rather dubious but matches gcc's behavior. If lhs has
5352 // no type qualifier and its class has no static protocol(s)
5353 // assume that it is mismatch.
5354 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5355 return false;
5356 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5357 LHSInheritedProtocols.begin(),
5358 E = LHSInheritedProtocols.end(); I != E; ++I) {
5359 bool match = false;
5360 ObjCProtocolDecl *lhsProto = (*I);
5361 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5362 E = rhsQID->qual_end(); J != E; ++J) {
5363 ObjCProtocolDecl *rhsProto = *J;
5364 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5365 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5366 match = true;
5367 break;
5368 }
5369 }
5370 if (!match)
5371 return false;
5372 }
5373 }
Steve Naroff4084c302009-07-23 01:01:38 +00005374 return true;
5375 }
5376 return false;
5377}
5378
Eli Friedman3d815e72008-08-22 00:56:42 +00005379/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005380/// compatible for assignment from RHS to LHS. This handles validation of any
5381/// protocol qualifiers on the LHS or RHS.
5382///
Steve Naroff14108da2009-07-10 23:34:53 +00005383bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5384 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00005385 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5386 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5387
Steve Naroffde2e22d2009-07-15 18:40:39 +00005388 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00005389 if (LHS->isObjCUnqualifiedIdOrClass() ||
5390 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00005391 return true;
5392
John McCallc12c5bb2010-05-15 11:32:37 +00005393 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00005394 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5395 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00005396 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005397
5398 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5399 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5400 QualType(RHSOPT,0));
5401
John McCallc12c5bb2010-05-15 11:32:37 +00005402 // If we have 2 user-defined types, fall into that path.
5403 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00005404 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00005405
Steve Naroff4084c302009-07-23 01:01:38 +00005406 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005407}
5408
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005409/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00005410/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005411/// arguments in block literals. When passed as arguments, passing 'A*' where
5412/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5413/// not OK. For the return type, the opposite is not OK.
5414bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5415 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005416 const ObjCObjectPointerType *RHSOPT,
5417 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005418 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005419 return true;
5420
5421 if (LHSOPT->isObjCBuiltinType()) {
5422 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5423 }
5424
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005425 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005426 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5427 QualType(RHSOPT,0),
5428 false);
5429
5430 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5431 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5432 if (LHS && RHS) { // We have 2 user-defined types.
5433 if (LHS != RHS) {
5434 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005435 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005436 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005437 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005438 }
5439 else
5440 return true;
5441 }
5442 return false;
5443}
5444
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005445/// getIntersectionOfProtocols - This routine finds the intersection of set
5446/// of protocols inherited from two distinct objective-c pointer objects.
5447/// It is used to build composite qualifier list of the composite type of
5448/// the conditional expression involving two objective-c pointer objects.
5449static
5450void getIntersectionOfProtocols(ASTContext &Context,
5451 const ObjCObjectPointerType *LHSOPT,
5452 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005453 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005454
John McCallc12c5bb2010-05-15 11:32:37 +00005455 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5456 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5457 assert(LHS->getInterface() && "LHS must have an interface base");
5458 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005459
5460 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5461 unsigned LHSNumProtocols = LHS->getNumProtocols();
5462 if (LHSNumProtocols > 0)
5463 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5464 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005465 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005466 Context.CollectInheritedProtocols(LHS->getInterface(),
5467 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005468 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5469 LHSInheritedProtocols.end());
5470 }
5471
5472 unsigned RHSNumProtocols = RHS->getNumProtocols();
5473 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00005474 ObjCProtocolDecl **RHSProtocols =
5475 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005476 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5477 if (InheritedProtocolSet.count(RHSProtocols[i]))
5478 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00005479 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005480 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005481 Context.CollectInheritedProtocols(RHS->getInterface(),
5482 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005483 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5484 RHSInheritedProtocols.begin(),
5485 E = RHSInheritedProtocols.end(); I != E; ++I)
5486 if (InheritedProtocolSet.count((*I)))
5487 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005488 }
5489}
5490
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005491/// areCommonBaseCompatible - Returns common base class of the two classes if
5492/// one found. Note that this is O'2 algorithm. But it will be called as the
5493/// last type comparison in a ?-exp of ObjC pointer types before a
5494/// warning is issued. So, its invokation is extremely rare.
5495QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00005496 const ObjCObjectPointerType *Lptr,
5497 const ObjCObjectPointerType *Rptr) {
5498 const ObjCObjectType *LHS = Lptr->getObjectType();
5499 const ObjCObjectType *RHS = Rptr->getObjectType();
5500 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5501 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00005502 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005503 return QualType();
5504
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005505 do {
John McCallc12c5bb2010-05-15 11:32:37 +00005506 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005507 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005508 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005509 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5510
5511 QualType Result = QualType(LHS, 0);
5512 if (!Protocols.empty())
5513 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5514 Result = getObjCObjectPointerType(Result);
5515 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005516 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005517 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005518
5519 return QualType();
5520}
5521
John McCallc12c5bb2010-05-15 11:32:37 +00005522bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5523 const ObjCObjectType *RHS) {
5524 assert(LHS->getInterface() && "LHS is not an interface type");
5525 assert(RHS->getInterface() && "RHS is not an interface type");
5526
Chris Lattner6ac46a42008-04-07 06:51:04 +00005527 // Verify that the base decls are compatible: the RHS must be a subclass of
5528 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00005529 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00005530 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005531
Chris Lattner6ac46a42008-04-07 06:51:04 +00005532 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5533 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00005534 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00005535 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005536
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005537 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5538 // more detailed analysis is required.
5539 if (RHS->getNumProtocols() == 0) {
5540 // OK, if LHS is a superclass of RHS *and*
5541 // this superclass is assignment compatible with LHS.
5542 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005543 bool IsSuperClass =
5544 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5545 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005546 // OK if conversion of LHS to SuperClass results in narrowing of types
5547 // ; i.e., SuperClass may implement at least one of the protocols
5548 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5549 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5550 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005551 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005552 // If super class has no protocols, it is not a match.
5553 if (SuperClassInheritedProtocols.empty())
5554 return false;
5555
5556 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5557 LHSPE = LHS->qual_end();
5558 LHSPI != LHSPE; LHSPI++) {
5559 bool SuperImplementsProtocol = false;
5560 ObjCProtocolDecl *LHSProto = (*LHSPI);
5561
5562 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5563 SuperClassInheritedProtocols.begin(),
5564 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5565 ObjCProtocolDecl *SuperClassProto = (*I);
5566 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5567 SuperImplementsProtocol = true;
5568 break;
5569 }
5570 }
5571 if (!SuperImplementsProtocol)
5572 return false;
5573 }
5574 return true;
5575 }
5576 return false;
5577 }
Mike Stump1eb44332009-09-09 15:08:12 +00005578
John McCallc12c5bb2010-05-15 11:32:37 +00005579 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5580 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005581 LHSPI != LHSPE; LHSPI++) {
5582 bool RHSImplementsProtocol = false;
5583
5584 // If the RHS doesn't implement the protocol on the left, the types
5585 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00005586 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5587 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00005588 RHSPI != RHSPE; RHSPI++) {
5589 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005590 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00005591 break;
5592 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005593 }
5594 // FIXME: For better diagnostics, consider passing back the protocol name.
5595 if (!RHSImplementsProtocol)
5596 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005597 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005598 // The RHS implements all protocols listed on the LHS.
5599 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005600}
5601
Steve Naroff389bf462009-02-12 17:52:19 +00005602bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5603 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00005604 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5605 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005606
Steve Naroff14108da2009-07-10 23:34:53 +00005607 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00005608 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005609
5610 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5611 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00005612}
5613
Douglas Gregor569c3162010-08-07 11:51:51 +00005614bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5615 return canAssignObjCInterfaces(
5616 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5617 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5618}
5619
Mike Stump1eb44332009-09-09 15:08:12 +00005620/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00005621/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00005622/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00005623/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00005624bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5625 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005626 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005627 return hasSameType(LHS, RHS);
5628
Douglas Gregor447234d2010-07-29 15:18:02 +00005629 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00005630}
5631
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005632bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00005633 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005634}
5635
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005636bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5637 return !mergeTypes(LHS, RHS, true).isNull();
5638}
5639
Peter Collingbourne48466752010-10-24 18:30:18 +00005640/// mergeTransparentUnionType - if T is a transparent union type and a member
5641/// of T is compatible with SubType, return the merged type, else return
5642/// QualType()
5643QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5644 bool OfBlockPointer,
5645 bool Unqualified) {
5646 if (const RecordType *UT = T->getAsUnionType()) {
5647 RecordDecl *UD = UT->getDecl();
5648 if (UD->hasAttr<TransparentUnionAttr>()) {
5649 for (RecordDecl::field_iterator it = UD->field_begin(),
5650 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00005651 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005652 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5653 if (!MT.isNull())
5654 return MT;
5655 }
5656 }
5657 }
5658
5659 return QualType();
5660}
5661
5662/// mergeFunctionArgumentTypes - merge two types which appear as function
5663/// argument types
5664QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5665 bool OfBlockPointer,
5666 bool Unqualified) {
5667 // GNU extension: two types are compatible if they appear as a function
5668 // argument, one of the types is a transparent union type and the other
5669 // type is compatible with a union member
5670 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5671 Unqualified);
5672 if (!lmerge.isNull())
5673 return lmerge;
5674
5675 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5676 Unqualified);
5677 if (!rmerge.isNull())
5678 return rmerge;
5679
5680 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5681}
5682
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005683QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00005684 bool OfBlockPointer,
5685 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00005686 const FunctionType *lbase = lhs->getAs<FunctionType>();
5687 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00005688 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5689 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00005690 bool allLTypes = true;
5691 bool allRTypes = true;
5692
5693 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005694 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005695 if (OfBlockPointer) {
5696 QualType RHS = rbase->getResultType();
5697 QualType LHS = lbase->getResultType();
5698 bool UnqualifiedResult = Unqualified;
5699 if (!UnqualifiedResult)
5700 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005701 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005702 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005703 else
John McCall8cc246c2010-12-15 01:06:38 +00005704 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5705 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005706 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005707
5708 if (Unqualified)
5709 retType = retType.getUnqualifiedType();
5710
5711 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5712 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5713 if (Unqualified) {
5714 LRetType = LRetType.getUnqualifiedType();
5715 RRetType = RRetType.getUnqualifiedType();
5716 }
5717
5718 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005719 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00005720 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005721 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005722
Daniel Dunbar6a15c852010-04-28 16:20:58 +00005723 // FIXME: double check this
5724 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5725 // rbase->getRegParmAttr() != 0 &&
5726 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00005727 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5728 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00005729
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005730 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00005731 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005732 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005733
John McCall8cc246c2010-12-15 01:06:38 +00005734 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00005735 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5736 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00005737 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5738 return QualType();
5739
John McCallf85e1932011-06-15 23:02:42 +00005740 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5741 return QualType();
5742
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005743 // functypes which return are preferred over those that do not.
5744 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5745 allLTypes = false;
5746 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5747 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005748 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5749 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00005750
John McCallf85e1932011-06-15 23:02:42 +00005751 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00005752
Eli Friedman3d815e72008-08-22 00:56:42 +00005753 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00005754 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5755 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005756 unsigned lproto_nargs = lproto->getNumArgs();
5757 unsigned rproto_nargs = rproto->getNumArgs();
5758
5759 // Compatible functions must have the same number of arguments
5760 if (lproto_nargs != rproto_nargs)
5761 return QualType();
5762
5763 // Variadic and non-variadic functions aren't compatible
5764 if (lproto->isVariadic() != rproto->isVariadic())
5765 return QualType();
5766
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00005767 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5768 return QualType();
5769
Fariborz Jahanian78213e42011-09-28 21:52:05 +00005770 if (LangOpts.ObjCAutoRefCount &&
5771 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5772 return QualType();
5773
Eli Friedman3d815e72008-08-22 00:56:42 +00005774 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00005775 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00005776 for (unsigned i = 0; i < lproto_nargs; i++) {
5777 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5778 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005779 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5780 OfBlockPointer,
5781 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005782 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005783
5784 if (Unqualified)
5785 argtype = argtype.getUnqualifiedType();
5786
Eli Friedman3d815e72008-08-22 00:56:42 +00005787 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00005788 if (Unqualified) {
5789 largtype = largtype.getUnqualifiedType();
5790 rargtype = rargtype.getUnqualifiedType();
5791 }
5792
Chris Lattner61710852008-10-05 17:34:18 +00005793 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5794 allLTypes = false;
5795 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5796 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00005797 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00005798
Eli Friedman3d815e72008-08-22 00:56:42 +00005799 if (allLTypes) return lhs;
5800 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005801
5802 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5803 EPI.ExtInfo = einfo;
5804 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005805 }
5806
5807 if (lproto) allRTypes = false;
5808 if (rproto) allLTypes = false;
5809
Douglas Gregor72564e72009-02-26 23:50:07 +00005810 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00005811 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00005812 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005813 if (proto->isVariadic()) return QualType();
5814 // Check that the types are compatible with the types that
5815 // would result from default argument promotions (C99 6.7.5.3p15).
5816 // The only types actually affected are promotable integer
5817 // types and floats, which would be passed as a different
5818 // type depending on whether the prototype is visible.
5819 unsigned proto_nargs = proto->getNumArgs();
5820 for (unsigned i = 0; i < proto_nargs; ++i) {
5821 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00005822
5823 // Look at the promotion type of enum types, since that is the type used
5824 // to pass enum values.
5825 if (const EnumType *Enum = argTy->getAs<EnumType>())
5826 argTy = Enum->getDecl()->getPromotionType();
5827
Eli Friedman3d815e72008-08-22 00:56:42 +00005828 if (argTy->isPromotableIntegerType() ||
5829 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5830 return QualType();
5831 }
5832
5833 if (allLTypes) return lhs;
5834 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005835
5836 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5837 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00005838 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005839 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005840 }
5841
5842 if (allLTypes) return lhs;
5843 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00005844 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00005845}
5846
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005847QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00005848 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005849 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00005850 // C++ [expr]: If an expression initially has the type "reference to T", the
5851 // type is adjusted to "T" prior to any further analysis, the expression
5852 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005853 // expression is an lvalue unless the reference is an rvalue reference and
5854 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005855 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5856 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00005857
5858 if (Unqualified) {
5859 LHS = LHS.getUnqualifiedType();
5860 RHS = RHS.getUnqualifiedType();
5861 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005862
Eli Friedman3d815e72008-08-22 00:56:42 +00005863 QualType LHSCan = getCanonicalType(LHS),
5864 RHSCan = getCanonicalType(RHS);
5865
5866 // If two types are identical, they are compatible.
5867 if (LHSCan == RHSCan)
5868 return LHS;
5869
John McCall0953e762009-09-24 19:53:00 +00005870 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005871 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5872 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00005873 if (LQuals != RQuals) {
5874 // If any of these qualifiers are different, we have a type
5875 // mismatch.
5876 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00005877 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5878 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00005879 return QualType();
5880
5881 // Exactly one GC qualifier difference is allowed: __strong is
5882 // okay if the other type has no GC qualifier but is an Objective
5883 // C object pointer (i.e. implicitly strong by default). We fix
5884 // this by pretending that the unqualified type was actually
5885 // qualified __strong.
5886 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5887 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5888 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5889
5890 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5891 return QualType();
5892
5893 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5894 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5895 }
5896 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5897 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5898 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005899 return QualType();
John McCall0953e762009-09-24 19:53:00 +00005900 }
5901
5902 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00005903
Eli Friedman852d63b2009-06-01 01:22:52 +00005904 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5905 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00005906
Chris Lattner1adb8832008-01-14 05:45:46 +00005907 // We want to consider the two function types to be the same for these
5908 // comparisons, just force one to the other.
5909 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5910 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00005911
5912 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00005913 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5914 LHSClass = Type::ConstantArray;
5915 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5916 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00005917
John McCallc12c5bb2010-05-15 11:32:37 +00005918 // ObjCInterfaces are just specialized ObjCObjects.
5919 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5920 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5921
Nate Begeman213541a2008-04-18 23:10:10 +00005922 // Canonicalize ExtVector -> Vector.
5923 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5924 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00005925
Chris Lattnera36a61f2008-04-07 05:43:21 +00005926 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005927 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00005928 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00005929 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00005930 // Compatibility is based on the underlying type, not the promotion
5931 // type.
John McCall183700f2009-09-21 23:43:11 +00005932 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00005933 QualType TINT = ETy->getDecl()->getIntegerType();
5934 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005935 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005936 }
John McCall183700f2009-09-21 23:43:11 +00005937 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00005938 QualType TINT = ETy->getDecl()->getIntegerType();
5939 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005940 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005941 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00005942 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00005943 if (OfBlockPointer && !BlockReturnType) {
5944 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
5945 return LHS;
5946 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
5947 return RHS;
5948 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00005949
Eli Friedman3d815e72008-08-22 00:56:42 +00005950 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005951 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005952
Steve Naroff4a746782008-01-09 22:43:08 +00005953 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005954 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00005955#define TYPE(Class, Base)
5956#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00005957#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00005958#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5959#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5960#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00005961 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00005962
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005963 case Type::LValueReference:
5964 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00005965 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00005966 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00005967
John McCallc12c5bb2010-05-15 11:32:37 +00005968 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00005969 case Type::IncompleteArray:
5970 case Type::VariableArray:
5971 case Type::FunctionProto:
5972 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00005973 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00005974
Chris Lattner1adb8832008-01-14 05:45:46 +00005975 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00005976 {
5977 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005978 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5979 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005980 if (Unqualified) {
5981 LHSPointee = LHSPointee.getUnqualifiedType();
5982 RHSPointee = RHSPointee.getUnqualifiedType();
5983 }
5984 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5985 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005986 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00005987 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005988 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00005989 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005990 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005991 return getPointerType(ResultType);
5992 }
Steve Naroffc0febd52008-12-10 17:49:55 +00005993 case Type::BlockPointer:
5994 {
5995 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005996 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5997 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005998 if (Unqualified) {
5999 LHSPointee = LHSPointee.getUnqualifiedType();
6000 RHSPointee = RHSPointee.getUnqualifiedType();
6001 }
6002 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6003 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00006004 if (ResultType.isNull()) return QualType();
6005 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6006 return LHS;
6007 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6008 return RHS;
6009 return getBlockPointerType(ResultType);
6010 }
Eli Friedmanb001de72011-10-06 23:00:33 +00006011 case Type::Atomic:
6012 {
6013 // Merge two pointer types, while trying to preserve typedef info
6014 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6015 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6016 if (Unqualified) {
6017 LHSValue = LHSValue.getUnqualifiedType();
6018 RHSValue = RHSValue.getUnqualifiedType();
6019 }
6020 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6021 Unqualified);
6022 if (ResultType.isNull()) return QualType();
6023 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6024 return LHS;
6025 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6026 return RHS;
6027 return getAtomicType(ResultType);
6028 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006029 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00006030 {
6031 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6032 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6033 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6034 return QualType();
6035
6036 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6037 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006038 if (Unqualified) {
6039 LHSElem = LHSElem.getUnqualifiedType();
6040 RHSElem = RHSElem.getUnqualifiedType();
6041 }
6042
6043 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006044 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00006045 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6046 return LHS;
6047 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6048 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00006049 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6050 ArrayType::ArraySizeModifier(), 0);
6051 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6052 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006053 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6054 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00006055 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6056 return LHS;
6057 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6058 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006059 if (LVAT) {
6060 // FIXME: This isn't correct! But tricky to implement because
6061 // the array's size has to be the size of LHS, but the type
6062 // has to be different.
6063 return LHS;
6064 }
6065 if (RVAT) {
6066 // FIXME: This isn't correct! But tricky to implement because
6067 // the array's size has to be the size of RHS, but the type
6068 // has to be different.
6069 return RHS;
6070 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00006071 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6072 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00006073 return getIncompleteArrayType(ResultType,
6074 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006075 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006076 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00006077 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00006078 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00006079 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00006080 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00006081 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006082 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00006083 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00006084 case Type::Complex:
6085 // Distinct complex types are incompatible.
6086 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006087 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006088 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00006089 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6090 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006091 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00006092 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00006093 case Type::ObjCObject: {
6094 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006095 // FIXME: This should be type compatibility, e.g. whether
6096 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00006097 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6098 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6099 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00006100 return LHS;
6101
Eli Friedman3d815e72008-08-22 00:56:42 +00006102 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00006103 }
Steve Naroff14108da2009-07-10 23:34:53 +00006104 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006105 if (OfBlockPointer) {
6106 if (canAssignObjCInterfacesInBlockPointer(
6107 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006108 RHS->getAs<ObjCObjectPointerType>(),
6109 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00006110 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006111 return QualType();
6112 }
John McCall183700f2009-09-21 23:43:11 +00006113 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6114 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00006115 return LHS;
6116
Steve Naroffbc76dd02008-12-10 22:14:21 +00006117 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00006118 }
Steve Naroffec0550f2007-10-15 20:41:53 +00006119 }
Douglas Gregor72564e72009-02-26 23:50:07 +00006120
David Blaikie7530c032012-01-17 06:56:22 +00006121 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00006122}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00006123
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006124bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6125 const FunctionProtoType *FromFunctionType,
6126 const FunctionProtoType *ToFunctionType) {
6127 if (FromFunctionType->hasAnyConsumedArgs() !=
6128 ToFunctionType->hasAnyConsumedArgs())
6129 return false;
6130 FunctionProtoType::ExtProtoInfo FromEPI =
6131 FromFunctionType->getExtProtoInfo();
6132 FunctionProtoType::ExtProtoInfo ToEPI =
6133 ToFunctionType->getExtProtoInfo();
6134 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6135 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6136 ArgIdx != NumArgs; ++ArgIdx) {
6137 if (FromEPI.ConsumedArguments[ArgIdx] !=
6138 ToEPI.ConsumedArguments[ArgIdx])
6139 return false;
6140 }
6141 return true;
6142}
6143
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006144/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6145/// 'RHS' attributes and returns the merged version; including for function
6146/// return types.
6147QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6148 QualType LHSCan = getCanonicalType(LHS),
6149 RHSCan = getCanonicalType(RHS);
6150 // If two types are identical, they are compatible.
6151 if (LHSCan == RHSCan)
6152 return LHS;
6153 if (RHSCan->isFunctionType()) {
6154 if (!LHSCan->isFunctionType())
6155 return QualType();
6156 QualType OldReturnType =
6157 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6158 QualType NewReturnType =
6159 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6160 QualType ResReturnType =
6161 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6162 if (ResReturnType.isNull())
6163 return QualType();
6164 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6165 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6166 // In either case, use OldReturnType to build the new function type.
6167 const FunctionType *F = LHS->getAs<FunctionType>();
6168 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00006169 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6170 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006171 QualType ResultType
6172 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006173 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006174 return ResultType;
6175 }
6176 }
6177 return QualType();
6178 }
6179
6180 // If the qualifiers are different, the types can still be merged.
6181 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6182 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6183 if (LQuals != RQuals) {
6184 // If any of these qualifiers are different, we have a type mismatch.
6185 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6186 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6187 return QualType();
6188
6189 // Exactly one GC qualifier difference is allowed: __strong is
6190 // okay if the other type has no GC qualifier but is an Objective
6191 // C object pointer (i.e. implicitly strong by default). We fix
6192 // this by pretending that the unqualified type was actually
6193 // qualified __strong.
6194 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6195 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6196 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6197
6198 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6199 return QualType();
6200
6201 if (GC_L == Qualifiers::Strong)
6202 return LHS;
6203 if (GC_R == Qualifiers::Strong)
6204 return RHS;
6205 return QualType();
6206 }
6207
6208 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6209 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6210 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6211 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6212 if (ResQT == LHSBaseQT)
6213 return LHS;
6214 if (ResQT == RHSBaseQT)
6215 return RHS;
6216 }
6217 return QualType();
6218}
6219
Chris Lattner5426bf62008-04-07 07:01:58 +00006220//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00006221// Integer Predicates
6222//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00006223
Jay Foad4ba2a172011-01-12 09:06:06 +00006224unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00006225 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00006226 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006227 if (T->isBooleanType())
6228 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00006229 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00006230 return (unsigned)getTypeSize(T);
6231}
6232
6233QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00006234 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00006235
6236 // Turn <4 x signed int> -> <4 x unsigned int>
6237 if (const VectorType *VTy = T->getAs<VectorType>())
6238 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00006239 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00006240
6241 // For enums, we return the unsigned version of the base type.
6242 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00006243 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00006244
6245 const BuiltinType *BTy = T->getAs<BuiltinType>();
6246 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006247 switch (BTy->getKind()) {
6248 case BuiltinType::Char_S:
6249 case BuiltinType::SChar:
6250 return UnsignedCharTy;
6251 case BuiltinType::Short:
6252 return UnsignedShortTy;
6253 case BuiltinType::Int:
6254 return UnsignedIntTy;
6255 case BuiltinType::Long:
6256 return UnsignedLongTy;
6257 case BuiltinType::LongLong:
6258 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00006259 case BuiltinType::Int128:
6260 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00006261 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00006262 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006263 }
6264}
6265
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00006266ASTMutationListener::~ASTMutationListener() { }
6267
Chris Lattner86df27b2009-06-14 00:45:47 +00006268
6269//===----------------------------------------------------------------------===//
6270// Builtin Type Computation
6271//===----------------------------------------------------------------------===//
6272
6273/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00006274/// pointer over the consumed characters. This returns the resultant type. If
6275/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6276/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6277/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00006278///
6279/// RequiresICE is filled in on return to indicate whether the value is required
6280/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00006281static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00006282 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00006283 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00006284 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00006285 // Modifiers.
6286 int HowLong = 0;
6287 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00006288 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006289
Chris Lattner33daae62010-10-01 22:42:38 +00006290 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00006291 bool Done = false;
6292 while (!Done) {
6293 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00006294 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006295 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00006296 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006297 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006298 case 'S':
6299 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6300 assert(!Signed && "Can't use 'S' modifier multiple times!");
6301 Signed = true;
6302 break;
6303 case 'U':
6304 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6305 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6306 Unsigned = true;
6307 break;
6308 case 'L':
6309 assert(HowLong <= 2 && "Can't have LLLL modifier");
6310 ++HowLong;
6311 break;
6312 }
6313 }
6314
6315 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00006316
Chris Lattner86df27b2009-06-14 00:45:47 +00006317 // Read the base type.
6318 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00006319 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00006320 case 'v':
6321 assert(HowLong == 0 && !Signed && !Unsigned &&
6322 "Bad modifiers used with 'v'!");
6323 Type = Context.VoidTy;
6324 break;
6325 case 'f':
6326 assert(HowLong == 0 && !Signed && !Unsigned &&
6327 "Bad modifiers used with 'f'!");
6328 Type = Context.FloatTy;
6329 break;
6330 case 'd':
6331 assert(HowLong < 2 && !Signed && !Unsigned &&
6332 "Bad modifiers used with 'd'!");
6333 if (HowLong)
6334 Type = Context.LongDoubleTy;
6335 else
6336 Type = Context.DoubleTy;
6337 break;
6338 case 's':
6339 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6340 if (Unsigned)
6341 Type = Context.UnsignedShortTy;
6342 else
6343 Type = Context.ShortTy;
6344 break;
6345 case 'i':
6346 if (HowLong == 3)
6347 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6348 else if (HowLong == 2)
6349 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6350 else if (HowLong == 1)
6351 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6352 else
6353 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6354 break;
6355 case 'c':
6356 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6357 if (Signed)
6358 Type = Context.SignedCharTy;
6359 else if (Unsigned)
6360 Type = Context.UnsignedCharTy;
6361 else
6362 Type = Context.CharTy;
6363 break;
6364 case 'b': // boolean
6365 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6366 Type = Context.BoolTy;
6367 break;
6368 case 'z': // size_t.
6369 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6370 Type = Context.getSizeType();
6371 break;
6372 case 'F':
6373 Type = Context.getCFConstantStringType();
6374 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00006375 case 'G':
6376 Type = Context.getObjCIdType();
6377 break;
6378 case 'H':
6379 Type = Context.getObjCSelType();
6380 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006381 case 'a':
6382 Type = Context.getBuiltinVaListType();
6383 assert(!Type.isNull() && "builtin va list type not initialized!");
6384 break;
6385 case 'A':
6386 // This is a "reference" to a va_list; however, what exactly
6387 // this means depends on how va_list is defined. There are two
6388 // different kinds of va_list: ones passed by value, and ones
6389 // passed by reference. An example of a by-value va_list is
6390 // x86, where va_list is a char*. An example of by-ref va_list
6391 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6392 // we want this argument to be a char*&; for x86-64, we want
6393 // it to be a __va_list_tag*.
6394 Type = Context.getBuiltinVaListType();
6395 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00006396 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00006397 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00006398 else
Chris Lattner86df27b2009-06-14 00:45:47 +00006399 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00006400 break;
6401 case 'V': {
6402 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00006403 unsigned NumElements = strtoul(Str, &End, 10);
6404 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00006405 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00006406
Chris Lattner14e0e742010-10-01 22:53:11 +00006407 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6408 RequiresICE, false);
6409 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00006410
6411 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00006412 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00006413 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00006414 break;
6415 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00006416 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00006417 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6418 false);
6419 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00006420 Type = Context.getComplexType(ElementType);
6421 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00006422 }
6423 case 'Y' : {
6424 Type = Context.getPointerDiffType();
6425 break;
6426 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006427 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00006428 Type = Context.getFILEType();
6429 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006430 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00006431 return QualType();
6432 }
Mike Stumpfd612db2009-07-28 23:47:15 +00006433 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006434 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00006435 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00006436 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00006437 else
6438 Type = Context.getjmp_bufType();
6439
Mike Stumpfd612db2009-07-28 23:47:15 +00006440 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006441 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00006442 return QualType();
6443 }
6444 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00006445 case 'K':
6446 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6447 Type = Context.getucontext_tType();
6448
6449 if (Type.isNull()) {
6450 Error = ASTContext::GE_Missing_ucontext;
6451 return QualType();
6452 }
6453 break;
Mike Stump782fa302009-07-28 02:25:19 +00006454 }
Mike Stump1eb44332009-09-09 15:08:12 +00006455
Chris Lattner33daae62010-10-01 22:42:38 +00006456 // If there are modifiers and if we're allowed to parse them, go for it.
6457 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00006458 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00006459 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00006460 default: Done = true; --Str; break;
6461 case '*':
6462 case '&': {
6463 // Both pointers and references can have their pointee types
6464 // qualified with an address space.
6465 char *End;
6466 unsigned AddrSpace = strtoul(Str, &End, 10);
6467 if (End != Str && AddrSpace != 0) {
6468 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6469 Str = End;
6470 }
6471 if (c == '*')
6472 Type = Context.getPointerType(Type);
6473 else
6474 Type = Context.getLValueReferenceType(Type);
6475 break;
6476 }
6477 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6478 case 'C':
6479 Type = Type.withConst();
6480 break;
6481 case 'D':
6482 Type = Context.getVolatileType(Type);
6483 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00006484 case 'R':
6485 Type = Type.withRestrict();
6486 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006487 }
6488 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00006489
Chris Lattner14e0e742010-10-01 22:53:11 +00006490 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00006491 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00006492
Chris Lattner86df27b2009-06-14 00:45:47 +00006493 return Type;
6494}
6495
6496/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00006497QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00006498 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00006499 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00006500 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00006501
Chris Lattner5f9e2722011-07-23 10:55:15 +00006502 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00006503
Chris Lattner14e0e742010-10-01 22:53:11 +00006504 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00006505 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00006506 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6507 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006508 if (Error != GE_None)
6509 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00006510
6511 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6512
Chris Lattner86df27b2009-06-14 00:45:47 +00006513 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00006514 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006515 if (Error != GE_None)
6516 return QualType();
6517
Chris Lattner14e0e742010-10-01 22:53:11 +00006518 // If this argument is required to be an IntegerConstantExpression and the
6519 // caller cares, fill in the bitmask we return.
6520 if (RequiresICE && IntegerConstantArgs)
6521 *IntegerConstantArgs |= 1 << ArgTypes.size();
6522
Chris Lattner86df27b2009-06-14 00:45:47 +00006523 // Do array -> pointer decay. The builtin should use the decayed type.
6524 if (Ty->isArrayType())
6525 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00006526
Chris Lattner86df27b2009-06-14 00:45:47 +00006527 ArgTypes.push_back(Ty);
6528 }
6529
6530 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6531 "'.' should only occur at end of builtin type list!");
6532
John McCall00ccbef2010-12-21 00:44:39 +00006533 FunctionType::ExtInfo EI;
6534 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6535
6536 bool Variadic = (TypeStr[0] == '.');
6537
6538 // We really shouldn't be making a no-proto type here, especially in C++.
6539 if (ArgTypes.empty() && Variadic)
6540 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00006541
John McCalle23cf432010-12-14 08:05:40 +00006542 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00006543 EPI.ExtInfo = EI;
6544 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00006545
6546 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00006547}
Eli Friedmana95d7572009-08-19 07:44:53 +00006548
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006549GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6550 GVALinkage External = GVA_StrongExternal;
6551
6552 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006553 switch (L) {
6554 case NoLinkage:
6555 case InternalLinkage:
6556 case UniqueExternalLinkage:
6557 return GVA_Internal;
6558
6559 case ExternalLinkage:
6560 switch (FD->getTemplateSpecializationKind()) {
6561 case TSK_Undeclared:
6562 case TSK_ExplicitSpecialization:
6563 External = GVA_StrongExternal;
6564 break;
6565
6566 case TSK_ExplicitInstantiationDefinition:
6567 return GVA_ExplicitTemplateInstantiation;
6568
6569 case TSK_ExplicitInstantiationDeclaration:
6570 case TSK_ImplicitInstantiation:
6571 External = GVA_TemplateInstantiation;
6572 break;
6573 }
6574 }
6575
6576 if (!FD->isInlined())
6577 return External;
6578
David Blaikie4e4d0842012-03-11 07:00:24 +00006579 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006580 // GNU or C99 inline semantics. Determine whether this symbol should be
6581 // externally visible.
6582 if (FD->isInlineDefinitionExternallyVisible())
6583 return External;
6584
6585 // C99 inline semantics, where the symbol is not externally visible.
6586 return GVA_C99Inline;
6587 }
6588
6589 // C++0x [temp.explicit]p9:
6590 // [ Note: The intent is that an inline function that is the subject of
6591 // an explicit instantiation declaration will still be implicitly
6592 // instantiated when used so that the body can be considered for
6593 // inlining, but that no out-of-line copy of the inline function would be
6594 // generated in the translation unit. -- end note ]
6595 if (FD->getTemplateSpecializationKind()
6596 == TSK_ExplicitInstantiationDeclaration)
6597 return GVA_C99Inline;
6598
6599 return GVA_CXXInline;
6600}
6601
6602GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6603 // If this is a static data member, compute the kind of template
6604 // specialization. Otherwise, this variable is not part of a
6605 // template.
6606 TemplateSpecializationKind TSK = TSK_Undeclared;
6607 if (VD->isStaticDataMember())
6608 TSK = VD->getTemplateSpecializationKind();
6609
6610 Linkage L = VD->getLinkage();
David Blaikie4e4d0842012-03-11 07:00:24 +00006611 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006612 VD->getType()->getLinkage() == UniqueExternalLinkage)
6613 L = UniqueExternalLinkage;
6614
6615 switch (L) {
6616 case NoLinkage:
6617 case InternalLinkage:
6618 case UniqueExternalLinkage:
6619 return GVA_Internal;
6620
6621 case ExternalLinkage:
6622 switch (TSK) {
6623 case TSK_Undeclared:
6624 case TSK_ExplicitSpecialization:
6625 return GVA_StrongExternal;
6626
6627 case TSK_ExplicitInstantiationDeclaration:
6628 llvm_unreachable("Variable should not be instantiated");
6629 // Fall through to treat this like any other instantiation.
6630
6631 case TSK_ExplicitInstantiationDefinition:
6632 return GVA_ExplicitTemplateInstantiation;
6633
6634 case TSK_ImplicitInstantiation:
6635 return GVA_TemplateInstantiation;
6636 }
6637 }
6638
David Blaikie7530c032012-01-17 06:56:22 +00006639 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006640}
6641
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00006642bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006643 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6644 if (!VD->isFileVarDecl())
6645 return false;
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00006646 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006647 return false;
6648
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006649 // Weak references don't produce any output by themselves.
6650 if (D->hasAttr<WeakRefAttr>())
6651 return false;
6652
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006653 // Aliases and used decls are required.
6654 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6655 return true;
6656
6657 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6658 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00006659 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00006660 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006661
6662 // Constructors and destructors are required.
6663 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6664 return true;
6665
6666 // The key function for a class is required.
6667 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6668 const CXXRecordDecl *RD = MD->getParent();
6669 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6670 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6671 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6672 return true;
6673 }
6674 }
6675
6676 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6677
6678 // static, static inline, always_inline, and extern inline functions can
6679 // always be deferred. Normal inline functions can be deferred in C99/C++.
6680 // Implicit template instantiations can also be deferred in C++.
6681 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00006682 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006683 return false;
6684 return true;
6685 }
Douglas Gregor94da1582011-09-10 00:22:34 +00006686
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006687 const VarDecl *VD = cast<VarDecl>(D);
6688 assert(VD->isFileVarDecl() && "Expected file scoped var");
6689
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006690 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6691 return false;
6692
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006693 // Structs that have non-trivial constructors or destructors are required.
6694
6695 // FIXME: Handle references.
Sean Hunt023df372011-05-09 18:22:59 +00006696 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006697 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6698 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Sean Hunt023df372011-05-09 18:22:59 +00006699 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6700 RD->hasTrivialCopyConstructor() &&
6701 RD->hasTrivialMoveConstructor() &&
6702 RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006703 return true;
6704 }
6705 }
6706
6707 GVALinkage L = GetGVALinkageForVariable(VD);
6708 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6709 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6710 return false;
6711 }
6712
6713 return true;
6714}
Charles Davis071cc7d2010-08-16 03:33:14 +00006715
Charles Davisee743f92010-11-09 18:04:24 +00006716CallingConv ASTContext::getDefaultMethodCallConv() {
6717 // Pass through to the C++ ABI object
6718 return ABI->getDefaultMethodCallConv();
6719}
6720
Jay Foad4ba2a172011-01-12 09:06:06 +00006721bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00006722 // Pass through to the C++ ABI object
6723 return ABI->isNearlyEmpty(RD);
6724}
6725
Peter Collingbourne14110472011-01-13 18:57:25 +00006726MangleContext *ASTContext::createMangleContext() {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00006727 switch (Target->getCXXABI()) {
Peter Collingbourne14110472011-01-13 18:57:25 +00006728 case CXXABI_ARM:
6729 case CXXABI_Itanium:
6730 return createItaniumMangleContext(*this, getDiagnostics());
6731 case CXXABI_Microsoft:
6732 return createMicrosoftMangleContext(*this, getDiagnostics());
6733 }
David Blaikieb219cfc2011-09-23 05:06:16 +00006734 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00006735}
6736
Charles Davis071cc7d2010-08-16 03:33:14 +00006737CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00006738
6739size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00006740 return ASTRecordLayouts.getMemorySize()
6741 + llvm::capacity_in_bytes(ObjCLayouts)
6742 + llvm::capacity_in_bytes(KeyFunctions)
6743 + llvm::capacity_in_bytes(ObjCImpls)
6744 + llvm::capacity_in_bytes(BlockVarCopyInits)
6745 + llvm::capacity_in_bytes(DeclAttrs)
6746 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6747 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6748 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6749 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6750 + llvm::capacity_in_bytes(OverriddenMethods)
6751 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00006752 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00006753 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00006754}
Ted Kremenekd211cb72011-10-06 05:00:56 +00006755
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00006756unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
6757 CXXRecordDecl *Lambda = CallOperator->getParent();
6758 return LambdaMangleContexts[Lambda->getDeclContext()]
6759 .getManglingNumber(CallOperator);
6760}
6761
6762
Ted Kremenekd211cb72011-10-06 05:00:56 +00006763void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6764 ParamIndices[D] = index;
6765}
6766
6767unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6768 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6769 assert(I != ParamIndices.end() &&
6770 "ParmIndices lacks entry set by ParmVarDecl");
6771 return I->second;
6772}