blob: ae96dfd14816fd4a4a0138f05516f801c13fdf1d [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 {
53 FloatRank, DoubleRank, LongDoubleRank
54};
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());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000077 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +000078 if (NTTP->isExpandedParameterPack()) {
79 ID.AddBoolean(true);
80 ID.AddInteger(NTTP->getNumExpansionTypes());
81 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
82 ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
83 } else
84 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +000085 continue;
86 }
87
88 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
89 ID.AddInteger(2);
90 Profile(ID, TTP);
91 }
92}
93
94TemplateTemplateParmDecl *
95ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +000096 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +000097 // Check if we already have a canonical template template parameter.
98 llvm::FoldingSetNodeID ID;
99 CanonicalTemplateTemplateParm::Profile(ID, TTP);
100 void *InsertPos = 0;
101 CanonicalTemplateTemplateParm *Canonical
102 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
103 if (Canonical)
104 return Canonical->getParam();
105
106 // Build a canonical template parameter list.
107 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000108 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000109 CanonParams.reserve(Params->size());
110 for (TemplateParameterList::const_iterator P = Params->begin(),
111 PEnd = Params->end();
112 P != PEnd; ++P) {
113 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
114 CanonParams.push_back(
115 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000116 SourceLocation(),
117 SourceLocation(),
118 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000119 TTP->getIndex(), 0, false,
120 TTP->isParameterPack()));
121 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000122 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
123 QualType T = getCanonicalType(NTTP->getType());
124 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
125 NonTypeTemplateParmDecl *Param;
126 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000127 SmallVector<QualType, 2> ExpandedTypes;
128 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000129 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
130 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
131 ExpandedTInfos.push_back(
132 getTrivialTypeSourceInfo(ExpandedTypes.back()));
133 }
134
135 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000136 SourceLocation(),
137 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000138 NTTP->getDepth(),
139 NTTP->getPosition(), 0,
140 T,
141 TInfo,
142 ExpandedTypes.data(),
143 ExpandedTypes.size(),
144 ExpandedTInfos.data());
145 } else {
146 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000147 SourceLocation(),
148 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000149 NTTP->getDepth(),
150 NTTP->getPosition(), 0,
151 T,
152 NTTP->isParameterPack(),
153 TInfo);
154 }
155 CanonParams.push_back(Param);
156
157 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000158 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
159 cast<TemplateTemplateParmDecl>(*P)));
160 }
161
162 TemplateTemplateParmDecl *CanonTTP
163 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
164 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000165 TTP->getPosition(),
166 TTP->isParameterPack(),
167 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000168 TemplateParameterList::Create(*this, SourceLocation(),
169 SourceLocation(),
170 CanonParams.data(),
171 CanonParams.size(),
172 SourceLocation()));
173
174 // Get the new insert position for the node we care about.
175 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
176 assert(Canonical == 0 && "Shouldn't be in the map!");
177 (void)Canonical;
178
179 // Create the canonical template template parameter entry.
180 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
181 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
182 return CanonTTP;
183}
184
Charles Davis071cc7d2010-08-16 03:33:14 +0000185CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000186 if (!LangOpts.CPlusPlus) return 0;
187
Charles Davis20cf7172010-08-19 02:18:14 +0000188 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000189 case CXXABI_ARM:
190 return CreateARMCXXABI(*this);
191 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000192 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000193 case CXXABI_Microsoft:
194 return CreateMicrosoftCXXABI(*this);
195 }
John McCallee79a4c2010-08-21 22:46:04 +0000196 return 0;
Charles Davis071cc7d2010-08-16 03:33:14 +0000197}
198
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000199static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000200 const LangOptions &LOpts) {
201 if (LOpts.FakeAddressSpaceMap) {
202 // The fake address space map must have a distinct entry for each
203 // language-specific address space.
204 static const unsigned FakeAddrSpaceMap[] = {
205 1, // opencl_global
206 2, // opencl_local
207 3 // opencl_constant
208 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000209 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000210 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000211 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000212 }
213}
214
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000215ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000216 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000217 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000218 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000219 unsigned size_reserve,
220 bool DelayInitialization)
221 : FunctionProtoTypes(this_()),
222 TemplateSpecializationTypes(this_()),
223 DependentTemplateSpecializationTypes(this_()),
224 SubstTemplateTemplateParmPacks(this_()),
225 GlobalNestedNameSpecifier(0),
226 Int128Decl(0), UInt128Decl(0),
227 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000228 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000229 FILEDecl(0),
230 jmp_bufDecl(0), sigjmp_bufDecl(0), BlockDescriptorType(0),
231 BlockDescriptorExtendedType(0), cudaConfigureCallDecl(0),
232 NullTypeSourceInfo(QualType()),
233 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000234 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000235 Idents(idents), Selectors(sels),
236 BuiltinInfo(builtins),
237 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000238 ExternalSource(0), Listener(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000239 LastSDM(0, 0),
240 UniqueBlockByRefTypeID(0)
241{
Mike Stump1eb44332009-09-09 15:08:12 +0000242 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000243 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000244
245 if (!DelayInitialization) {
246 assert(t && "No target supplied for ASTContext initialization");
247 InitBuiltinTypes(*t);
248 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000249}
250
Reid Spencer5f016e22007-07-11 17:01:13 +0000251ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000252 // Release the DenseMaps associated with DeclContext objects.
253 // FIXME: Is this the ideal solution?
254 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000255
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000256 // Call all of the deallocation functions.
257 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
258 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000259
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000260 // Release all of the memory associated with overridden C++ methods.
261 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
262 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
263 OM != OMEnd; ++OM)
264 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +0000265
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000266 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000267 // because they can contain DenseMaps.
268 for (llvm::DenseMap<const ObjCContainerDecl*,
269 const ASTRecordLayout*>::iterator
270 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
271 // Increment in loop to prevent using deallocated memory.
272 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
273 R->Destroy(*this);
274
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000275 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
276 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
277 // Increment in loop to prevent using deallocated memory.
278 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
279 R->Destroy(*this);
280 }
Douglas Gregor63200642010-08-30 16:49:28 +0000281
282 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
283 AEnd = DeclAttrs.end();
284 A != AEnd; ++A)
285 A->second->~AttrVec();
286}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000287
Douglas Gregor00545312010-05-23 18:26:36 +0000288void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
289 Deallocations.push_back(std::make_pair(Callback, Data));
290}
291
Mike Stump1eb44332009-09-09 15:08:12 +0000292void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000293ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
294 ExternalSource.reset(Source.take());
295}
296
Reid Spencer5f016e22007-07-11 17:01:13 +0000297void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000298 llvm::errs() << "\n*** AST Context Stats:\n";
299 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000300
Douglas Gregordbe833d2009-05-26 14:40:08 +0000301 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000302#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000303#define ABSTRACT_TYPE(Name, Parent)
304#include "clang/AST/TypeNodes.def"
305 0 // Extra
306 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000307
Reid Spencer5f016e22007-07-11 17:01:13 +0000308 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
309 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000310 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000311 }
312
Douglas Gregordbe833d2009-05-26 14:40:08 +0000313 unsigned Idx = 0;
314 unsigned TotalBytes = 0;
315#define TYPE(Name, Parent) \
316 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000317 llvm::errs() << " " << counts[Idx] << " " << #Name \
318 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000319 TotalBytes += counts[Idx] * sizeof(Name##Type); \
320 ++Idx;
321#define ABSTRACT_TYPE(Name, Parent)
322#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Chandler Carruthcd92a652011-07-04 05:32:14 +0000324 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
325
Douglas Gregor4923aa22010-07-02 20:37:36 +0000326 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000327 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
328 << NumImplicitDefaultConstructors
329 << " implicit default constructors created\n";
330 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
331 << NumImplicitCopyConstructors
332 << " implicit copy constructors created\n";
Sean Huntffe37fd2011-05-25 20:50:04 +0000333 if (getLangOptions().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000334 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
335 << NumImplicitMoveConstructors
336 << " implicit move constructors created\n";
337 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
338 << NumImplicitCopyAssignmentOperators
339 << " implicit copy assignment operators created\n";
Sean Huntffe37fd2011-05-25 20:50:04 +0000340 if (getLangOptions().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000341 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
342 << NumImplicitMoveAssignmentOperators
343 << " implicit move assignment operators created\n";
344 llvm::errs() << NumImplicitDestructorsDeclared << "/"
345 << NumImplicitDestructors
346 << " implicit destructors created\n";
347
Douglas Gregor2cf26342009-04-09 22:27:44 +0000348 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000349 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000350 ExternalSource->PrintStats();
351 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000352
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000353 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000354}
355
Douglas Gregor772eeae2011-08-12 06:49:56 +0000356TypedefDecl *ASTContext::getInt128Decl() const {
357 if (!Int128Decl) {
358 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
359 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
360 getTranslationUnitDecl(),
361 SourceLocation(),
362 SourceLocation(),
363 &Idents.get("__int128_t"),
364 TInfo);
365 }
366
367 return Int128Decl;
368}
369
370TypedefDecl *ASTContext::getUInt128Decl() const {
371 if (!UInt128Decl) {
372 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
373 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
374 getTranslationUnitDecl(),
375 SourceLocation(),
376 SourceLocation(),
377 &Idents.get("__uint128_t"),
378 TInfo);
379 }
380
381 return UInt128Decl;
382}
Reid Spencer5f016e22007-07-11 17:01:13 +0000383
John McCalle27ec8a2009-10-23 23:03:21 +0000384void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000385 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000386 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000387 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000388}
389
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000390void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
391 assert((!this->Target || this->Target == &Target) &&
392 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000393 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000395 this->Target = &Target;
396
397 ABI.reset(createCXXABI(Target));
398 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
399
Reid Spencer5f016e22007-07-11 17:01:13 +0000400 // C99 6.2.5p19.
401 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Reid Spencer5f016e22007-07-11 17:01:13 +0000403 // C99 6.2.5p2.
404 InitBuiltinType(BoolTy, BuiltinType::Bool);
405 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000406 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000407 InitBuiltinType(CharTy, BuiltinType::Char_S);
408 else
409 InitBuiltinType(CharTy, BuiltinType::Char_U);
410 // C99 6.2.5p4.
411 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
412 InitBuiltinType(ShortTy, BuiltinType::Short);
413 InitBuiltinType(IntTy, BuiltinType::Int);
414 InitBuiltinType(LongTy, BuiltinType::Long);
415 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000416
Reid Spencer5f016e22007-07-11 17:01:13 +0000417 // C99 6.2.5p6.
418 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
419 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
420 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
421 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
422 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Reid Spencer5f016e22007-07-11 17:01:13 +0000424 // C99 6.2.5p10.
425 InitBuiltinType(FloatTy, BuiltinType::Float);
426 InitBuiltinType(DoubleTy, BuiltinType::Double);
427 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000428
Chris Lattner2df9ced2009-04-30 02:43:43 +0000429 // GNU extension, 128-bit integers.
430 InitBuiltinType(Int128Ty, BuiltinType::Int128);
431 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
432
Chris Lattner3f59c972010-12-25 23:25:43 +0000433 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedmand3d77cd2011-04-30 19:24:24 +0000434 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattner3f59c972010-12-25 23:25:43 +0000435 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
436 else // -fshort-wchar makes wchar_t be unsigned.
437 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
438 } else // C99
Chris Lattner3a250322009-02-26 23:43:47 +0000439 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000440
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000441 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
442 InitBuiltinType(Char16Ty, BuiltinType::Char16);
443 else // C99
444 Char16Ty = getFromTargetType(Target.getChar16Type());
445
446 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
447 InitBuiltinType(Char32Ty, BuiltinType::Char32);
448 else // C99
449 Char32Ty = getFromTargetType(Target.getChar32Type());
450
Douglas Gregor898574e2008-12-05 23:32:09 +0000451 // Placeholder type for type-dependent expressions whose type is
452 // completely unknown. No code should ever check a type against
453 // DependentTy and users should never see it; however, it is here to
454 // help diagnose failures to properly check for type-dependent
455 // expressions.
456 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000457
John McCall2a984ca2010-10-12 00:20:44 +0000458 // Placeholder type for functions.
459 InitBuiltinType(OverloadTy, BuiltinType::Overload);
460
John McCall864c0412011-04-26 20:42:42 +0000461 // Placeholder type for bound members.
462 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
463
John McCall1de4d4e2011-04-07 08:22:57 +0000464 // "any" type; useful for debugger-like clients.
465 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
466
Reid Spencer5f016e22007-07-11 17:01:13 +0000467 // C99 6.2.5p11.
468 FloatComplexTy = getComplexType(FloatTy);
469 DoubleComplexTy = getComplexType(DoubleTy);
470 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000471
Steve Naroff7e219e42007-10-15 14:41:52 +0000472 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000474 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000475 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
476 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000477 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000478
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000479 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000481 // void * type
482 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000483
484 // nullptr type (C++0x 2.14.7)
485 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000486}
487
David Blaikied6471f72011-09-25 23:23:43 +0000488DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000489 return SourceMgr.getDiagnostics();
490}
491
Douglas Gregor63200642010-08-30 16:49:28 +0000492AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
493 AttrVec *&Result = DeclAttrs[D];
494 if (!Result) {
495 void *Mem = Allocate(sizeof(AttrVec));
496 Result = new (Mem) AttrVec;
497 }
498
499 return *Result;
500}
501
502/// \brief Erase the attributes corresponding to the given declaration.
503void ASTContext::eraseDeclAttrs(const Decl *D) {
504 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
505 if (Pos != DeclAttrs.end()) {
506 Pos->second->~AttrVec();
507 DeclAttrs.erase(Pos);
508 }
509}
510
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000511MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000512ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000513 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000514 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000515 = InstantiatedFromStaticDataMember.find(Var);
516 if (Pos == InstantiatedFromStaticDataMember.end())
517 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000518
Douglas Gregor7caa6822009-07-24 20:34:43 +0000519 return Pos->second;
520}
521
Mike Stump1eb44332009-09-09 15:08:12 +0000522void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000523ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000524 TemplateSpecializationKind TSK,
525 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000526 assert(Inst->isStaticDataMember() && "Not a static data member");
527 assert(Tmpl->isStaticDataMember() && "Not a static data member");
528 assert(!InstantiatedFromStaticDataMember[Inst] &&
529 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000530 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000531 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000532}
533
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000534FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
535 const FunctionDecl *FD){
536 assert(FD && "Specialization is 0");
537 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000538 = ClassScopeSpecializationPattern.find(FD);
539 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000540 return 0;
541
542 return Pos->second;
543}
544
545void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
546 FunctionDecl *Pattern) {
547 assert(FD && "Specialization is 0");
548 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000549 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000550}
551
John McCall7ba107a2009-11-18 02:36:19 +0000552NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000553ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000554 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000555 = InstantiatedFromUsingDecl.find(UUD);
556 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000557 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000558
Anders Carlsson0d8df782009-08-29 19:37:28 +0000559 return Pos->second;
560}
561
562void
John McCalled976492009-12-04 22:46:56 +0000563ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
564 assert((isa<UsingDecl>(Pattern) ||
565 isa<UnresolvedUsingValueDecl>(Pattern) ||
566 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
567 "pattern decl is not a using decl");
568 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
569 InstantiatedFromUsingDecl[Inst] = Pattern;
570}
571
572UsingShadowDecl *
573ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
574 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
575 = InstantiatedFromUsingShadowDecl.find(Inst);
576 if (Pos == InstantiatedFromUsingShadowDecl.end())
577 return 0;
578
579 return Pos->second;
580}
581
582void
583ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
584 UsingShadowDecl *Pattern) {
585 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
586 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000587}
588
Anders Carlssond8b285f2009-09-01 04:26:58 +0000589FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
590 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
591 = InstantiatedFromUnnamedFieldDecl.find(Field);
592 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
593 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000594
Anders Carlssond8b285f2009-09-01 04:26:58 +0000595 return Pos->second;
596}
597
598void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
599 FieldDecl *Tmpl) {
600 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
601 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
602 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
603 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000604
Anders Carlssond8b285f2009-09-01 04:26:58 +0000605 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
606}
607
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000608bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
609 const FieldDecl *LastFD) const {
610 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000611 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000612}
613
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000614bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
615 const FieldDecl *LastFD) const {
616 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000617 FD->getBitWidthValue(*this) == 0 &&
618 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000619}
620
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000621bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
622 const FieldDecl *LastFD) const {
623 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000624 FD->getBitWidthValue(*this) &&
625 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000626}
627
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000628bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000629 const FieldDecl *LastFD) const {
630 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000631 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000632}
633
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000634bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000635 const FieldDecl *LastFD) const {
636 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000637 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000638}
639
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000640ASTContext::overridden_cxx_method_iterator
641ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
642 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
643 = OverriddenMethods.find(Method);
644 if (Pos == OverriddenMethods.end())
645 return 0;
646
647 return Pos->second.begin();
648}
649
650ASTContext::overridden_cxx_method_iterator
651ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
652 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
653 = OverriddenMethods.find(Method);
654 if (Pos == OverriddenMethods.end())
655 return 0;
656
657 return Pos->second.end();
658}
659
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000660unsigned
661ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
662 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
663 = OverriddenMethods.find(Method);
664 if (Pos == OverriddenMethods.end())
665 return 0;
666
667 return Pos->second.size();
668}
669
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000670void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
671 const CXXMethodDecl *Overridden) {
672 OverriddenMethods[Method].push_back(Overridden);
673}
674
Chris Lattner464175b2007-07-18 17:52:12 +0000675//===----------------------------------------------------------------------===//
676// Type Sizing and Analysis
677//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000678
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000679/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
680/// scalar floating point type.
681const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000682 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000683 assert(BT && "Not a floating point type!");
684 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000685 default: llvm_unreachable("Not a floating point type!");
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000686 case BuiltinType::Float: return Target->getFloatFormat();
687 case BuiltinType::Double: return Target->getDoubleFormat();
688 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000689 }
690}
691
Ken Dyck8b752f12010-01-27 17:10:57 +0000692/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000693/// specified decl. Note that bitfields do not have a valid alignment, so
694/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000695/// If @p RefAsPointee, references are treated like their underlying type
696/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +0000697CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000698 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +0000699
John McCall4081a5c2010-10-08 18:24:19 +0000700 bool UseAlignAttrOnly = false;
701 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
702 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +0000703
John McCall4081a5c2010-10-08 18:24:19 +0000704 // __attribute__((aligned)) can increase or decrease alignment
705 // *except* on a struct or struct member, where it only increases
706 // alignment unless 'packed' is also specified.
707 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +0000708 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +0000709 // ignore that possibility; Sema should diagnose it.
710 if (isa<FieldDecl>(D)) {
711 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
712 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
713 } else {
714 UseAlignAttrOnly = true;
715 }
716 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +0000717 else if (isa<FieldDecl>(D))
718 UseAlignAttrOnly =
719 D->hasAttr<PackedAttr>() ||
720 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +0000721
John McCallba4f5d52011-01-20 07:57:12 +0000722 // If we're using the align attribute only, just ignore everything
723 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +0000724 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +0000725 // do nothing
726
John McCall4081a5c2010-10-08 18:24:19 +0000727 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +0000728 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000729 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000730 if (RefAsPointee)
731 T = RT->getPointeeType();
732 else
733 T = getPointerType(RT->getPointeeType());
734 }
735 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +0000736 // Adjust alignments of declarations with array type by the
737 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000738 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +0000739 const ArrayType *arrayType;
740 if (MinWidth && (arrayType = getAsArrayType(T))) {
741 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000742 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +0000743 else if (isa<ConstantArrayType>(arrayType) &&
744 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000745 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000746
John McCall3b657512011-01-19 10:06:00 +0000747 // Walk through any array types while we're at it.
748 T = getBaseElementType(arrayType);
749 }
Chad Rosier9f1210c2011-07-26 07:03:04 +0000750 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedmandcdafb62009-02-22 02:56:25 +0000751 }
John McCallba4f5d52011-01-20 07:57:12 +0000752
753 // Fields can be subject to extra alignment constraints, like if
754 // the field is packed, the struct is packed, or the struct has a
755 // a max-field-alignment constraint (#pragma pack). So calculate
756 // the actual alignment of the field within the struct, and then
757 // (as we're expected to) constrain that by the alignment of the type.
758 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
759 // So calculate the alignment of the field.
760 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
761
762 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +0000763 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +0000764
765 // Use the GCD of that and the offset within the record.
766 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
767 if (offset > 0) {
768 // Alignment is always a power of 2, so the GCD will be a power of 2,
769 // which means we get to do this crazy thing instead of Euclid's.
770 uint64_t lowBitOfOffset = offset & (~offset + 1);
771 if (lowBitOfOffset < fieldAlign)
772 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
773 }
774
775 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +0000776 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000777 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000778
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000779 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +0000780}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000781
John McCallea1471e2010-05-20 01:18:31 +0000782std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000783ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +0000784 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000785 return std::make_pair(toCharUnitsFromBits(Info.first),
786 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +0000787}
788
789std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000790ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +0000791 return getTypeInfoInChars(T.getTypePtr());
792}
793
Chris Lattnera7674d82007-07-13 22:13:22 +0000794/// getTypeSize - Return the size of the specified type, in bits. This method
795/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000796///
797/// FIXME: Pointers into different addr spaces could have different sizes and
798/// alignment requirements: getPointerInfo should take an AddrSpace, this
799/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000800std::pair<uint64_t, unsigned>
Jay Foad4ba2a172011-01-12 09:06:06 +0000801ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +0000802 uint64_t Width=0;
803 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000804 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000805#define TYPE(Class, Base)
806#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000807#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000808#define DEPENDENT_TYPE(Class, Base) case Type::Class:
809#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +0000810 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000811 break;
812
Chris Lattner692233e2007-07-13 22:27:08 +0000813 case Type::FunctionNoProto:
814 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000815 // GCC extension: alignof(function) = 32 bits
816 Width = 0;
817 Align = 32;
818 break;
819
Douglas Gregor72564e72009-02-26 23:50:07 +0000820 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000821 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000822 Width = 0;
823 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
824 break;
825
Steve Narofffb22d962007-08-30 01:06:46 +0000826 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000827 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000828
Chris Lattner98be4942008-03-05 18:54:05 +0000829 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000830 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000831 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +0000832 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000833 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000834 }
Nate Begeman213541a2008-04-18 23:10:10 +0000835 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000836 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000837 const VectorType *VT = cast<VectorType>(T);
838 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
839 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000840 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000841 // If the alignment is not a power of 2, round up to the next power of 2.
842 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000843 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000844 Align = llvm::NextPowerOf2(Align);
845 Width = llvm::RoundUpToAlignment(Width, Align);
846 }
Chris Lattner030d8842007-07-19 22:06:24 +0000847 break;
848 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000849
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000850 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000851 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000852 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000853 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000854 // GCC extension: alignof(void) = 8 bits.
855 Width = 0;
856 Align = 8;
857 break;
858
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000859 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000860 Width = Target->getBoolWidth();
861 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000862 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000863 case BuiltinType::Char_S:
864 case BuiltinType::Char_U:
865 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000866 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000867 Width = Target->getCharWidth();
868 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000869 break;
Chris Lattner3f59c972010-12-25 23:25:43 +0000870 case BuiltinType::WChar_S:
871 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000872 Width = Target->getWCharWidth();
873 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000874 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000875 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000876 Width = Target->getChar16Width();
877 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000878 break;
879 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000880 Width = Target->getChar32Width();
881 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000882 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000883 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000884 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000885 Width = Target->getShortWidth();
886 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000887 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000888 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000889 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000890 Width = Target->getIntWidth();
891 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000892 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000893 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000894 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000895 Width = Target->getLongWidth();
896 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000897 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000898 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000899 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000900 Width = Target->getLongLongWidth();
901 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000902 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000903 case BuiltinType::Int128:
904 case BuiltinType::UInt128:
905 Width = 128;
906 Align = 128; // int128_t is 128-bit aligned on all targets.
907 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000908 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000909 Width = Target->getFloatWidth();
910 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000911 break;
912 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000913 Width = Target->getDoubleWidth();
914 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000915 break;
916 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000917 Width = Target->getLongDoubleWidth();
918 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000919 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000920 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000921 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
922 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000923 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000924 case BuiltinType::ObjCId:
925 case BuiltinType::ObjCClass:
926 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000927 Width = Target->getPointerWidth(0);
928 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000929 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000930 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000931 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000932 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000933 Width = Target->getPointerWidth(0);
934 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000935 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000936 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000937 unsigned AS = getTargetAddressSpace(
938 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000939 Width = Target->getPointerWidth(AS);
940 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +0000941 break;
942 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000943 case Type::LValueReference:
944 case Type::RValueReference: {
945 // alignof and sizeof should never enter this code path here, so we go
946 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000947 unsigned AS = getTargetAddressSpace(
948 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000949 Width = Target->getPointerWidth(AS);
950 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +0000951 break;
952 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000953 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000954 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000955 Width = Target->getPointerWidth(AS);
956 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000957 break;
958 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000959 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +0000960 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000961 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000962 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +0000963 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000964 Align = PtrDiffInfo.second;
965 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000966 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000967 case Type::Complex: {
968 // Complex types have the same alignment as their elements, but twice the
969 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000970 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000971 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000972 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000973 Align = EltInfo.second;
974 break;
975 }
John McCallc12c5bb2010-05-15 11:32:37 +0000976 case Type::ObjCObject:
977 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000978 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000979 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000980 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +0000981 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +0000982 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +0000983 break;
984 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000985 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000986 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000987 const TagType *TT = cast<TagType>(T);
988
989 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +0000990 Width = 8;
991 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +0000992 break;
993 }
Mike Stump1eb44332009-09-09 15:08:12 +0000994
Daniel Dunbar1d751182008-11-08 05:48:37 +0000995 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000996 return getTypeInfo(ET->getDecl()->getIntegerType());
997
Daniel Dunbar1d751182008-11-08 05:48:37 +0000998 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000999 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001000 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001001 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001002 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001003 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001004
Chris Lattner9fcfe922009-10-22 05:17:15 +00001005 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001006 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1007 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001008
Richard Smith34b41d92011-02-20 03:19:35 +00001009 case Type::Auto: {
1010 const AutoType *A = cast<AutoType>(T);
1011 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001012 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001013 }
1014
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001015 case Type::Paren:
1016 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1017
Douglas Gregor18857642009-04-30 17:32:17 +00001018 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001019 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001020 std::pair<uint64_t, unsigned> Info
1021 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001022 // If the typedef has an aligned attribute on it, it overrides any computed
1023 // alignment we have. This violates the GCC documentation (which says that
1024 // attribute(aligned) can only round up) but matches its implementation.
1025 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1026 Align = AttrAlign;
1027 else
1028 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001029 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001030 break;
Chris Lattner71763312008-04-06 22:05:18 +00001031 }
Douglas Gregor18857642009-04-30 17:32:17 +00001032
1033 case Type::TypeOfExpr:
1034 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1035 .getTypePtr());
1036
1037 case Type::TypeOf:
1038 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1039
Anders Carlsson395b4752009-06-24 19:06:50 +00001040 case Type::Decltype:
1041 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1042 .getTypePtr());
1043
Sean Huntca63c202011-05-24 22:41:36 +00001044 case Type::UnaryTransform:
1045 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1046
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001047 case Type::Elaborated:
1048 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001049
John McCall9d156a72011-01-06 01:58:22 +00001050 case Type::Attributed:
1051 return getTypeInfo(
1052 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1053
Richard Smith3e4c6c42011-05-05 21:57:07 +00001054 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001055 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001056 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001057 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1058 // A type alias template specialization may refer to a typedef with the
1059 // aligned attribute on it.
1060 if (TST->isTypeAlias())
1061 return getTypeInfo(TST->getAliasedType().getTypePtr());
1062 else
1063 return getTypeInfo(getCanonicalType(T));
1064 }
1065
Eli Friedmanb001de72011-10-06 23:00:33 +00001066 case Type::Atomic: {
Eli Friedman2be46072011-10-14 20:59:01 +00001067 std::pair<uint64_t, unsigned> Info
1068 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1069 Width = Info.first;
1070 Align = Info.second;
1071 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1072 llvm::isPowerOf2_64(Width)) {
1073 // We can potentially perform lock-free atomic operations for this
1074 // type; promote the alignment appropriately.
1075 // FIXME: We could potentially promote the width here as well...
1076 // is that worthwhile? (Non-struct atomic types generally have
1077 // power-of-two size anyway, but structs might not. Requires a bit
1078 // of implementation work to make sure we zero out the extra bits.)
1079 Align = static_cast<unsigned>(Width);
1080 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001081 }
1082
Douglas Gregor18857642009-04-30 17:32:17 +00001083 }
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Eli Friedman2be46072011-10-14 20:59:01 +00001085 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001086 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001087}
1088
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001089/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1090CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1091 return CharUnits::fromQuantity(BitSize / getCharWidth());
1092}
1093
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001094/// toBits - Convert a size in characters to a size in characters.
1095int64_t ASTContext::toBits(CharUnits CharSize) const {
1096 return CharSize.getQuantity() * getCharWidth();
1097}
1098
Ken Dyckbdc601b2009-12-22 14:23:30 +00001099/// getTypeSizeInChars - Return the size of the specified type, in characters.
1100/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001101CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001102 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001103}
Jay Foad4ba2a172011-01-12 09:06:06 +00001104CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001105 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001106}
1107
Ken Dyck16e20cc2010-01-26 17:25:18 +00001108/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001109/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001110CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001111 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001112}
Jay Foad4ba2a172011-01-12 09:06:06 +00001113CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001114 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001115}
1116
Chris Lattner34ebde42009-01-27 18:08:34 +00001117/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1118/// type for the current target in bits. This can be different than the ABI
1119/// alignment in cases where it is beneficial for performance to overalign
1120/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001121unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001122 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001123
1124 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001125 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001126 T = CT->getElementType().getTypePtr();
1127 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1128 T->isSpecificBuiltinType(BuiltinType::LongLong))
1129 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1130
Chris Lattner34ebde42009-01-27 18:08:34 +00001131 return ABIAlign;
1132}
1133
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001134/// DeepCollectObjCIvars -
1135/// This routine first collects all declared, but not synthesized, ivars in
1136/// super class and then collects all ivars, including those synthesized for
1137/// current class. This routine is used for implementation of current class
1138/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001139///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001140void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1141 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001142 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001143 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1144 DeepCollectObjCIvars(SuperClass, false, Ivars);
1145 if (!leafClass) {
1146 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1147 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanian11062e12010-02-19 00:31:17 +00001148 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001149 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001150 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001151 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001152 Iv= Iv->getNextIvar())
1153 Ivars.push_back(Iv);
1154 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001155}
1156
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001157/// CollectInheritedProtocols - Collect all protocols in current class and
1158/// those inherited by it.
1159void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001160 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001161 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001162 // We can use protocol_iterator here instead of
1163 // all_referenced_protocol_iterator since we are walking all categories.
1164 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1165 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001166 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001167 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001168 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001169 PE = Proto->protocol_end(); P != PE; ++P) {
1170 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001171 CollectInheritedProtocols(*P, Protocols);
1172 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001173 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001174
1175 // Categories of this Interface.
1176 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1177 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1178 CollectInheritedProtocols(CDeclChain, Protocols);
1179 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1180 while (SD) {
1181 CollectInheritedProtocols(SD, Protocols);
1182 SD = SD->getSuperClass();
1183 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001184 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001185 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001186 PE = OC->protocol_end(); P != PE; ++P) {
1187 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001188 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001189 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1190 PE = Proto->protocol_end(); P != PE; ++P)
1191 CollectInheritedProtocols(*P, Protocols);
1192 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001193 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001194 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1195 PE = OP->protocol_end(); P != PE; ++P) {
1196 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001197 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001198 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1199 PE = Proto->protocol_end(); P != PE; ++P)
1200 CollectInheritedProtocols(*P, Protocols);
1201 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001202 }
1203}
1204
Jay Foad4ba2a172011-01-12 09:06:06 +00001205unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001206 unsigned count = 0;
1207 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001208 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1209 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001210 count += CDecl->ivar_size();
1211
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001212 // Count ivar defined in this class's implementation. This
1213 // includes synthesized ivars.
1214 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001215 count += ImplDecl->ivar_size();
1216
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001217 return count;
1218}
1219
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001220/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1221ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1222 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1223 I = ObjCImpls.find(D);
1224 if (I != ObjCImpls.end())
1225 return cast<ObjCImplementationDecl>(I->second);
1226 return 0;
1227}
1228/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1229ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1230 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1231 I = ObjCImpls.find(D);
1232 if (I != ObjCImpls.end())
1233 return cast<ObjCCategoryImplDecl>(I->second);
1234 return 0;
1235}
1236
1237/// \brief Set the implementation of ObjCInterfaceDecl.
1238void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1239 ObjCImplementationDecl *ImplD) {
1240 assert(IFaceD && ImplD && "Passed null params");
1241 ObjCImpls[IFaceD] = ImplD;
1242}
1243/// \brief Set the implementation of ObjCCategoryDecl.
1244void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1245 ObjCCategoryImplDecl *ImplD) {
1246 assert(CatD && ImplD && "Passed null params");
1247 ObjCImpls[CatD] = ImplD;
1248}
1249
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001250/// \brief Get the copy initialization expression of VarDecl,or NULL if
1251/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001252Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001253 assert(VD && "Passed null params");
1254 assert(VD->hasAttr<BlocksAttr>() &&
1255 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001256 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001257 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001258 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1259}
1260
1261/// \brief Set the copy inialization expression of a block var decl.
1262void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1263 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001264 assert(VD->hasAttr<BlocksAttr>() &&
1265 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001266 BlockVarCopyInits[VD] = Init;
1267}
1268
John McCalla93c9342009-12-07 02:54:59 +00001269/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001270///
John McCalla93c9342009-12-07 02:54:59 +00001271/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001272/// the TypeLoc wrappers.
1273///
1274/// \param T the type that will be the basis for type source info. This type
1275/// should refer to how the declarator was written in source code, not to
1276/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001277TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001278 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001279 if (!DataSize)
1280 DataSize = TypeLoc::getFullDataSizeForType(T);
1281 else
1282 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001283 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001284
John McCalla93c9342009-12-07 02:54:59 +00001285 TypeSourceInfo *TInfo =
1286 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1287 new (TInfo) TypeSourceInfo(T);
1288 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001289}
1290
John McCalla93c9342009-12-07 02:54:59 +00001291TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001292 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001293 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001294 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001295 return DI;
1296}
1297
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001298const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001299ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001300 return getObjCLayout(D, 0);
1301}
1302
1303const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001304ASTContext::getASTObjCImplementationLayout(
1305 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001306 return getObjCLayout(D->getClassInterface(), D);
1307}
1308
Chris Lattnera7674d82007-07-13 22:13:22 +00001309//===----------------------------------------------------------------------===//
1310// Type creation/memoization methods
1311//===----------------------------------------------------------------------===//
1312
Jay Foad4ba2a172011-01-12 09:06:06 +00001313QualType
John McCall3b657512011-01-19 10:06:00 +00001314ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1315 unsigned fastQuals = quals.getFastQualifiers();
1316 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001317
1318 // Check if we've already instantiated this type.
1319 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001320 ExtQuals::Profile(ID, baseType, quals);
1321 void *insertPos = 0;
1322 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1323 assert(eq->getQualifiers() == quals);
1324 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001325 }
1326
John McCall3b657512011-01-19 10:06:00 +00001327 // If the base type is not canonical, make the appropriate canonical type.
1328 QualType canon;
1329 if (!baseType->isCanonicalUnqualified()) {
1330 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1331 canonSplit.second.addConsistentQualifiers(quals);
1332 canon = getExtQualType(canonSplit.first, canonSplit.second);
1333
1334 // Re-find the insert position.
1335 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1336 }
1337
1338 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1339 ExtQualNodes.InsertNode(eq, insertPos);
1340 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001341}
1342
Jay Foad4ba2a172011-01-12 09:06:06 +00001343QualType
1344ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001345 QualType CanT = getCanonicalType(T);
1346 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001347 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001348
John McCall0953e762009-09-24 19:53:00 +00001349 // If we are composing extended qualifiers together, merge together
1350 // into one ExtQuals node.
1351 QualifierCollector Quals;
1352 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001353
John McCall0953e762009-09-24 19:53:00 +00001354 // If this type already has an address space specified, it cannot get
1355 // another one.
1356 assert(!Quals.hasAddressSpace() &&
1357 "Type cannot be in multiple addr spaces!");
1358 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001359
John McCall0953e762009-09-24 19:53:00 +00001360 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001361}
1362
Chris Lattnerb7d25532009-02-18 22:53:11 +00001363QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001364 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001365 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001366 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001367 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001368
John McCall7f040a92010-12-24 02:08:15 +00001369 if (const PointerType *ptr = T->getAs<PointerType>()) {
1370 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001371 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001372 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1373 return getPointerType(ResultType);
1374 }
1375 }
Mike Stump1eb44332009-09-09 15:08:12 +00001376
John McCall0953e762009-09-24 19:53:00 +00001377 // If we are composing extended qualifiers together, merge together
1378 // into one ExtQuals node.
1379 QualifierCollector Quals;
1380 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001381
John McCall0953e762009-09-24 19:53:00 +00001382 // If this type already has an ObjCGC specified, it cannot get
1383 // another one.
1384 assert(!Quals.hasObjCGCAttr() &&
1385 "Type cannot have multiple ObjCGCs!");
1386 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001387
John McCall0953e762009-09-24 19:53:00 +00001388 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001389}
Chris Lattnera7674d82007-07-13 22:13:22 +00001390
John McCalle6a365d2010-12-19 02:44:49 +00001391const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1392 FunctionType::ExtInfo Info) {
1393 if (T->getExtInfo() == Info)
1394 return T;
1395
1396 QualType Result;
1397 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1398 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1399 } else {
1400 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1401 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1402 EPI.ExtInfo = Info;
1403 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1404 FPT->getNumArgs(), EPI);
1405 }
1406
1407 return cast<FunctionType>(Result.getTypePtr());
1408}
1409
Reid Spencer5f016e22007-07-11 17:01:13 +00001410/// getComplexType - Return the uniqued reference to the type for a complex
1411/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001412QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001413 // Unique pointers, to guarantee there is only one pointer of a particular
1414 // structure.
1415 llvm::FoldingSetNodeID ID;
1416 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001417
Reid Spencer5f016e22007-07-11 17:01:13 +00001418 void *InsertPos = 0;
1419 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1420 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001421
Reid Spencer5f016e22007-07-11 17:01:13 +00001422 // If the pointee type isn't canonical, this won't be a canonical type either,
1423 // so fill in the canonical type field.
1424 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001425 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001426 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001427
Reid Spencer5f016e22007-07-11 17:01:13 +00001428 // Get the new insert position for the node we care about.
1429 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001430 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001431 }
John McCall6b304a02009-09-24 23:30:46 +00001432 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001433 Types.push_back(New);
1434 ComplexTypes.InsertNode(New, InsertPos);
1435 return QualType(New, 0);
1436}
1437
Reid Spencer5f016e22007-07-11 17:01:13 +00001438/// getPointerType - Return the uniqued reference to the type for a pointer to
1439/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001440QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001441 // Unique pointers, to guarantee there is only one pointer of a particular
1442 // structure.
1443 llvm::FoldingSetNodeID ID;
1444 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001445
Reid Spencer5f016e22007-07-11 17:01:13 +00001446 void *InsertPos = 0;
1447 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1448 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001449
Reid Spencer5f016e22007-07-11 17:01:13 +00001450 // If the pointee type isn't canonical, this won't be a canonical type either,
1451 // so fill in the canonical type field.
1452 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001453 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001454 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001455
Reid Spencer5f016e22007-07-11 17:01:13 +00001456 // Get the new insert position for the node we care about.
1457 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001458 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001459 }
John McCall6b304a02009-09-24 23:30:46 +00001460 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001461 Types.push_back(New);
1462 PointerTypes.InsertNode(New, InsertPos);
1463 return QualType(New, 0);
1464}
1465
Mike Stump1eb44332009-09-09 15:08:12 +00001466/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001467/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001468QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001469 assert(T->isFunctionType() && "block of function types only");
1470 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001471 // structure.
1472 llvm::FoldingSetNodeID ID;
1473 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001474
Steve Naroff5618bd42008-08-27 16:04:49 +00001475 void *InsertPos = 0;
1476 if (BlockPointerType *PT =
1477 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1478 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001479
1480 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001481 // type either so fill in the canonical type field.
1482 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001483 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001484 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001485
Steve Naroff5618bd42008-08-27 16:04:49 +00001486 // Get the new insert position for the node we care about.
1487 BlockPointerType *NewIP =
1488 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001489 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001490 }
John McCall6b304a02009-09-24 23:30:46 +00001491 BlockPointerType *New
1492 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001493 Types.push_back(New);
1494 BlockPointerTypes.InsertNode(New, InsertPos);
1495 return QualType(New, 0);
1496}
1497
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001498/// getLValueReferenceType - Return the uniqued reference to the type for an
1499/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001500QualType
1501ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00001502 assert(getCanonicalType(T) != OverloadTy &&
1503 "Unresolved overloaded function type");
1504
Reid Spencer5f016e22007-07-11 17:01:13 +00001505 // Unique pointers, to guarantee there is only one pointer of a particular
1506 // structure.
1507 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001508 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001509
1510 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001511 if (LValueReferenceType *RT =
1512 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001513 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001514
John McCall54e14c42009-10-22 22:37:11 +00001515 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1516
Reid Spencer5f016e22007-07-11 17:01:13 +00001517 // If the referencee type isn't canonical, this won't be a canonical type
1518 // either, so fill in the canonical type field.
1519 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001520 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1521 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1522 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001523
Reid Spencer5f016e22007-07-11 17:01:13 +00001524 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001525 LValueReferenceType *NewIP =
1526 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001527 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001528 }
1529
John McCall6b304a02009-09-24 23:30:46 +00001530 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001531 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1532 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001533 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001534 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001535
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001536 return QualType(New, 0);
1537}
1538
1539/// getRValueReferenceType - Return the uniqued reference to the type for an
1540/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001541QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001542 // Unique pointers, to guarantee there is only one pointer of a particular
1543 // structure.
1544 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001545 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001546
1547 void *InsertPos = 0;
1548 if (RValueReferenceType *RT =
1549 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1550 return QualType(RT, 0);
1551
John McCall54e14c42009-10-22 22:37:11 +00001552 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1553
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001554 // If the referencee type isn't canonical, this won't be a canonical type
1555 // either, so fill in the canonical type field.
1556 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001557 if (InnerRef || !T.isCanonical()) {
1558 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1559 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001560
1561 // Get the new insert position for the node we care about.
1562 RValueReferenceType *NewIP =
1563 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001564 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001565 }
1566
John McCall6b304a02009-09-24 23:30:46 +00001567 RValueReferenceType *New
1568 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001569 Types.push_back(New);
1570 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001571 return QualType(New, 0);
1572}
1573
Sebastian Redlf30208a2009-01-24 21:16:55 +00001574/// getMemberPointerType - Return the uniqued reference to the type for a
1575/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00001576QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001577 // Unique pointers, to guarantee there is only one pointer of a particular
1578 // structure.
1579 llvm::FoldingSetNodeID ID;
1580 MemberPointerType::Profile(ID, T, Cls);
1581
1582 void *InsertPos = 0;
1583 if (MemberPointerType *PT =
1584 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1585 return QualType(PT, 0);
1586
1587 // If the pointee or class type isn't canonical, this won't be a canonical
1588 // type either, so fill in the canonical type field.
1589 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001590 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001591 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1592
1593 // Get the new insert position for the node we care about.
1594 MemberPointerType *NewIP =
1595 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001596 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001597 }
John McCall6b304a02009-09-24 23:30:46 +00001598 MemberPointerType *New
1599 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001600 Types.push_back(New);
1601 MemberPointerTypes.InsertNode(New, InsertPos);
1602 return QualType(New, 0);
1603}
1604
Mike Stump1eb44332009-09-09 15:08:12 +00001605/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001606/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001607QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001608 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001609 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001610 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001611 assert((EltTy->isDependentType() ||
1612 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001613 "Constant array of VLAs is illegal!");
1614
Chris Lattner38aeec72009-05-13 04:12:56 +00001615 // Convert the array size into a canonical width matching the pointer size for
1616 // the target.
1617 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001618 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001619 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00001620
Reid Spencer5f016e22007-07-11 17:01:13 +00001621 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001622 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001623
Reid Spencer5f016e22007-07-11 17:01:13 +00001624 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001625 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001626 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001627 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001628
John McCall3b657512011-01-19 10:06:00 +00001629 // If the element type isn't canonical or has qualifiers, this won't
1630 // be a canonical type either, so fill in the canonical type field.
1631 QualType Canon;
1632 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1633 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1634 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001635 ASM, IndexTypeQuals);
John McCall3b657512011-01-19 10:06:00 +00001636 Canon = getQualifiedType(Canon, canonSplit.second);
1637
Reid Spencer5f016e22007-07-11 17:01:13 +00001638 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001639 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001640 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001641 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001642 }
Mike Stump1eb44332009-09-09 15:08:12 +00001643
John McCall6b304a02009-09-24 23:30:46 +00001644 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001645 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001646 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001647 Types.push_back(New);
1648 return QualType(New, 0);
1649}
1650
John McCallce889032011-01-18 08:40:38 +00001651/// getVariableArrayDecayedType - Turns the given type, which may be
1652/// variably-modified, into the corresponding type with all the known
1653/// sizes replaced with [*].
1654QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1655 // Vastly most common case.
1656 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001657
John McCallce889032011-01-18 08:40:38 +00001658 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001659
John McCallce889032011-01-18 08:40:38 +00001660 SplitQualType split = type.getSplitDesugaredType();
1661 const Type *ty = split.first;
1662 switch (ty->getTypeClass()) {
1663#define TYPE(Class, Base)
1664#define ABSTRACT_TYPE(Class, Base)
1665#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1666#include "clang/AST/TypeNodes.def"
1667 llvm_unreachable("didn't desugar past all non-canonical types?");
1668
1669 // These types should never be variably-modified.
1670 case Type::Builtin:
1671 case Type::Complex:
1672 case Type::Vector:
1673 case Type::ExtVector:
1674 case Type::DependentSizedExtVector:
1675 case Type::ObjCObject:
1676 case Type::ObjCInterface:
1677 case Type::ObjCObjectPointer:
1678 case Type::Record:
1679 case Type::Enum:
1680 case Type::UnresolvedUsing:
1681 case Type::TypeOfExpr:
1682 case Type::TypeOf:
1683 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00001684 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00001685 case Type::DependentName:
1686 case Type::InjectedClassName:
1687 case Type::TemplateSpecialization:
1688 case Type::DependentTemplateSpecialization:
1689 case Type::TemplateTypeParm:
1690 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00001691 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00001692 case Type::PackExpansion:
1693 llvm_unreachable("type should never be variably-modified");
1694
1695 // These types can be variably-modified but should never need to
1696 // further decay.
1697 case Type::FunctionNoProto:
1698 case Type::FunctionProto:
1699 case Type::BlockPointer:
1700 case Type::MemberPointer:
1701 return type;
1702
1703 // These types can be variably-modified. All these modifications
1704 // preserve structure except as noted by comments.
1705 // TODO: if we ever care about optimizing VLAs, there are no-op
1706 // optimizations available here.
1707 case Type::Pointer:
1708 result = getPointerType(getVariableArrayDecayedType(
1709 cast<PointerType>(ty)->getPointeeType()));
1710 break;
1711
1712 case Type::LValueReference: {
1713 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1714 result = getLValueReferenceType(
1715 getVariableArrayDecayedType(lv->getPointeeType()),
1716 lv->isSpelledAsLValue());
1717 break;
1718 }
1719
1720 case Type::RValueReference: {
1721 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1722 result = getRValueReferenceType(
1723 getVariableArrayDecayedType(lv->getPointeeType()));
1724 break;
1725 }
1726
Eli Friedmanb001de72011-10-06 23:00:33 +00001727 case Type::Atomic: {
1728 const AtomicType *at = cast<AtomicType>(ty);
1729 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1730 break;
1731 }
1732
John McCallce889032011-01-18 08:40:38 +00001733 case Type::ConstantArray: {
1734 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1735 result = getConstantArrayType(
1736 getVariableArrayDecayedType(cat->getElementType()),
1737 cat->getSize(),
1738 cat->getSizeModifier(),
1739 cat->getIndexTypeCVRQualifiers());
1740 break;
1741 }
1742
1743 case Type::DependentSizedArray: {
1744 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1745 result = getDependentSizedArrayType(
1746 getVariableArrayDecayedType(dat->getElementType()),
1747 dat->getSizeExpr(),
1748 dat->getSizeModifier(),
1749 dat->getIndexTypeCVRQualifiers(),
1750 dat->getBracketsRange());
1751 break;
1752 }
1753
1754 // Turn incomplete types into [*] types.
1755 case Type::IncompleteArray: {
1756 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1757 result = getVariableArrayType(
1758 getVariableArrayDecayedType(iat->getElementType()),
1759 /*size*/ 0,
1760 ArrayType::Normal,
1761 iat->getIndexTypeCVRQualifiers(),
1762 SourceRange());
1763 break;
1764 }
1765
1766 // Turn VLA types into [*] types.
1767 case Type::VariableArray: {
1768 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1769 result = getVariableArrayType(
1770 getVariableArrayDecayedType(vat->getElementType()),
1771 /*size*/ 0,
1772 ArrayType::Star,
1773 vat->getIndexTypeCVRQualifiers(),
1774 vat->getBracketsRange());
1775 break;
1776 }
1777 }
1778
1779 // Apply the top-level qualifiers from the original.
1780 return getQualifiedType(result, split.second);
1781}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001782
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001783/// getVariableArrayType - Returns a non-unique reference to the type for a
1784/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001785QualType ASTContext::getVariableArrayType(QualType EltTy,
1786 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001787 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001788 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00001789 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001790 // Since we don't unique expressions, it isn't possible to unique VLA's
1791 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00001792 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00001793
John McCall3b657512011-01-19 10:06:00 +00001794 // Be sure to pull qualifiers off the element type.
1795 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1796 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1797 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001798 IndexTypeQuals, Brackets);
John McCall3b657512011-01-19 10:06:00 +00001799 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor715e9c82010-05-23 16:10:32 +00001800 }
1801
John McCall6b304a02009-09-24 23:30:46 +00001802 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001803 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001804
1805 VariableArrayTypes.push_back(New);
1806 Types.push_back(New);
1807 return QualType(New, 0);
1808}
1809
Douglas Gregor898574e2008-12-05 23:32:09 +00001810/// getDependentSizedArrayType - Returns a non-unique reference to
1811/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001812/// type.
John McCall3b657512011-01-19 10:06:00 +00001813QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1814 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00001815 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001816 unsigned elementTypeQuals,
1817 SourceRange brackets) const {
1818 assert((!numElements || numElements->isTypeDependent() ||
1819 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001820 "Size must be type- or value-dependent!");
1821
John McCall3b657512011-01-19 10:06:00 +00001822 // Dependently-sized array types that do not have a specified number
1823 // of elements will have their sizes deduced from a dependent
1824 // initializer. We do no canonicalization here at all, which is okay
1825 // because they can't be used in most locations.
1826 if (!numElements) {
1827 DependentSizedArrayType *newType
1828 = new (*this, TypeAlignment)
1829 DependentSizedArrayType(*this, elementType, QualType(),
1830 numElements, ASM, elementTypeQuals,
1831 brackets);
1832 Types.push_back(newType);
1833 return QualType(newType, 0);
1834 }
1835
1836 // Otherwise, we actually build a new type every time, but we
1837 // also build a canonical type.
1838
1839 SplitQualType canonElementType = getCanonicalType(elementType).split();
1840
1841 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001842 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001843 DependentSizedArrayType::Profile(ID, *this,
1844 QualType(canonElementType.first, 0),
1845 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001846
John McCall3b657512011-01-19 10:06:00 +00001847 // Look for an existing type with these properties.
1848 DependentSizedArrayType *canonTy =
1849 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001850
John McCall3b657512011-01-19 10:06:00 +00001851 // If we don't have one, build one.
1852 if (!canonTy) {
1853 canonTy = new (*this, TypeAlignment)
1854 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1855 QualType(), numElements, ASM, elementTypeQuals,
1856 brackets);
1857 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1858 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001859 }
1860
John McCall3b657512011-01-19 10:06:00 +00001861 // Apply qualifiers from the element type to the array.
1862 QualType canon = getQualifiedType(QualType(canonTy,0),
1863 canonElementType.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001864
John McCall3b657512011-01-19 10:06:00 +00001865 // If we didn't need extra canonicalization for the element type,
1866 // then just use that as our result.
1867 if (QualType(canonElementType.first, 0) == elementType)
1868 return canon;
1869
1870 // Otherwise, we need to build a type which follows the spelling
1871 // of the element type.
1872 DependentSizedArrayType *sugaredType
1873 = new (*this, TypeAlignment)
1874 DependentSizedArrayType(*this, elementType, canon, numElements,
1875 ASM, elementTypeQuals, brackets);
1876 Types.push_back(sugaredType);
1877 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00001878}
1879
John McCall3b657512011-01-19 10:06:00 +00001880QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00001881 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001882 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001883 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001884 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001885
John McCall3b657512011-01-19 10:06:00 +00001886 void *insertPos = 0;
1887 if (IncompleteArrayType *iat =
1888 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1889 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001890
1891 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00001892 // either, so fill in the canonical type field. We also have to pull
1893 // qualifiers off the element type.
1894 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00001895
John McCall3b657512011-01-19 10:06:00 +00001896 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1897 SplitQualType canonSplit = getCanonicalType(elementType).split();
1898 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1899 ASM, elementTypeQuals);
1900 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001901
1902 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00001903 IncompleteArrayType *existing =
1904 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1905 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001906 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001907
John McCall3b657512011-01-19 10:06:00 +00001908 IncompleteArrayType *newType = new (*this, TypeAlignment)
1909 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001910
John McCall3b657512011-01-19 10:06:00 +00001911 IncompleteArrayTypes.InsertNode(newType, insertPos);
1912 Types.push_back(newType);
1913 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001914}
1915
Steve Naroff73322922007-07-18 18:00:27 +00001916/// getVectorType - Return the unique reference to a vector type of
1917/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001918QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00001919 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00001920 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001921
Reid Spencer5f016e22007-07-11 17:01:13 +00001922 // Check if we've already instantiated a vector of this type.
1923 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00001924 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00001925
Reid Spencer5f016e22007-07-11 17:01:13 +00001926 void *InsertPos = 0;
1927 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1928 return QualType(VTP, 0);
1929
1930 // If the element type isn't canonical, this won't be a canonical type either,
1931 // so fill in the canonical type field.
1932 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00001933 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00001934 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00001935
Reid Spencer5f016e22007-07-11 17:01:13 +00001936 // Get the new insert position for the node we care about.
1937 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001938 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001939 }
John McCall6b304a02009-09-24 23:30:46 +00001940 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00001941 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001942 VectorTypes.InsertNode(New, InsertPos);
1943 Types.push_back(New);
1944 return QualType(New, 0);
1945}
1946
Nate Begeman213541a2008-04-18 23:10:10 +00001947/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001948/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001949QualType
1950ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00001951 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00001952
Steve Naroff73322922007-07-18 18:00:27 +00001953 // Check if we've already instantiated a vector of this type.
1954 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001955 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001956 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00001957 void *InsertPos = 0;
1958 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1959 return QualType(VTP, 0);
1960
1961 // If the element type isn't canonical, this won't be a canonical type either,
1962 // so fill in the canonical type field.
1963 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001964 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001965 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001966
Steve Naroff73322922007-07-18 18:00:27 +00001967 // Get the new insert position for the node we care about.
1968 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001969 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001970 }
John McCall6b304a02009-09-24 23:30:46 +00001971 ExtVectorType *New = new (*this, TypeAlignment)
1972 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001973 VectorTypes.InsertNode(New, InsertPos);
1974 Types.push_back(New);
1975 return QualType(New, 0);
1976}
1977
Jay Foad4ba2a172011-01-12 09:06:06 +00001978QualType
1979ASTContext::getDependentSizedExtVectorType(QualType vecType,
1980 Expr *SizeExpr,
1981 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001982 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001983 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001984 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001985
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001986 void *InsertPos = 0;
1987 DependentSizedExtVectorType *Canon
1988 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1989 DependentSizedExtVectorType *New;
1990 if (Canon) {
1991 // We already have a canonical version of this array type; use it as
1992 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001993 New = new (*this, TypeAlignment)
1994 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1995 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001996 } else {
1997 QualType CanonVecTy = getCanonicalType(vecType);
1998 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001999 New = new (*this, TypeAlignment)
2000 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2001 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002002
2003 DependentSizedExtVectorType *CanonCheck
2004 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2005 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2006 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002007 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2008 } else {
2009 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2010 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002011 New = new (*this, TypeAlignment)
2012 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002013 }
2014 }
Mike Stump1eb44332009-09-09 15:08:12 +00002015
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002016 Types.push_back(New);
2017 return QualType(New, 0);
2018}
2019
Douglas Gregor72564e72009-02-26 23:50:07 +00002020/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002021///
Jay Foad4ba2a172011-01-12 09:06:06 +00002022QualType
2023ASTContext::getFunctionNoProtoType(QualType ResultTy,
2024 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002025 const CallingConv DefaultCC = Info.getCC();
2026 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2027 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002028 // Unique functions, to guarantee there is only one function of a particular
2029 // structure.
2030 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002031 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002032
Reid Spencer5f016e22007-07-11 17:01:13 +00002033 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002034 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002035 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002036 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002037
Reid Spencer5f016e22007-07-11 17:01:13 +00002038 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002039 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002040 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002041 Canonical =
2042 getFunctionNoProtoType(getCanonicalType(ResultTy),
2043 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002044
Reid Spencer5f016e22007-07-11 17:01:13 +00002045 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002046 FunctionNoProtoType *NewIP =
2047 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002048 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002049 }
Mike Stump1eb44332009-09-09 15:08:12 +00002050
Roman Divackycfe9af22011-03-01 17:40:53 +00002051 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002052 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002053 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002054 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002055 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002056 return QualType(New, 0);
2057}
2058
2059/// getFunctionType - Return a normal function type with a typed argument
2060/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002061QualType
2062ASTContext::getFunctionType(QualType ResultTy,
2063 const QualType *ArgArray, unsigned NumArgs,
2064 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002065 // Unique functions, to guarantee there is only one function of a particular
2066 // structure.
2067 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002068 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002069
2070 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002071 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002072 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002073 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002074
2075 // Determine whether the type being created is already canonical or not.
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002076 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00002077 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002078 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002079 isCanonical = false;
2080
Roman Divackycfe9af22011-03-01 17:40:53 +00002081 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2082 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2083 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002084
Reid Spencer5f016e22007-07-11 17:01:13 +00002085 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002086 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002087 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002088 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002089 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002090 CanonicalArgs.reserve(NumArgs);
2091 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002092 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002093
John McCalle23cf432010-12-14 08:05:40 +00002094 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002095 CanonicalEPI.ExceptionSpecType = EST_None;
2096 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002097 CanonicalEPI.ExtInfo
2098 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2099
Chris Lattnerf52ab252008-04-06 22:59:24 +00002100 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00002101 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002102 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002103
Reid Spencer5f016e22007-07-11 17:01:13 +00002104 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002105 FunctionProtoType *NewIP =
2106 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002107 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002108 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002109
John McCallf85e1932011-06-15 23:02:42 +00002110 // FunctionProtoType objects are allocated with extra bytes after
2111 // them for three variable size arrays at the end:
2112 // - parameter types
2113 // - exception types
2114 // - consumed-arguments flags
2115 // Instead of the exception types, there could be a noexcept
2116 // expression.
John McCalle23cf432010-12-14 08:05:40 +00002117 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002118 NumArgs * sizeof(QualType);
2119 if (EPI.ExceptionSpecType == EST_Dynamic)
2120 Size += EPI.NumExceptions * sizeof(QualType);
2121 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002122 Size += sizeof(Expr*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002123 }
John McCallf85e1932011-06-15 23:02:42 +00002124 if (EPI.ConsumedArguments)
2125 Size += NumArgs * sizeof(bool);
2126
John McCalle23cf432010-12-14 08:05:40 +00002127 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002128 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2129 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002130 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002131 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002132 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002133 return QualType(FTP, 0);
2134}
2135
John McCall3cb0ebd2010-03-10 03:28:59 +00002136#ifndef NDEBUG
2137static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2138 if (!isa<CXXRecordDecl>(D)) return false;
2139 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2140 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2141 return true;
2142 if (RD->getDescribedClassTemplate() &&
2143 !isa<ClassTemplateSpecializationDecl>(RD))
2144 return true;
2145 return false;
2146}
2147#endif
2148
2149/// getInjectedClassNameType - Return the unique reference to the
2150/// injected class name type for the specified templated declaration.
2151QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002152 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002153 assert(NeedsInjectedClassNameType(Decl));
2154 if (Decl->TypeForDecl) {
2155 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00002156 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002157 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2158 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2159 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2160 } else {
John McCallf4c73712011-01-19 06:33:43 +00002161 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002162 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002163 Decl->TypeForDecl = newType;
2164 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002165 }
2166 return QualType(Decl->TypeForDecl, 0);
2167}
2168
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002169/// getTypeDeclType - Return the unique reference to the type for the
2170/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002171QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002172 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002173 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002174
Richard Smith162e1c12011-04-15 14:24:37 +00002175 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002176 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002177
John McCallbecb8d52010-03-10 06:48:02 +00002178 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2179 "Template type parameter types are always available.");
2180
John McCall19c85762010-02-16 03:57:14 +00002181 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002182 assert(!Record->getPreviousDeclaration() &&
2183 "struct/union has previous declaration");
2184 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002185 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002186 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002187 assert(!Enum->getPreviousDeclaration() &&
2188 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002189 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002190 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002191 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002192 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2193 Decl->TypeForDecl = newType;
2194 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002195 } else
John McCallbecb8d52010-03-10 06:48:02 +00002196 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002197
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002198 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002199}
2200
Reid Spencer5f016e22007-07-11 17:01:13 +00002201/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002202/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002203QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002204ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2205 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002206 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002207
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002208 if (Canonical.isNull())
2209 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002210 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002211 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002212 Decl->TypeForDecl = newType;
2213 Types.push_back(newType);
2214 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002215}
2216
Jay Foad4ba2a172011-01-12 09:06:06 +00002217QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002218 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2219
2220 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2221 if (PrevDecl->TypeForDecl)
2222 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2223
John McCallf4c73712011-01-19 06:33:43 +00002224 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2225 Decl->TypeForDecl = newType;
2226 Types.push_back(newType);
2227 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002228}
2229
Jay Foad4ba2a172011-01-12 09:06:06 +00002230QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002231 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2232
2233 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2234 if (PrevDecl->TypeForDecl)
2235 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2236
John McCallf4c73712011-01-19 06:33:43 +00002237 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2238 Decl->TypeForDecl = newType;
2239 Types.push_back(newType);
2240 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002241}
2242
John McCall9d156a72011-01-06 01:58:22 +00002243QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2244 QualType modifiedType,
2245 QualType equivalentType) {
2246 llvm::FoldingSetNodeID id;
2247 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2248
2249 void *insertPos = 0;
2250 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2251 if (type) return QualType(type, 0);
2252
2253 QualType canon = getCanonicalType(equivalentType);
2254 type = new (*this, TypeAlignment)
2255 AttributedType(canon, attrKind, modifiedType, equivalentType);
2256
2257 Types.push_back(type);
2258 AttributedTypes.InsertNode(type, insertPos);
2259
2260 return QualType(type, 0);
2261}
2262
2263
John McCall49a832b2009-10-18 09:09:24 +00002264/// \brief Retrieve a substitution-result type.
2265QualType
2266ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002267 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002268 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002269 && "replacement types must always be canonical");
2270
2271 llvm::FoldingSetNodeID ID;
2272 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2273 void *InsertPos = 0;
2274 SubstTemplateTypeParmType *SubstParm
2275 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2276
2277 if (!SubstParm) {
2278 SubstParm = new (*this, TypeAlignment)
2279 SubstTemplateTypeParmType(Parm, Replacement);
2280 Types.push_back(SubstParm);
2281 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2282 }
2283
2284 return QualType(SubstParm, 0);
2285}
2286
Douglas Gregorc3069d62011-01-14 02:55:32 +00002287/// \brief Retrieve a
2288QualType ASTContext::getSubstTemplateTypeParmPackType(
2289 const TemplateTypeParmType *Parm,
2290 const TemplateArgument &ArgPack) {
2291#ifndef NDEBUG
2292 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2293 PEnd = ArgPack.pack_end();
2294 P != PEnd; ++P) {
2295 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2296 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2297 }
2298#endif
2299
2300 llvm::FoldingSetNodeID ID;
2301 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2302 void *InsertPos = 0;
2303 if (SubstTemplateTypeParmPackType *SubstParm
2304 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2305 return QualType(SubstParm, 0);
2306
2307 QualType Canon;
2308 if (!Parm->isCanonicalUnqualified()) {
2309 Canon = getCanonicalType(QualType(Parm, 0));
2310 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2311 ArgPack);
2312 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2313 }
2314
2315 SubstTemplateTypeParmPackType *SubstParm
2316 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2317 ArgPack);
2318 Types.push_back(SubstParm);
2319 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2320 return QualType(SubstParm, 0);
2321}
2322
Douglas Gregorfab9d672009-02-05 23:33:38 +00002323/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002324/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002325/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002326QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002327 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002328 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002329 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002330 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002331 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002332 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002333 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2334
2335 if (TypeParm)
2336 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002337
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002338 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002339 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002340 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002341
2342 TemplateTypeParmType *TypeCheck
2343 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2344 assert(!TypeCheck && "Template type parameter canonical type broken");
2345 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002346 } else
John McCall6b304a02009-09-24 23:30:46 +00002347 TypeParm = new (*this, TypeAlignment)
2348 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002349
2350 Types.push_back(TypeParm);
2351 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2352
2353 return QualType(TypeParm, 0);
2354}
2355
John McCall3cb0ebd2010-03-10 03:28:59 +00002356TypeSourceInfo *
2357ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2358 SourceLocation NameLoc,
2359 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002360 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002361 assert(!Name.getAsDependentTemplateName() &&
2362 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002363 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002364
2365 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2366 TemplateSpecializationTypeLoc TL
2367 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2368 TL.setTemplateNameLoc(NameLoc);
2369 TL.setLAngleLoc(Args.getLAngleLoc());
2370 TL.setRAngleLoc(Args.getRAngleLoc());
2371 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2372 TL.setArgLocInfo(i, Args[i].getLocInfo());
2373 return DI;
2374}
2375
Mike Stump1eb44332009-09-09 15:08:12 +00002376QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002377ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002378 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002379 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002380 assert(!Template.getAsDependentTemplateName() &&
2381 "No dependent template names here!");
2382
John McCalld5532b62009-11-23 01:53:49 +00002383 unsigned NumArgs = Args.size();
2384
Chris Lattner5f9e2722011-07-23 10:55:15 +00002385 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002386 ArgVec.reserve(NumArgs);
2387 for (unsigned i = 0; i != NumArgs; ++i)
2388 ArgVec.push_back(Args[i].getArgument());
2389
John McCall31f17ec2010-04-27 00:57:59 +00002390 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002391 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002392}
2393
2394QualType
2395ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002396 const TemplateArgument *Args,
2397 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002398 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002399 assert(!Template.getAsDependentTemplateName() &&
2400 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002401 // Look through qualified template names.
2402 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2403 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002404
Richard Smith3e4c6c42011-05-05 21:57:07 +00002405 bool isTypeAlias =
2406 Template.getAsTemplateDecl() &&
2407 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2408
2409 QualType CanonType;
2410 if (!Underlying.isNull())
2411 CanonType = getCanonicalType(Underlying);
2412 else {
2413 assert(!isTypeAlias &&
2414 "Underlying type for template alias must be computed by caller");
2415 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2416 NumArgs);
2417 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002418
Douglas Gregor1275ae02009-07-28 23:00:59 +00002419 // Allocate the (non-canonical) template specialization type, but don't
2420 // try to unique it: these types typically have location information that
2421 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002422 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2423 sizeof(TemplateArgument) * NumArgs +
2424 (isTypeAlias ? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00002425 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002426 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00002427 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00002428 Args, NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002429 CanonType,
2430 isTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00002431
Douglas Gregor55f6b142009-02-09 18:46:07 +00002432 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002433 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002434}
2435
Mike Stump1eb44332009-09-09 15:08:12 +00002436QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002437ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2438 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002439 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002440 assert(!Template.getAsDependentTemplateName() &&
2441 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002442 assert((!Template.getAsTemplateDecl() ||
2443 !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2444 "Underlying type for template alias must be computed by caller");
2445
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002446 // Look through qualified template names.
2447 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2448 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002449
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002450 // Build the canonical template specialization type.
2451 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002452 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002453 CanonArgs.reserve(NumArgs);
2454 for (unsigned I = 0; I != NumArgs; ++I)
2455 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2456
2457 // Determine whether this canonical template specialization type already
2458 // exists.
2459 llvm::FoldingSetNodeID ID;
2460 TemplateSpecializationType::Profile(ID, CanonTemplate,
2461 CanonArgs.data(), NumArgs, *this);
2462
2463 void *InsertPos = 0;
2464 TemplateSpecializationType *Spec
2465 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2466
2467 if (!Spec) {
2468 // Allocate a new canonical template specialization type.
2469 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2470 sizeof(TemplateArgument) * NumArgs),
2471 TypeAlignment);
2472 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2473 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002474 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002475 Types.push_back(Spec);
2476 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2477 }
2478
2479 assert(Spec->isDependentType() &&
2480 "Non-dependent template-id type must have a canonical type");
2481 return QualType(Spec, 0);
2482}
2483
2484QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002485ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2486 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002487 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002488 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002489 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002490
2491 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002492 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002493 if (T)
2494 return QualType(T, 0);
2495
Douglas Gregor789b1f62010-02-04 18:10:26 +00002496 QualType Canon = NamedType;
2497 if (!Canon.isCanonical()) {
2498 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002499 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2500 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002501 (void)CheckT;
2502 }
2503
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002504 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002505 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002506 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002507 return QualType(T, 0);
2508}
2509
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002510QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002511ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002512 llvm::FoldingSetNodeID ID;
2513 ParenType::Profile(ID, InnerType);
2514
2515 void *InsertPos = 0;
2516 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2517 if (T)
2518 return QualType(T, 0);
2519
2520 QualType Canon = InnerType;
2521 if (!Canon.isCanonical()) {
2522 Canon = getCanonicalType(InnerType);
2523 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2524 assert(!CheckT && "Paren canonical type broken");
2525 (void)CheckT;
2526 }
2527
2528 T = new (*this) ParenType(InnerType, Canon);
2529 Types.push_back(T);
2530 ParenTypes.InsertNode(T, InsertPos);
2531 return QualType(T, 0);
2532}
2533
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002534QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2535 NestedNameSpecifier *NNS,
2536 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002537 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002538 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2539
2540 if (Canon.isNull()) {
2541 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002542 ElaboratedTypeKeyword CanonKeyword = Keyword;
2543 if (Keyword == ETK_None)
2544 CanonKeyword = ETK_Typename;
2545
2546 if (CanonNNS != NNS || CanonKeyword != Keyword)
2547 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002548 }
2549
2550 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002551 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002552
2553 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002554 DependentNameType *T
2555 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002556 if (T)
2557 return QualType(T, 0);
2558
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002559 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002560 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002561 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002562 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002563}
2564
Mike Stump1eb44332009-09-09 15:08:12 +00002565QualType
John McCall33500952010-06-11 00:33:02 +00002566ASTContext::getDependentTemplateSpecializationType(
2567 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002568 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002569 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002570 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00002571 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00002572 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00002573 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2574 ArgCopy.push_back(Args[I].getArgument());
2575 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2576 ArgCopy.size(),
2577 ArgCopy.data());
2578}
2579
2580QualType
2581ASTContext::getDependentTemplateSpecializationType(
2582 ElaboratedTypeKeyword Keyword,
2583 NestedNameSpecifier *NNS,
2584 const IdentifierInfo *Name,
2585 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002586 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00002587 assert((!NNS || NNS->isDependent()) &&
2588 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00002589
Douglas Gregor789b1f62010-02-04 18:10:26 +00002590 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002591 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2592 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002593
2594 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002595 DependentTemplateSpecializationType *T
2596 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002597 if (T)
2598 return QualType(T, 0);
2599
John McCall33500952010-06-11 00:33:02 +00002600 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002601
John McCall33500952010-06-11 00:33:02 +00002602 ElaboratedTypeKeyword CanonKeyword = Keyword;
2603 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2604
2605 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002606 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00002607 for (unsigned I = 0; I != NumArgs; ++I) {
2608 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2609 if (!CanonArgs[I].structurallyEquals(Args[I]))
2610 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002611 }
2612
John McCall33500952010-06-11 00:33:02 +00002613 QualType Canon;
2614 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2615 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2616 Name, NumArgs,
2617 CanonArgs.data());
2618
2619 // Find the insert position again.
2620 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2621 }
2622
2623 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2624 sizeof(TemplateArgument) * NumArgs),
2625 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002626 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002627 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002628 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002629 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002630 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002631}
2632
Douglas Gregorcded4f62011-01-14 17:04:44 +00002633QualType ASTContext::getPackExpansionType(QualType Pattern,
2634 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00002635 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002636 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002637
2638 assert(Pattern->containsUnexpandedParameterPack() &&
2639 "Pack expansions must expand one or more parameter packs");
2640 void *InsertPos = 0;
2641 PackExpansionType *T
2642 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2643 if (T)
2644 return QualType(T, 0);
2645
2646 QualType Canon;
2647 if (!Pattern.isCanonical()) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002648 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002649
2650 // Find the insert position again.
2651 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2652 }
2653
Douglas Gregorcded4f62011-01-14 17:04:44 +00002654 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002655 Types.push_back(T);
2656 PackExpansionTypes.InsertNode(T, InsertPos);
2657 return QualType(T, 0);
2658}
2659
Chris Lattner88cb27a2008-04-07 04:56:42 +00002660/// CmpProtocolNames - Comparison predicate for sorting protocols
2661/// alphabetically.
2662static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2663 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002664 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002665}
2666
John McCallc12c5bb2010-05-15 11:32:37 +00002667static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002668 unsigned NumProtocols) {
2669 if (NumProtocols == 0) return true;
2670
2671 for (unsigned i = 1; i != NumProtocols; ++i)
2672 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2673 return false;
2674 return true;
2675}
2676
2677static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002678 unsigned &NumProtocols) {
2679 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002680
Chris Lattner88cb27a2008-04-07 04:56:42 +00002681 // Sort protocols, keyed by name.
2682 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2683
2684 // Remove duplicates.
2685 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2686 NumProtocols = ProtocolsEnd-Protocols;
2687}
2688
John McCallc12c5bb2010-05-15 11:32:37 +00002689QualType ASTContext::getObjCObjectType(QualType BaseType,
2690 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00002691 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002692 // If the base type is an interface and there aren't any protocols
2693 // to add, then the interface type will do just fine.
2694 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2695 return BaseType;
2696
2697 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002698 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002699 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002700 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002701 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2702 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002703
John McCallc12c5bb2010-05-15 11:32:37 +00002704 // Build the canonical type, which has the canonical base type and
2705 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002706 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002707 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2708 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2709 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002710 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00002711 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002712 unsigned UniqueCount = NumProtocols;
2713
John McCall54e14c42009-10-22 22:37:11 +00002714 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002715 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2716 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002717 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002718 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2719 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002720 }
2721
2722 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002723 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2724 }
2725
2726 unsigned Size = sizeof(ObjCObjectTypeImpl);
2727 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2728 void *Mem = Allocate(Size, TypeAlignment);
2729 ObjCObjectTypeImpl *T =
2730 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2731
2732 Types.push_back(T);
2733 ObjCObjectTypes.InsertNode(T, InsertPos);
2734 return QualType(T, 0);
2735}
2736
2737/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2738/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002739QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002740 llvm::FoldingSetNodeID ID;
2741 ObjCObjectPointerType::Profile(ID, ObjectT);
2742
2743 void *InsertPos = 0;
2744 if (ObjCObjectPointerType *QT =
2745 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2746 return QualType(QT, 0);
2747
2748 // Find the canonical object type.
2749 QualType Canonical;
2750 if (!ObjectT.isCanonical()) {
2751 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2752
2753 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002754 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2755 }
2756
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002757 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002758 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2759 ObjCObjectPointerType *QType =
2760 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002761
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002762 Types.push_back(QType);
2763 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002764 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002765}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002766
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002767/// getObjCInterfaceType - Return the unique reference to the type for the
2768/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad4ba2a172011-01-12 09:06:06 +00002769QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002770 if (Decl->TypeForDecl)
2771 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002772
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002773 // FIXME: redeclarations?
2774 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2775 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2776 Decl->TypeForDecl = T;
2777 Types.push_back(T);
2778 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002779}
2780
Douglas Gregor72564e72009-02-26 23:50:07 +00002781/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2782/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002783/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002784/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002785/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002786QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002787 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002788 if (tofExpr->isTypeDependent()) {
2789 llvm::FoldingSetNodeID ID;
2790 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002791
Douglas Gregorb1975722009-07-30 23:18:24 +00002792 void *InsertPos = 0;
2793 DependentTypeOfExprType *Canon
2794 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2795 if (Canon) {
2796 // We already have a "canonical" version of an identical, dependent
2797 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002798 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002799 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00002800 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00002801 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002802 Canon
2803 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002804 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2805 toe = Canon;
2806 }
2807 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002808 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002809 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002810 }
Steve Naroff9752f252007-08-01 18:02:17 +00002811 Types.push_back(toe);
2812 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002813}
2814
Steve Naroff9752f252007-08-01 18:02:17 +00002815/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2816/// TypeOfType AST's. The only motivation to unique these nodes would be
2817/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002818/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002819/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002820QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002821 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002822 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002823 Types.push_back(tot);
2824 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002825}
2826
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002827/// getDecltypeForExpr - Given an expr, will return the decltype for that
2828/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad4ba2a172011-01-12 09:06:06 +00002829static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002830 if (e->isTypeDependent())
2831 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002832
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002833 // If e is an id expression or a class member access, decltype(e) is defined
2834 // as the type of the entity named by e.
2835 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2836 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2837 return VD->getType();
2838 }
2839 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2840 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2841 return FD->getType();
2842 }
2843 // If e is a function call or an invocation of an overloaded operator,
2844 // (parentheses around e are ignored), decltype(e) is defined as the
2845 // return type of that function.
2846 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2847 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002848
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002849 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002850
2851 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002852 // defined as T&, otherwise decltype(e) is defined as T.
John McCall7eb0a9e2010-11-24 05:12:34 +00002853 if (e->isLValue())
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002854 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002855
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002856 return T;
2857}
2858
Anders Carlsson395b4752009-06-24 19:06:50 +00002859/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2860/// DecltypeType AST's. The only motivation to unique these nodes would be
2861/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002862/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002863/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002864QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002865 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00002866
2867 // C++0x [temp.type]p2:
2868 // If an expression e involves a template parameter, decltype(e) denotes a
2869 // unique dependent type. Two such decltype-specifiers refer to the same
2870 // type only if their expressions are equivalent (14.5.6.1).
2871 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002872 llvm::FoldingSetNodeID ID;
2873 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002874
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002875 void *InsertPos = 0;
2876 DependentDecltypeType *Canon
2877 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2878 if (Canon) {
2879 // We already have a "canonical" version of an equivalent, dependent
2880 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002881 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002882 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00002883 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002884 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002885 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002886 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2887 dt = Canon;
2888 }
2889 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002890 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002891 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002892 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002893 Types.push_back(dt);
2894 return QualType(dt, 0);
2895}
2896
Sean Huntca63c202011-05-24 22:41:36 +00002897/// getUnaryTransformationType - We don't unique these, since the memory
2898/// savings are minimal and these are rare.
2899QualType ASTContext::getUnaryTransformType(QualType BaseType,
2900 QualType UnderlyingType,
2901 UnaryTransformType::UTTKind Kind)
2902 const {
2903 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00002904 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2905 Kind,
2906 UnderlyingType->isDependentType() ?
2907 QualType() : UnderlyingType);
Sean Huntca63c202011-05-24 22:41:36 +00002908 Types.push_back(Ty);
2909 return QualType(Ty, 0);
2910}
2911
Richard Smith483b9f32011-02-21 20:05:19 +00002912/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00002913QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00002914 void *InsertPos = 0;
2915 if (!DeducedType.isNull()) {
2916 // Look in the folding set for an existing type.
2917 llvm::FoldingSetNodeID ID;
2918 AutoType::Profile(ID, DeducedType);
2919 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2920 return QualType(AT, 0);
2921 }
2922
2923 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2924 Types.push_back(AT);
2925 if (InsertPos)
2926 AutoTypes.InsertNode(AT, InsertPos);
2927 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00002928}
2929
Eli Friedmanb001de72011-10-06 23:00:33 +00002930/// getAtomicType - Return the uniqued reference to the atomic type for
2931/// the given value type.
2932QualType ASTContext::getAtomicType(QualType T) const {
2933 // Unique pointers, to guarantee there is only one pointer of a particular
2934 // structure.
2935 llvm::FoldingSetNodeID ID;
2936 AtomicType::Profile(ID, T);
2937
2938 void *InsertPos = 0;
2939 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
2940 return QualType(AT, 0);
2941
2942 // If the atomic value type isn't canonical, this won't be a canonical type
2943 // either, so fill in the canonical type field.
2944 QualType Canonical;
2945 if (!T.isCanonical()) {
2946 Canonical = getAtomicType(getCanonicalType(T));
2947
2948 // Get the new insert position for the node we care about.
2949 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
2950 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2951 }
2952 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
2953 Types.push_back(New);
2954 AtomicTypes.InsertNode(New, InsertPos);
2955 return QualType(New, 0);
2956}
2957
Richard Smithad762fc2011-04-14 22:09:26 +00002958/// getAutoDeductType - Get type pattern for deducing against 'auto'.
2959QualType ASTContext::getAutoDeductType() const {
2960 if (AutoDeductTy.isNull())
2961 AutoDeductTy = getAutoType(QualType());
2962 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
2963 return AutoDeductTy;
2964}
2965
2966/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
2967QualType ASTContext::getAutoRRefDeductType() const {
2968 if (AutoRRefDeductTy.isNull())
2969 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
2970 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
2971 return AutoRRefDeductTy;
2972}
2973
Reid Spencer5f016e22007-07-11 17:01:13 +00002974/// getTagDeclType - Return the unique reference to the type for the
2975/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00002976QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00002977 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002978 // FIXME: What is the design on getTagDeclType when it requires casting
2979 // away const? mutable?
2980 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002981}
2982
Mike Stump1eb44332009-09-09 15:08:12 +00002983/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2984/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2985/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002986CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002987 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002988}
2989
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002990/// getSignedWCharType - Return the type of "signed wchar_t".
2991/// Used when in C++, as a GCC extension.
2992QualType ASTContext::getSignedWCharType() const {
2993 // FIXME: derive from "Target" ?
2994 return WCharTy;
2995}
2996
2997/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2998/// Used when in C++, as a GCC extension.
2999QualType ASTContext::getUnsignedWCharType() const {
3000 // FIXME: derive from "Target" ?
3001 return UnsignedIntTy;
3002}
3003
Chris Lattner8b9023b2007-07-13 03:05:23 +00003004/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
3005/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3006QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003007 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003008}
3009
Chris Lattnere6327742008-04-02 05:18:44 +00003010//===----------------------------------------------------------------------===//
3011// Type Operators
3012//===----------------------------------------------------------------------===//
3013
Jay Foad4ba2a172011-01-12 09:06:06 +00003014CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003015 // Push qualifiers into arrays, and then discard any remaining
3016 // qualifiers.
3017 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003018 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003019 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003020 QualType Result;
3021 if (isa<ArrayType>(Ty)) {
3022 Result = getArrayDecayedType(QualType(Ty,0));
3023 } else if (isa<FunctionType>(Ty)) {
3024 Result = getPointerType(QualType(Ty, 0));
3025 } else {
3026 Result = QualType(Ty, 0);
3027 }
3028
3029 return CanQualType::CreateUnsafe(Result);
3030}
3031
John McCall62c28c82011-01-18 07:41:22 +00003032QualType ASTContext::getUnqualifiedArrayType(QualType type,
3033 Qualifiers &quals) {
3034 SplitQualType splitType = type.getSplitUnqualifiedType();
3035
3036 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3037 // the unqualified desugared type and then drops it on the floor.
3038 // We then have to strip that sugar back off with
3039 // getUnqualifiedDesugaredType(), which is silly.
3040 const ArrayType *AT =
3041 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
3042
3043 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003044 if (!AT) {
John McCall62c28c82011-01-18 07:41:22 +00003045 quals = splitType.second;
3046 return QualType(splitType.first, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003047 }
3048
John McCall62c28c82011-01-18 07:41:22 +00003049 // Otherwise, recurse on the array's element type.
3050 QualType elementType = AT->getElementType();
3051 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3052
3053 // If that didn't change the element type, AT has no qualifiers, so we
3054 // can just use the results in splitType.
3055 if (elementType == unqualElementType) {
3056 assert(quals.empty()); // from the recursive call
3057 quals = splitType.second;
3058 return QualType(splitType.first, 0);
3059 }
3060
3061 // Otherwise, add in the qualifiers from the outermost type, then
3062 // build the type back up.
3063 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003064
Douglas Gregor9dadd942010-05-17 18:45:21 +00003065 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003066 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003067 CAT->getSizeModifier(), 0);
3068 }
3069
Douglas Gregor9dadd942010-05-17 18:45:21 +00003070 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003071 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003072 }
3073
Douglas Gregor9dadd942010-05-17 18:45:21 +00003074 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003075 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003076 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003077 VAT->getSizeModifier(),
3078 VAT->getIndexTypeCVRQualifiers(),
3079 VAT->getBracketsRange());
3080 }
3081
3082 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003083 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003084 DSAT->getSizeModifier(), 0,
3085 SourceRange());
3086}
3087
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003088/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3089/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3090/// they point to and return true. If T1 and T2 aren't pointer types
3091/// or pointer-to-member types, or if they are not similar at this
3092/// level, returns false and leaves T1 and T2 unchanged. Top-level
3093/// qualifiers on T1 and T2 are ignored. This function will typically
3094/// be called in a loop that successively "unwraps" pointer and
3095/// pointer-to-member types to compare them at each level.
3096bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3097 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3098 *T2PtrType = T2->getAs<PointerType>();
3099 if (T1PtrType && T2PtrType) {
3100 T1 = T1PtrType->getPointeeType();
3101 T2 = T2PtrType->getPointeeType();
3102 return true;
3103 }
3104
3105 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3106 *T2MPType = T2->getAs<MemberPointerType>();
3107 if (T1MPType && T2MPType &&
3108 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3109 QualType(T2MPType->getClass(), 0))) {
3110 T1 = T1MPType->getPointeeType();
3111 T2 = T2MPType->getPointeeType();
3112 return true;
3113 }
3114
3115 if (getLangOptions().ObjC1) {
3116 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3117 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3118 if (T1OPType && T2OPType) {
3119 T1 = T1OPType->getPointeeType();
3120 T2 = T2OPType->getPointeeType();
3121 return true;
3122 }
3123 }
3124
3125 // FIXME: Block pointers, too?
3126
3127 return false;
3128}
3129
Jay Foad4ba2a172011-01-12 09:06:06 +00003130DeclarationNameInfo
3131ASTContext::getNameForTemplate(TemplateName Name,
3132 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003133 switch (Name.getKind()) {
3134 case TemplateName::QualifiedTemplate:
3135 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003136 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003137 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3138 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003139
John McCall14606042011-06-30 08:33:18 +00003140 case TemplateName::OverloadedTemplate: {
3141 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3142 // DNInfo work in progress: CHECKME: what about DNLoc?
3143 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3144 }
3145
3146 case TemplateName::DependentTemplate: {
3147 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003148 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003149 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003150 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3151 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003152 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003153 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3154 // DNInfo work in progress: FIXME: source locations?
3155 DeclarationNameLoc DNLoc;
3156 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3157 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3158 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003159 }
3160 }
3161
John McCall14606042011-06-30 08:33:18 +00003162 case TemplateName::SubstTemplateTemplateParm: {
3163 SubstTemplateTemplateParmStorage *subst
3164 = Name.getAsSubstTemplateTemplateParm();
3165 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3166 NameLoc);
3167 }
3168
3169 case TemplateName::SubstTemplateTemplateParmPack: {
3170 SubstTemplateTemplateParmPackStorage *subst
3171 = Name.getAsSubstTemplateTemplateParmPack();
3172 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3173 NameLoc);
3174 }
3175 }
3176
3177 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003178}
3179
Jay Foad4ba2a172011-01-12 09:06:06 +00003180TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003181 switch (Name.getKind()) {
3182 case TemplateName::QualifiedTemplate:
3183 case TemplateName::Template: {
3184 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003185 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003186 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003187 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3188
3189 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003190 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003191 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003192
John McCall14606042011-06-30 08:33:18 +00003193 case TemplateName::OverloadedTemplate:
3194 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003195
John McCall14606042011-06-30 08:33:18 +00003196 case TemplateName::DependentTemplate: {
3197 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3198 assert(DTN && "Non-dependent template names must refer to template decls.");
3199 return DTN->CanonicalTemplateName;
3200 }
3201
3202 case TemplateName::SubstTemplateTemplateParm: {
3203 SubstTemplateTemplateParmStorage *subst
3204 = Name.getAsSubstTemplateTemplateParm();
3205 return getCanonicalTemplateName(subst->getReplacement());
3206 }
3207
3208 case TemplateName::SubstTemplateTemplateParmPack: {
3209 SubstTemplateTemplateParmPackStorage *subst
3210 = Name.getAsSubstTemplateTemplateParmPack();
3211 TemplateTemplateParmDecl *canonParameter
3212 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3213 TemplateArgument canonArgPack
3214 = getCanonicalTemplateArgument(subst->getArgumentPack());
3215 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3216 }
3217 }
3218
3219 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003220}
3221
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003222bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3223 X = getCanonicalTemplateName(X);
3224 Y = getCanonicalTemplateName(Y);
3225 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3226}
3227
Mike Stump1eb44332009-09-09 15:08:12 +00003228TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003229ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003230 switch (Arg.getKind()) {
3231 case TemplateArgument::Null:
3232 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003233
Douglas Gregor1275ae02009-07-28 23:00:59 +00003234 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003235 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003236
Douglas Gregor1275ae02009-07-28 23:00:59 +00003237 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00003238 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003239
Douglas Gregor788cd062009-11-11 01:00:40 +00003240 case TemplateArgument::Template:
3241 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003242
3243 case TemplateArgument::TemplateExpansion:
3244 return TemplateArgument(getCanonicalTemplateName(
3245 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003246 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003247
Douglas Gregor1275ae02009-07-28 23:00:59 +00003248 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00003249 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003250 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003251
Douglas Gregor1275ae02009-07-28 23:00:59 +00003252 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003253 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003254
Douglas Gregor1275ae02009-07-28 23:00:59 +00003255 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003256 if (Arg.pack_size() == 0)
3257 return Arg;
3258
Douglas Gregor910f8002010-11-07 23:05:16 +00003259 TemplateArgument *CanonArgs
3260 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003261 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003262 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003263 AEnd = Arg.pack_end();
3264 A != AEnd; (void)++A, ++Idx)
3265 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003266
Douglas Gregor910f8002010-11-07 23:05:16 +00003267 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003268 }
3269 }
3270
3271 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00003272 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00003273}
3274
Douglas Gregord57959a2009-03-27 23:10:48 +00003275NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003276ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003277 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003278 return 0;
3279
3280 switch (NNS->getKind()) {
3281 case NestedNameSpecifier::Identifier:
3282 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003283 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003284 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3285 NNS->getAsIdentifier());
3286
3287 case NestedNameSpecifier::Namespace:
3288 // A namespace is canonical; build a nested-name-specifier with
3289 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003290 return NestedNameSpecifier::Create(*this, 0,
3291 NNS->getAsNamespace()->getOriginalNamespace());
3292
3293 case NestedNameSpecifier::NamespaceAlias:
3294 // A namespace is canonical; build a nested-name-specifier with
3295 // this namespace and no prefix.
3296 return NestedNameSpecifier::Create(*this, 0,
3297 NNS->getAsNamespaceAlias()->getNamespace()
3298 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003299
3300 case NestedNameSpecifier::TypeSpec:
3301 case NestedNameSpecifier::TypeSpecWithTemplate: {
3302 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003303
3304 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3305 // break it apart into its prefix and identifier, then reconsititute those
3306 // as the canonical nested-name-specifier. This is required to canonicalize
3307 // a dependent nested-name-specifier involving typedefs of dependent-name
3308 // types, e.g.,
3309 // typedef typename T::type T1;
3310 // typedef typename T1::type T2;
3311 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3312 NestedNameSpecifier *Prefix
3313 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3314 return NestedNameSpecifier::Create(*this, Prefix,
3315 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3316 }
3317
Douglas Gregor643f8432010-11-04 00:14:23 +00003318 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor264bf662010-11-04 00:09:33 +00003319 if (const DependentTemplateSpecializationType *DTST
3320 = T->getAs<DependentTemplateSpecializationType>()) {
3321 NestedNameSpecifier *Prefix
3322 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003323
3324 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3325 Prefix, DTST->getIdentifier(),
3326 DTST->getNumArgs(),
3327 DTST->getArgs());
Douglas Gregor264bf662010-11-04 00:09:33 +00003328 T = getCanonicalType(T);
3329 }
3330
John McCall3b657512011-01-19 10:06:00 +00003331 return NestedNameSpecifier::Create(*this, 0, false,
3332 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003333 }
3334
3335 case NestedNameSpecifier::Global:
3336 // The global specifier is canonical and unique.
3337 return NNS;
3338 }
3339
3340 // Required to silence a GCC warning
3341 return 0;
3342}
3343
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003344
Jay Foad4ba2a172011-01-12 09:06:06 +00003345const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003346 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003347 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003348 // Handle the common positive case fast.
3349 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3350 return AT;
3351 }
Mike Stump1eb44332009-09-09 15:08:12 +00003352
John McCall0953e762009-09-24 19:53:00 +00003353 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003354 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003355 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003356
John McCall0953e762009-09-24 19:53:00 +00003357 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003358 // implements C99 6.7.3p8: "If the specification of an array type includes
3359 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003360
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003361 // If we get here, we either have type qualifiers on the type, or we have
3362 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003363 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003364
John McCall3b657512011-01-19 10:06:00 +00003365 SplitQualType split = T.getSplitDesugaredType();
3366 Qualifiers qs = split.second;
Mike Stump1eb44332009-09-09 15:08:12 +00003367
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003368 // If we have a simple case, just return now.
John McCall3b657512011-01-19 10:06:00 +00003369 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3370 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003371 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003372
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003373 // Otherwise, we have an array and we have qualifiers on it. Push the
3374 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003375 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003376
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003377 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3378 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3379 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003380 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003381 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3382 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3383 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003384 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003385
Mike Stump1eb44332009-09-09 15:08:12 +00003386 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003387 = dyn_cast<DependentSizedArrayType>(ATy))
3388 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003389 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003390 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003391 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003392 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003393 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003394
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003395 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003396 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003397 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003398 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003399 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003400 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003401}
3402
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003403QualType ASTContext::getAdjustedParameterType(QualType T) {
3404 // C99 6.7.5.3p7:
3405 // A declaration of a parameter as "array of type" shall be
3406 // adjusted to "qualified pointer to type", where the type
3407 // qualifiers (if any) are those specified within the [ and ] of
3408 // the array type derivation.
3409 if (T->isArrayType())
3410 return getArrayDecayedType(T);
3411
3412 // C99 6.7.5.3p8:
3413 // A declaration of a parameter as "function returning type"
3414 // shall be adjusted to "pointer to function returning type", as
3415 // in 6.3.2.1.
3416 if (T->isFunctionType())
3417 return getPointerType(T);
3418
3419 return T;
3420}
3421
3422QualType ASTContext::getSignatureParameterType(QualType T) {
3423 T = getVariableArrayDecayedType(T);
3424 T = getAdjustedParameterType(T);
3425 return T.getUnqualifiedType();
3426}
3427
Chris Lattnere6327742008-04-02 05:18:44 +00003428/// getArrayDecayedType - Return the properly qualified result of decaying the
3429/// specified array type to a pointer. This operation is non-trivial when
3430/// handling typedefs etc. The canonical type of "T" must be an array type,
3431/// this returns a pointer to a properly qualified element of the array.
3432///
3433/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003434QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003435 // Get the element type with 'getAsArrayType' so that we don't lose any
3436 // typedefs in the element type of the array. This also handles propagation
3437 // of type qualifiers from the array type into the element type if present
3438 // (C99 6.7.3p8).
3439 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3440 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003441
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003442 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003443
3444 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003445 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003446}
3447
John McCall3b657512011-01-19 10:06:00 +00003448QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3449 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003450}
3451
John McCall3b657512011-01-19 10:06:00 +00003452QualType ASTContext::getBaseElementType(QualType type) const {
3453 Qualifiers qs;
3454 while (true) {
3455 SplitQualType split = type.getSplitDesugaredType();
3456 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3457 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003458
John McCall3b657512011-01-19 10:06:00 +00003459 type = array->getElementType();
3460 qs.addConsistentQualifiers(split.second);
3461 }
Mike Stump1eb44332009-09-09 15:08:12 +00003462
John McCall3b657512011-01-19 10:06:00 +00003463 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003464}
3465
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003466/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003467uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003468ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3469 uint64_t ElementCount = 1;
3470 do {
3471 ElementCount *= CA->getSize().getZExtValue();
3472 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3473 } while (CA);
3474 return ElementCount;
3475}
3476
Reid Spencer5f016e22007-07-11 17:01:13 +00003477/// getFloatingRank - Return a relative rank for floating point types.
3478/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003479static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003480 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003481 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003482
John McCall183700f2009-09-21 23:43:11 +00003483 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3484 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003485 default: llvm_unreachable("getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00003486 case BuiltinType::Float: return FloatRank;
3487 case BuiltinType::Double: return DoubleRank;
3488 case BuiltinType::LongDouble: return LongDoubleRank;
3489 }
3490}
3491
Mike Stump1eb44332009-09-09 15:08:12 +00003492/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3493/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003494/// 'typeDomain' is a real floating point or complex type.
3495/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003496QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3497 QualType Domain) const {
3498 FloatingRank EltRank = getFloatingRank(Size);
3499 if (Domain->isComplexType()) {
3500 switch (EltRank) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003501 default: llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00003502 case FloatRank: return FloatComplexTy;
3503 case DoubleRank: return DoubleComplexTy;
3504 case LongDoubleRank: return LongDoubleComplexTy;
3505 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003506 }
Chris Lattner1361b112008-04-06 23:58:54 +00003507
3508 assert(Domain->isRealFloatingType() && "Unknown domain!");
3509 switch (EltRank) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003510 default: llvm_unreachable("getFloatingRank(): illegal value for rank");
Chris Lattner1361b112008-04-06 23:58:54 +00003511 case FloatRank: return FloatTy;
3512 case DoubleRank: return DoubleTy;
3513 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003514 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003515}
3516
Chris Lattner7cfeb082008-04-06 23:55:33 +00003517/// getFloatingTypeOrder - Compare the rank of the two specified floating
3518/// point types, ignoring the domain of the type (i.e. 'double' ==
3519/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003520/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003521int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003522 FloatingRank LHSR = getFloatingRank(LHS);
3523 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003524
Chris Lattnera75cea32008-04-06 23:38:49 +00003525 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003526 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003527 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003528 return 1;
3529 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003530}
3531
Chris Lattnerf52ab252008-04-06 22:59:24 +00003532/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3533/// routine will assert if passed a built-in type that isn't an integer or enum,
3534/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003535unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003536 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCallf4c73712011-01-19 06:33:43 +00003537 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00003538 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00003539
Chris Lattner3f59c972010-12-25 23:25:43 +00003540 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3541 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003542 T = getFromTargetType(Target->getWCharType()).getTypePtr();
Eli Friedmana3426752009-07-05 23:44:27 +00003543
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003544 if (T->isSpecificBuiltinType(BuiltinType::Char16))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003545 T = getFromTargetType(Target->getChar16Type()).getTypePtr();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003546
3547 if (T->isSpecificBuiltinType(BuiltinType::Char32))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003548 T = getFromTargetType(Target->getChar32Type()).getTypePtr();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003549
Chris Lattnerf52ab252008-04-06 22:59:24 +00003550 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003551 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00003552 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003553 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003554 case BuiltinType::Char_S:
3555 case BuiltinType::Char_U:
3556 case BuiltinType::SChar:
3557 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003558 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003559 case BuiltinType::Short:
3560 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003561 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003562 case BuiltinType::Int:
3563 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003564 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003565 case BuiltinType::Long:
3566 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003567 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003568 case BuiltinType::LongLong:
3569 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003570 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003571 case BuiltinType::Int128:
3572 case BuiltinType::UInt128:
3573 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003574 }
3575}
3576
Eli Friedman04e83572009-08-20 04:21:42 +00003577/// \brief Whether this is a promotable bitfield reference according
3578/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3579///
3580/// \returns the type this bit-field will promote to, or NULL if no
3581/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00003582QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003583 if (E->isTypeDependent() || E->isValueDependent())
3584 return QualType();
3585
Eli Friedman04e83572009-08-20 04:21:42 +00003586 FieldDecl *Field = E->getBitField();
3587 if (!Field)
3588 return QualType();
3589
3590 QualType FT = Field->getType();
3591
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003592 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00003593 uint64_t IntSize = getTypeSize(IntTy);
3594 // GCC extension compatibility: if the bit-field size is less than or equal
3595 // to the size of int, it gets promoted no matter what its type is.
3596 // For instance, unsigned long bf : 4 gets promoted to signed int.
3597 if (BitWidth < IntSize)
3598 return IntTy;
3599
3600 if (BitWidth == IntSize)
3601 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3602
3603 // Types bigger than int are not subject to promotions, and therefore act
3604 // like the base type.
3605 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3606 // is ridiculous.
3607 return QualType();
3608}
3609
Eli Friedmana95d7572009-08-19 07:44:53 +00003610/// getPromotedIntegerType - Returns the type that Promotable will
3611/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3612/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003613QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003614 assert(!Promotable.isNull());
3615 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003616 if (const EnumType *ET = Promotable->getAs<EnumType>())
3617 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00003618 if (Promotable->isSignedIntegerType())
3619 return IntTy;
3620 uint64_t PromotableSize = getTypeSize(Promotable);
3621 uint64_t IntSize = getTypeSize(IntTy);
3622 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3623 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3624}
3625
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003626/// \brief Recurses in pointer/array types until it finds an objc retainable
3627/// type and returns its ownership.
3628Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3629 while (!T.isNull()) {
3630 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3631 return T.getObjCLifetime();
3632 if (T->isArrayType())
3633 T = getBaseElementType(T);
3634 else if (const PointerType *PT = T->getAs<PointerType>())
3635 T = PT->getPointeeType();
3636 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00003637 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003638 else
3639 break;
3640 }
3641
3642 return Qualifiers::OCL_None;
3643}
3644
Mike Stump1eb44332009-09-09 15:08:12 +00003645/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003646/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003647/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003648int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00003649 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3650 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003651 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003652
Chris Lattnerf52ab252008-04-06 22:59:24 +00003653 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3654 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003655
Chris Lattner7cfeb082008-04-06 23:55:33 +00003656 unsigned LHSRank = getIntegerRank(LHSC);
3657 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003658
Chris Lattner7cfeb082008-04-06 23:55:33 +00003659 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3660 if (LHSRank == RHSRank) return 0;
3661 return LHSRank > RHSRank ? 1 : -1;
3662 }
Mike Stump1eb44332009-09-09 15:08:12 +00003663
Chris Lattner7cfeb082008-04-06 23:55:33 +00003664 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3665 if (LHSUnsigned) {
3666 // If the unsigned [LHS] type is larger, return it.
3667 if (LHSRank >= RHSRank)
3668 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003669
Chris Lattner7cfeb082008-04-06 23:55:33 +00003670 // If the signed type can represent all values of the unsigned type, it
3671 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003672 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003673 return -1;
3674 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003675
Chris Lattner7cfeb082008-04-06 23:55:33 +00003676 // If the unsigned [RHS] type is larger, return it.
3677 if (RHSRank >= LHSRank)
3678 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003679
Chris Lattner7cfeb082008-04-06 23:55:33 +00003680 // If the signed type can represent all values of the unsigned type, it
3681 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003682 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003683 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003684}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003685
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003686static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003687CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3688 DeclContext *DC, IdentifierInfo *Id) {
3689 SourceLocation Loc;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003690 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003691 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003692 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003693 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003694}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003695
Mike Stump1eb44332009-09-09 15:08:12 +00003696// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003697QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003698 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003699 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003700 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003701 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003702 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003703
Anders Carlssonf06273f2007-11-19 00:25:30 +00003704 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003705
Anders Carlsson71993dd2007-08-17 05:31:46 +00003706 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003707 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003708 // int flags;
3709 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003710 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003711 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003712 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003713 FieldTypes[3] = LongTy;
3714
Anders Carlsson71993dd2007-08-17 05:31:46 +00003715 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003716 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003717 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003718 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00003719 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003720 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003721 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003722 /*Mutable=*/false,
3723 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003724 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003725 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003726 }
3727
Douglas Gregor838db382010-02-11 01:19:42 +00003728 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003729 }
Mike Stump1eb44332009-09-09 15:08:12 +00003730
Anders Carlsson71993dd2007-08-17 05:31:46 +00003731 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003732}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003733
Douglas Gregor319ac892009-04-23 22:29:11 +00003734void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003735 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003736 assert(Rec && "Invalid CFConstantStringType");
3737 CFConstantStringTypeDecl = Rec->getDecl();
3738}
3739
Jay Foad4ba2a172011-01-12 09:06:06 +00003740QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00003741 if (BlockDescriptorType)
3742 return getTagDeclType(BlockDescriptorType);
3743
3744 RecordDecl *T;
3745 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003746 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003747 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003748 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003749
3750 QualType FieldTypes[] = {
3751 UnsignedLongTy,
3752 UnsignedLongTy,
3753 };
3754
3755 const char *FieldNames[] = {
3756 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003757 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003758 };
3759
3760 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003761 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003762 SourceLocation(),
3763 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003764 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003765 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003766 /*Mutable=*/false,
3767 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003768 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003769 T->addDecl(Field);
3770 }
3771
Douglas Gregor838db382010-02-11 01:19:42 +00003772 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003773
3774 BlockDescriptorType = T;
3775
3776 return getTagDeclType(BlockDescriptorType);
3777}
3778
Jay Foad4ba2a172011-01-12 09:06:06 +00003779QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00003780 if (BlockDescriptorExtendedType)
3781 return getTagDeclType(BlockDescriptorExtendedType);
3782
3783 RecordDecl *T;
3784 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003785 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003786 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003787 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003788
3789 QualType FieldTypes[] = {
3790 UnsignedLongTy,
3791 UnsignedLongTy,
3792 getPointerType(VoidPtrTy),
3793 getPointerType(VoidPtrTy)
3794 };
3795
3796 const char *FieldNames[] = {
3797 "reserved",
3798 "Size",
3799 "CopyFuncPtr",
3800 "DestroyFuncPtr"
3801 };
3802
3803 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003804 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00003805 SourceLocation(),
3806 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003807 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003808 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003809 /*Mutable=*/false,
3810 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003811 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003812 T->addDecl(Field);
3813 }
3814
Douglas Gregor838db382010-02-11 01:19:42 +00003815 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003816
3817 BlockDescriptorExtendedType = T;
3818
3819 return getTagDeclType(BlockDescriptorExtendedType);
3820}
3821
Jay Foad4ba2a172011-01-12 09:06:06 +00003822bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCallf85e1932011-06-15 23:02:42 +00003823 if (Ty->isObjCRetainableType())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003824 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003825 if (getLangOptions().CPlusPlus) {
3826 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3827 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Huntffe37fd2011-05-25 20:50:04 +00003828 return RD->hasConstCopyConstructor();
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003829
3830 }
3831 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003832 return false;
3833}
3834
Jay Foad4ba2a172011-01-12 09:06:06 +00003835QualType
Chris Lattner5f9e2722011-07-23 10:55:15 +00003836ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003837 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003838 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003839 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003840 // unsigned int __flags;
3841 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003842 // void *__copy_helper; // as needed
3843 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003844 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003845 // } *
3846
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003847 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3848
3849 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003850 llvm::SmallString<36> Name;
3851 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3852 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003853 RecordDecl *T;
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003854 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003855 T->startDefinition();
3856 QualType Int32Ty = IntTy;
3857 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3858 QualType FieldTypes[] = {
3859 getPointerType(VoidPtrTy),
3860 getPointerType(getTagDeclType(T)),
3861 Int32Ty,
3862 Int32Ty,
3863 getPointerType(VoidPtrTy),
3864 getPointerType(VoidPtrTy),
3865 Ty
3866 };
3867
Chris Lattner5f9e2722011-07-23 10:55:15 +00003868 StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003869 "__isa",
3870 "__forwarding",
3871 "__flags",
3872 "__size",
3873 "__copy_helper",
3874 "__destroy_helper",
3875 DeclName,
3876 };
3877
3878 for (size_t i = 0; i < 7; ++i) {
3879 if (!HasCopyAndDispose && i >=4 && i <= 5)
3880 continue;
3881 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003882 SourceLocation(),
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003883 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003884 FieldTypes[i], /*TInfo=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003885 /*BitWidth=*/0, /*Mutable=*/false,
3886 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003887 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003888 T->addDecl(Field);
3889 }
3890
Douglas Gregor838db382010-02-11 01:19:42 +00003891 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003892
3893 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003894}
3895
Douglas Gregore97179c2011-09-08 01:46:34 +00003896TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
3897 if (!ObjCInstanceTypeDecl)
3898 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
3899 getTranslationUnitDecl(),
3900 SourceLocation(),
3901 SourceLocation(),
3902 &Idents.get("instancetype"),
3903 getTrivialTypeSourceInfo(getObjCIdType()));
3904 return ObjCInstanceTypeDecl;
3905}
3906
Anders Carlssone8c49532007-10-29 06:33:42 +00003907// This returns true if a type has been typedefed to BOOL:
3908// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003909static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003910 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003911 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3912 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003913
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003914 return false;
3915}
3916
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003917/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003918/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00003919CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00003920 if (!type->isIncompleteArrayType() && type->isIncompleteType())
3921 return CharUnits::Zero();
3922
Ken Dyck199c3d62010-01-11 17:06:35 +00003923 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003924
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003925 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003926 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003927 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003928 // Treat arrays as pointers, since that's how they're passed in.
3929 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003930 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003931 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003932}
3933
3934static inline
3935std::string charUnitsToString(const CharUnits &CU) {
3936 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003937}
3938
John McCall6b5a61b2011-02-07 10:33:21 +00003939/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003940/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00003941std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3942 std::string S;
3943
David Chisnall5e530af2009-11-17 19:33:30 +00003944 const BlockDecl *Decl = Expr->getBlockDecl();
3945 QualType BlockTy =
3946 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3947 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003948 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003949 // Compute size of all parameters.
3950 // Start with computing size of a pointer in number of bytes.
3951 // FIXME: There might(should) be a better way of doing this computation!
3952 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003953 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3954 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003955 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003956 E = Decl->param_end(); PI != E; ++PI) {
3957 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003958 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003959 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003960 ParmOffset += sz;
3961 }
3962 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003963 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003964 // Block pointer and offset.
3965 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00003966
3967 // Argument types.
3968 ParmOffset = PtrSize;
3969 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3970 Decl->param_end(); PI != E; ++PI) {
3971 ParmVarDecl *PVDecl = *PI;
3972 QualType PType = PVDecl->getOriginalType();
3973 if (const ArrayType *AT =
3974 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3975 // Use array's original type only if it has known number of
3976 // elements.
3977 if (!isa<ConstantArrayType>(AT))
3978 PType = PVDecl->getType();
3979 } else if (PType->isFunctionType())
3980 PType = PVDecl->getType();
3981 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003982 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003983 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003984 }
John McCall6b5a61b2011-02-07 10:33:21 +00003985
3986 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00003987}
3988
Douglas Gregorf968d832011-05-27 01:19:52 +00003989bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00003990 std::string& S) {
3991 // Encode result type.
3992 getObjCEncodingForType(Decl->getResultType(), S);
3993 CharUnits ParmOffset;
3994 // Compute size of all parameters.
3995 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3996 E = Decl->param_end(); PI != E; ++PI) {
3997 QualType PType = (*PI)->getType();
3998 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00003999 if (sz.isZero())
4000 return true;
4001
David Chisnall5389f482010-12-30 14:05:53 +00004002 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004003 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004004 ParmOffset += sz;
4005 }
4006 S += charUnitsToString(ParmOffset);
4007 ParmOffset = CharUnits::Zero();
4008
4009 // Argument types.
4010 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4011 E = Decl->param_end(); PI != E; ++PI) {
4012 ParmVarDecl *PVDecl = *PI;
4013 QualType PType = PVDecl->getOriginalType();
4014 if (const ArrayType *AT =
4015 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4016 // Use array's original type only if it has known number of
4017 // elements.
4018 if (!isa<ConstantArrayType>(AT))
4019 PType = PVDecl->getType();
4020 } else if (PType->isFunctionType())
4021 PType = PVDecl->getType();
4022 getObjCEncodingForType(PType, S);
4023 S += charUnitsToString(ParmOffset);
4024 ParmOffset += getObjCEncodingTypeSize(PType);
4025 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004026
4027 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004028}
4029
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004030/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004031/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004032bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00004033 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004034 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004035 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004036 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004037 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004038 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004039 // Compute size of all parameters.
4040 // Start with computing size of a pointer in number of bytes.
4041 // FIXME: There might(should) be a better way of doing this computation!
4042 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004043 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004044 // The first two arguments (self and _cmd) are pointers; account for
4045 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004046 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004047 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004048 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004049 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004050 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004051 if (sz.isZero())
4052 return true;
4053
Ken Dyck199c3d62010-01-11 17:06:35 +00004054 assert (sz.isPositive() &&
4055 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004056 ParmOffset += sz;
4057 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004058 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004059 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004060 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004061
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004062 // Argument types.
4063 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004064 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004065 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004066 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004067 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004068 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004069 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4070 // Use array's original type only if it has known number of
4071 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004072 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004073 PType = PVDecl->getType();
4074 } else if (PType->isFunctionType())
4075 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004076 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004077 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004078 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004079 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004080 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004081 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004082 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004083
4084 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004085}
4086
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004087/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004088/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004089/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4090/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004091/// Property attributes are stored as a comma-delimited C string. The simple
4092/// attributes readonly and bycopy are encoded as single characters. The
4093/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4094/// encoded as single characters, followed by an identifier. Property types
4095/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004096/// these attributes are defined by the following enumeration:
4097/// @code
4098/// enum PropertyAttributes {
4099/// kPropertyReadOnly = 'R', // property is read-only.
4100/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4101/// kPropertyByref = '&', // property is a reference to the value last assigned
4102/// kPropertyDynamic = 'D', // property is dynamic
4103/// kPropertyGetter = 'G', // followed by getter selector name
4104/// kPropertySetter = 'S', // followed by setter selector name
4105/// kPropertyInstanceVariable = 'V' // followed by instance variable name
4106/// kPropertyType = 't' // followed by old-style type encoding.
4107/// kPropertyWeak = 'W' // 'weak' property
4108/// kPropertyStrong = 'P' // property GC'able
4109/// kPropertyNonAtomic = 'N' // property non-atomic
4110/// };
4111/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004112void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004113 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004114 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004115 // Collect information from the property implementation decl(s).
4116 bool Dynamic = false;
4117 ObjCPropertyImplDecl *SynthesizePID = 0;
4118
4119 // FIXME: Duplicated code due to poor abstraction.
4120 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004121 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004122 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4123 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004124 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004125 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004126 ObjCPropertyImplDecl *PID = *i;
4127 if (PID->getPropertyDecl() == PD) {
4128 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4129 Dynamic = true;
4130 } else {
4131 SynthesizePID = PID;
4132 }
4133 }
4134 }
4135 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004136 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004137 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004138 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004139 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004140 ObjCPropertyImplDecl *PID = *i;
4141 if (PID->getPropertyDecl() == PD) {
4142 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4143 Dynamic = true;
4144 } else {
4145 SynthesizePID = PID;
4146 }
4147 }
Mike Stump1eb44332009-09-09 15:08:12 +00004148 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004149 }
4150 }
4151
4152 // FIXME: This is not very efficient.
4153 S = "T";
4154
4155 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004156 // GCC has some special rules regarding encoding of properties which
4157 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004158 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004159 true /* outermost type */,
4160 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004161
4162 if (PD->isReadOnly()) {
4163 S += ",R";
4164 } else {
4165 switch (PD->getSetterKind()) {
4166 case ObjCPropertyDecl::Assign: break;
4167 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004168 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004169 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004170 }
4171 }
4172
4173 // It really isn't clear at all what this means, since properties
4174 // are "dynamic by default".
4175 if (Dynamic)
4176 S += ",D";
4177
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004178 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4179 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004180
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004181 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4182 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004183 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004184 }
4185
4186 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4187 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004188 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004189 }
4190
4191 if (SynthesizePID) {
4192 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4193 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004194 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004195 }
4196
4197 // FIXME: OBJCGC: weak & strong
4198}
4199
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004200/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004201/// Another legacy compatibility encoding: 32-bit longs are encoded as
4202/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004203/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4204///
4205void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004206 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004207 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004208 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004209 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004210 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004211 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004212 PointeeTy = IntTy;
4213 }
4214 }
4215}
4216
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004217void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004218 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004219 // We follow the behavior of gcc, expanding structures which are
4220 // directly pointed to, and expanding embedded structures. Note that
4221 // these rules are sufficient to prevent recursive encoding of the
4222 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004223 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004224 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004225}
4226
David Chisnall64fd7e82010-06-04 01:10:52 +00004227static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4228 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004229 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnall64fd7e82010-06-04 01:10:52 +00004230 case BuiltinType::Void: return 'v';
4231 case BuiltinType::Bool: return 'B';
4232 case BuiltinType::Char_U:
4233 case BuiltinType::UChar: return 'C';
4234 case BuiltinType::UShort: return 'S';
4235 case BuiltinType::UInt: return 'I';
4236 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00004237 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004238 case BuiltinType::UInt128: return 'T';
4239 case BuiltinType::ULongLong: return 'Q';
4240 case BuiltinType::Char_S:
4241 case BuiltinType::SChar: return 'c';
4242 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004243 case BuiltinType::WChar_S:
4244 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004245 case BuiltinType::Int: return 'i';
4246 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00004247 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004248 case BuiltinType::LongLong: return 'q';
4249 case BuiltinType::Int128: return 't';
4250 case BuiltinType::Float: return 'f';
4251 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004252 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004253 }
4254}
4255
Douglas Gregor5471bc82011-09-08 17:18:35 +00004256static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4257 EnumDecl *Enum = ET->getDecl();
4258
4259 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4260 if (!Enum->isFixed())
4261 return 'i';
4262
4263 // The encoding of a fixed enum type matches its fixed underlying type.
4264 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4265}
4266
Jay Foad4ba2a172011-01-12 09:06:06 +00004267static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004268 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004269 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004270 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004271 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4272 // The GNU runtime requires more information; bitfields are encoded as b,
4273 // then the offset (in bits) of the first element, then the type of the
4274 // bitfield, then the size in bits. For example, in this structure:
4275 //
4276 // struct
4277 // {
4278 // int integer;
4279 // int flags:2;
4280 // };
4281 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4282 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4283 // information is not especially sensible, but we're stuck with it for
4284 // compatibility with GCC, although providing it breaks anything that
4285 // actually uses runtime introspection and wants to work on both runtimes...
4286 if (!Ctx->getLangOptions().NeXTRuntime) {
4287 const RecordDecl *RD = FD->getParent();
4288 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004289 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00004290 if (const EnumType *ET = T->getAs<EnumType>())
4291 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnallc7ff82c2010-12-26 20:12:30 +00004292 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004293 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004294 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004295 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004296}
4297
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004298// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004299void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4300 bool ExpandPointedToStructures,
4301 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004302 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004303 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004304 bool EncodingProperty,
4305 bool StructField) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004306 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004307 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004308 return EncodeBitField(this, S, T, FD);
4309 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004310 return;
4311 }
Mike Stump1eb44332009-09-09 15:08:12 +00004312
John McCall183700f2009-09-21 23:43:11 +00004313 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004314 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004315 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004316 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004317 return;
4318 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004319
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004320 // encoding for pointer or r3eference types.
4321 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004322 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004323 if (PT->isObjCSelType()) {
4324 S += ':';
4325 return;
4326 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004327 PointeeTy = PT->getPointeeType();
4328 }
4329 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4330 PointeeTy = RT->getPointeeType();
4331 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004332 bool isReadOnly = false;
4333 // For historical/compatibility reasons, the read-only qualifier of the
4334 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4335 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004336 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004337 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004338 if (OutermostType && T.isConstQualified()) {
4339 isReadOnly = true;
4340 S += 'r';
4341 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004342 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004343 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004344 while (P->getAs<PointerType>())
4345 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004346 if (P.isConstQualified()) {
4347 isReadOnly = true;
4348 S += 'r';
4349 }
4350 }
4351 if (isReadOnly) {
4352 // Another legacy compatibility encoding. Some ObjC qualifier and type
4353 // combinations need to be rearranged.
4354 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00004355 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00004356 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004357 }
Mike Stump1eb44332009-09-09 15:08:12 +00004358
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004359 if (PointeeTy->isCharType()) {
4360 // char pointer types should be encoded as '*' unless it is a
4361 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004362 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004363 S += '*';
4364 return;
4365 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004366 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004367 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4368 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4369 S += '#';
4370 return;
4371 }
4372 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4373 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4374 S += '@';
4375 return;
4376 }
4377 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004378 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004379 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004380 getLegacyIntegralTypeEncoding(PointeeTy);
4381
Mike Stump1eb44332009-09-09 15:08:12 +00004382 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004383 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004384 return;
4385 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004386
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004387 if (const ArrayType *AT =
4388 // Ignore type qualifiers etc.
4389 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004390 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004391 // Incomplete arrays are encoded as a pointer to the array element.
4392 S += '^';
4393
Mike Stump1eb44332009-09-09 15:08:12 +00004394 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004395 false, ExpandStructures, FD);
4396 } else {
4397 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004398
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004399 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4400 if (getTypeSize(CAT->getElementType()) == 0)
4401 S += '0';
4402 else
4403 S += llvm::utostr(CAT->getSize().getZExtValue());
4404 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00004405 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004406 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4407 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00004408 S += '0';
4409 }
Mike Stump1eb44332009-09-09 15:08:12 +00004410
4411 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004412 false, ExpandStructures, FD);
4413 S += ']';
4414 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004415 return;
4416 }
Mike Stump1eb44332009-09-09 15:08:12 +00004417
John McCall183700f2009-09-21 23:43:11 +00004418 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004419 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004420 return;
4421 }
Mike Stump1eb44332009-09-09 15:08:12 +00004422
Ted Kremenek6217b802009-07-29 21:53:49 +00004423 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004424 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004425 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004426 // Anonymous structures print as '?'
4427 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4428 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004429 if (ClassTemplateSpecializationDecl *Spec
4430 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4431 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4432 std::string TemplateArgsStr
4433 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004434 TemplateArgs.data(),
4435 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00004436 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004437
4438 S += TemplateArgsStr;
4439 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004440 } else {
4441 S += '?';
4442 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004443 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004444 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004445 if (!RDecl->isUnion()) {
4446 getObjCEncodingForStructureImpl(RDecl, S, FD);
4447 } else {
4448 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4449 FieldEnd = RDecl->field_end();
4450 Field != FieldEnd; ++Field) {
4451 if (FD) {
4452 S += '"';
4453 S += Field->getNameAsString();
4454 S += '"';
4455 }
Mike Stump1eb44332009-09-09 15:08:12 +00004456
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004457 // Special case bit-fields.
4458 if (Field->isBitField()) {
4459 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4460 (*Field));
4461 } else {
4462 QualType qt = Field->getType();
4463 getLegacyIntegralTypeEncoding(qt);
4464 getObjCEncodingForTypeImpl(qt, S, false, true,
4465 FD, /*OutermostType*/false,
4466 /*EncodingProperty*/false,
4467 /*StructField*/true);
4468 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004469 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004470 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004471 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004472 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004473 return;
4474 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004475
Douglas Gregor5471bc82011-09-08 17:18:35 +00004476 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004477 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004478 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004479 else
Douglas Gregor5471bc82011-09-08 17:18:35 +00004480 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004481 return;
4482 }
Mike Stump1eb44332009-09-09 15:08:12 +00004483
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004484 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004485 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004486 return;
4487 }
Mike Stump1eb44332009-09-09 15:08:12 +00004488
John McCallc12c5bb2010-05-15 11:32:37 +00004489 // Ignore protocol qualifiers when mangling at this level.
4490 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4491 T = OT->getBaseType();
4492
John McCall0953e762009-09-24 19:53:00 +00004493 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004494 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004495 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004496 S += '{';
4497 const IdentifierInfo *II = OI->getIdentifier();
4498 S += II->getName();
4499 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00004500 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004501 DeepCollectObjCIvars(OI, true, Ivars);
4502 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00004503 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004504 if (Field->isBitField())
4505 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004506 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004507 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004508 }
4509 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004510 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004511 }
Mike Stump1eb44332009-09-09 15:08:12 +00004512
John McCall183700f2009-09-21 23:43:11 +00004513 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004514 if (OPT->isObjCIdType()) {
4515 S += '@';
4516 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004517 }
Mike Stump1eb44332009-09-09 15:08:12 +00004518
Steve Naroff27d20a22009-10-28 22:03:49 +00004519 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4520 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4521 // Since this is a binary compatibility issue, need to consult with runtime
4522 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004523 S += '#';
4524 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004525 }
Mike Stump1eb44332009-09-09 15:08:12 +00004526
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004527 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004528 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004529 ExpandPointedToStructures,
4530 ExpandStructures, FD);
4531 if (FD || EncodingProperty) {
4532 // Note that we do extended encoding of protocol qualifer list
4533 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004534 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004535 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4536 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004537 S += '<';
4538 S += (*I)->getNameAsString();
4539 S += '>';
4540 }
4541 S += '"';
4542 }
4543 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004544 }
Mike Stump1eb44332009-09-09 15:08:12 +00004545
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004546 QualType PointeeTy = OPT->getPointeeType();
4547 if (!EncodingProperty &&
4548 isa<TypedefType>(PointeeTy.getTypePtr())) {
4549 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004550 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004551 // {...};
4552 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004553 getObjCEncodingForTypeImpl(PointeeTy, S,
4554 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004555 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004556 return;
4557 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004558
4559 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00004560 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004561 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004562 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004563 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4564 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004565 S += '<';
4566 S += (*I)->getNameAsString();
4567 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004568 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004569 S += '"';
4570 }
4571 return;
4572 }
Mike Stump1eb44332009-09-09 15:08:12 +00004573
John McCall532ec7b2010-05-17 23:56:34 +00004574 // gcc just blithely ignores member pointers.
4575 // TODO: maybe there should be a mangling for these
4576 if (T->getAs<MemberPointerType>())
4577 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004578
4579 if (T->isVectorType()) {
4580 // This matches gcc's encoding, even though technically it is
4581 // insufficient.
4582 // FIXME. We should do a better job than gcc.
4583 return;
4584 }
4585
David Blaikieb219cfc2011-09-23 05:06:16 +00004586 llvm_unreachable("@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004587}
4588
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004589void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4590 std::string &S,
4591 const FieldDecl *FD,
4592 bool includeVBases) const {
4593 assert(RDecl && "Expected non-null RecordDecl");
4594 assert(!RDecl->isUnion() && "Should not be called for unions");
4595 if (!RDecl->getDefinition())
4596 return;
4597
4598 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4599 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4600 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4601
4602 if (CXXRec) {
4603 for (CXXRecordDecl::base_class_iterator
4604 BI = CXXRec->bases_begin(),
4605 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4606 if (!BI->isVirtual()) {
4607 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004608 if (base->isEmpty())
4609 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004610 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4611 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4612 std::make_pair(offs, base));
4613 }
4614 }
4615 }
4616
4617 unsigned i = 0;
4618 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4619 FieldEnd = RDecl->field_end();
4620 Field != FieldEnd; ++Field, ++i) {
4621 uint64_t offs = layout.getFieldOffset(i);
4622 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4623 std::make_pair(offs, *Field));
4624 }
4625
4626 if (CXXRec && includeVBases) {
4627 for (CXXRecordDecl::base_class_iterator
4628 BI = CXXRec->vbases_begin(),
4629 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4630 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004631 if (base->isEmpty())
4632 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004633 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00004634 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4635 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4636 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004637 }
4638 }
4639
4640 CharUnits size;
4641 if (CXXRec) {
4642 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4643 } else {
4644 size = layout.getSize();
4645 }
4646
4647 uint64_t CurOffs = 0;
4648 std::multimap<uint64_t, NamedDecl *>::iterator
4649 CurLayObj = FieldOrBaseOffsets.begin();
4650
Argyrios Kyrtzidiscb8061e2011-08-22 16:03:14 +00004651 if ((CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) ||
4652 (CurLayObj == FieldOrBaseOffsets.end() &&
4653 CXXRec && CXXRec->isDynamicClass())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004654 assert(CXXRec && CXXRec->isDynamicClass() &&
4655 "Offset 0 was empty but no VTable ?");
4656 if (FD) {
4657 S += "\"_vptr$";
4658 std::string recname = CXXRec->getNameAsString();
4659 if (recname.empty()) recname = "?";
4660 S += recname;
4661 S += '"';
4662 }
4663 S += "^^?";
4664 CurOffs += getTypeSize(VoidPtrTy);
4665 }
4666
4667 if (!RDecl->hasFlexibleArrayMember()) {
4668 // Mark the end of the structure.
4669 uint64_t offs = toBits(size);
4670 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4671 std::make_pair(offs, (NamedDecl*)0));
4672 }
4673
4674 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4675 assert(CurOffs <= CurLayObj->first);
4676
4677 if (CurOffs < CurLayObj->first) {
4678 uint64_t padding = CurLayObj->first - CurOffs;
4679 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4680 // packing/alignment of members is different that normal, in which case
4681 // the encoding will be out-of-sync with the real layout.
4682 // If the runtime switches to just consider the size of types without
4683 // taking into account alignment, we could make padding explicit in the
4684 // encoding (e.g. using arrays of chars). The encoding strings would be
4685 // longer then though.
4686 CurOffs += padding;
4687 }
4688
4689 NamedDecl *dcl = CurLayObj->second;
4690 if (dcl == 0)
4691 break; // reached end of structure.
4692
4693 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4694 // We expand the bases without their virtual bases since those are going
4695 // in the initial structure. Note that this differs from gcc which
4696 // expands virtual bases each time one is encountered in the hierarchy,
4697 // making the encoding type bigger than it really is.
4698 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004699 assert(!base->isEmpty());
4700 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004701 } else {
4702 FieldDecl *field = cast<FieldDecl>(dcl);
4703 if (FD) {
4704 S += '"';
4705 S += field->getNameAsString();
4706 S += '"';
4707 }
4708
4709 if (field->isBitField()) {
4710 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004711 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004712 } else {
4713 QualType qt = field->getType();
4714 getLegacyIntegralTypeEncoding(qt);
4715 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4716 /*OutermostType*/false,
4717 /*EncodingProperty*/false,
4718 /*StructField*/true);
4719 CurOffs += getTypeSize(field->getType());
4720 }
4721 }
4722 }
4723}
4724
Mike Stump1eb44332009-09-09 15:08:12 +00004725void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004726 std::string& S) const {
4727 if (QT & Decl::OBJC_TQ_In)
4728 S += 'n';
4729 if (QT & Decl::OBJC_TQ_Inout)
4730 S += 'N';
4731 if (QT & Decl::OBJC_TQ_Out)
4732 S += 'o';
4733 if (QT & Decl::OBJC_TQ_Bycopy)
4734 S += 'O';
4735 if (QT & Decl::OBJC_TQ_Byref)
4736 S += 'R';
4737 if (QT & Decl::OBJC_TQ_Oneway)
4738 S += 'V';
4739}
4740
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004741void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004742 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004743
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004744 BuiltinVaListType = T;
4745}
4746
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00004747TypedefDecl *ASTContext::getObjCIdDecl() const {
4748 if (!ObjCIdDecl) {
4749 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4750 T = getObjCObjectPointerType(T);
4751 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4752 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4753 getTranslationUnitDecl(),
4754 SourceLocation(), SourceLocation(),
4755 &Idents.get("id"), IdInfo);
4756 }
4757
4758 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00004759}
4760
Douglas Gregor7a27ea52011-08-12 06:17:30 +00004761TypedefDecl *ASTContext::getObjCSelDecl() const {
4762 if (!ObjCSelDecl) {
4763 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4764 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4765 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4766 getTranslationUnitDecl(),
4767 SourceLocation(), SourceLocation(),
4768 &Idents.get("SEL"), SelInfo);
4769 }
4770 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004771}
4772
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004773void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004774 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00004775}
4776
Douglas Gregor79d67262011-08-12 05:59:41 +00004777TypedefDecl *ASTContext::getObjCClassDecl() const {
4778 if (!ObjCClassDecl) {
4779 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4780 T = getObjCObjectPointerType(T);
4781 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4782 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4783 getTranslationUnitDecl(),
4784 SourceLocation(), SourceLocation(),
4785 &Idents.get("Class"), ClassInfo);
4786 }
4787
4788 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004789}
4790
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004791void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004792 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004793 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004794
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004795 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004796}
4797
John McCall0bd6feb2009-12-02 08:04:21 +00004798/// \brief Retrieve the template name that corresponds to a non-empty
4799/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00004800TemplateName
4801ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4802 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00004803 unsigned size = End - Begin;
4804 assert(size > 1 && "set is not overloaded!");
4805
4806 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4807 size * sizeof(FunctionTemplateDecl*));
4808 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4809
4810 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004811 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004812 NamedDecl *D = *I;
4813 assert(isa<FunctionTemplateDecl>(D) ||
4814 (isa<UsingShadowDecl>(D) &&
4815 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4816 *Storage++ = D;
4817 }
4818
4819 return TemplateName(OT);
4820}
4821
Douglas Gregor7532dc62009-03-30 22:58:21 +00004822/// \brief Retrieve the template name that represents a qualified
4823/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00004824TemplateName
4825ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4826 bool TemplateKeyword,
4827 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00004828 assert(NNS && "Missing nested-name-specifier in qualified template name");
4829
Douglas Gregor789b1f62010-02-04 18:10:26 +00004830 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004831 llvm::FoldingSetNodeID ID;
4832 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4833
4834 void *InsertPos = 0;
4835 QualifiedTemplateName *QTN =
4836 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4837 if (!QTN) {
4838 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4839 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4840 }
4841
4842 return TemplateName(QTN);
4843}
4844
4845/// \brief Retrieve the template name that represents a dependent
4846/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00004847TemplateName
4848ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4849 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004850 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004851 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004852
4853 llvm::FoldingSetNodeID ID;
4854 DependentTemplateName::Profile(ID, NNS, Name);
4855
4856 void *InsertPos = 0;
4857 DependentTemplateName *QTN =
4858 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4859
4860 if (QTN)
4861 return TemplateName(QTN);
4862
4863 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4864 if (CanonNNS == NNS) {
4865 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4866 } else {
4867 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4868 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004869 DependentTemplateName *CheckQTN =
4870 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4871 assert(!CheckQTN && "Dependent type name canonicalization broken");
4872 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004873 }
4874
4875 DependentTemplateNames.InsertNode(QTN, InsertPos);
4876 return TemplateName(QTN);
4877}
4878
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004879/// \brief Retrieve the template name that represents a dependent
4880/// template name such as \c MetaFun::template operator+.
4881TemplateName
4882ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00004883 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004884 assert((!NNS || NNS->isDependent()) &&
4885 "Nested name specifier must be dependent");
4886
4887 llvm::FoldingSetNodeID ID;
4888 DependentTemplateName::Profile(ID, NNS, Operator);
4889
4890 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004891 DependentTemplateName *QTN
4892 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004893
4894 if (QTN)
4895 return TemplateName(QTN);
4896
4897 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4898 if (CanonNNS == NNS) {
4899 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4900 } else {
4901 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4902 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004903
4904 DependentTemplateName *CheckQTN
4905 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4906 assert(!CheckQTN && "Dependent template name canonicalization broken");
4907 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004908 }
4909
4910 DependentTemplateNames.InsertNode(QTN, InsertPos);
4911 return TemplateName(QTN);
4912}
4913
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004914TemplateName
John McCall14606042011-06-30 08:33:18 +00004915ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
4916 TemplateName replacement) const {
4917 llvm::FoldingSetNodeID ID;
4918 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
4919
4920 void *insertPos = 0;
4921 SubstTemplateTemplateParmStorage *subst
4922 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
4923
4924 if (!subst) {
4925 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
4926 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
4927 }
4928
4929 return TemplateName(subst);
4930}
4931
4932TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004933ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4934 const TemplateArgument &ArgPack) const {
4935 ASTContext &Self = const_cast<ASTContext &>(*this);
4936 llvm::FoldingSetNodeID ID;
4937 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4938
4939 void *InsertPos = 0;
4940 SubstTemplateTemplateParmPackStorage *Subst
4941 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4942
4943 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00004944 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004945 ArgPack.pack_size(),
4946 ArgPack.pack_begin());
4947 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4948 }
4949
4950 return TemplateName(Subst);
4951}
4952
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004953/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004954/// TargetInfo, produce the corresponding type. The unsigned @p Type
4955/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004956CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004957 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004958 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004959 case TargetInfo::SignedShort: return ShortTy;
4960 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4961 case TargetInfo::SignedInt: return IntTy;
4962 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4963 case TargetInfo::SignedLong: return LongTy;
4964 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4965 case TargetInfo::SignedLongLong: return LongLongTy;
4966 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4967 }
4968
David Blaikieb219cfc2011-09-23 05:06:16 +00004969 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004970}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004971
4972//===----------------------------------------------------------------------===//
4973// Type Predicates.
4974//===----------------------------------------------------------------------===//
4975
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004976/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4977/// garbage collection attribute.
4978///
John McCallae278a32011-01-12 00:34:59 +00004979Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
Douglas Gregore289d812011-09-13 17:21:33 +00004980 if (getLangOptions().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00004981 return Qualifiers::GCNone;
4982
4983 assert(getLangOptions().ObjC1);
4984 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4985
4986 // Default behaviour under objective-C's gc is for ObjC pointers
4987 // (or pointers to them) be treated as though they were declared
4988 // as __strong.
4989 if (GCAttrs == Qualifiers::GCNone) {
4990 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4991 return Qualifiers::Strong;
4992 else if (Ty->isPointerType())
4993 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4994 } else {
4995 // It's not valid to set GC attributes on anything that isn't a
4996 // pointer.
4997#ifndef NDEBUG
4998 QualType CT = Ty->getCanonicalTypeInternal();
4999 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5000 CT = AT->getElementType();
5001 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5002#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005003 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00005004 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005005}
5006
Chris Lattner6ac46a42008-04-07 06:51:04 +00005007//===----------------------------------------------------------------------===//
5008// Type Compatibility Testing
5009//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00005010
Mike Stump1eb44332009-09-09 15:08:12 +00005011/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005012/// compatible.
5013static bool areCompatVectorTypes(const VectorType *LHS,
5014 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00005015 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00005016 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00005017 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00005018}
5019
Douglas Gregor255210e2010-08-06 10:14:59 +00005020bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5021 QualType SecondVec) {
5022 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5023 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5024
5025 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5026 return true;
5027
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005028 // Treat Neon vector types and most AltiVec vector types as if they are the
5029 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00005030 const VectorType *First = FirstVec->getAs<VectorType>();
5031 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005032 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00005033 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005034 First->getVectorKind() != VectorType::AltiVecPixel &&
5035 First->getVectorKind() != VectorType::AltiVecBool &&
5036 Second->getVectorKind() != VectorType::AltiVecPixel &&
5037 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00005038 return true;
5039
5040 return false;
5041}
5042
Steve Naroff4084c302009-07-23 01:01:38 +00005043//===----------------------------------------------------------------------===//
5044// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5045//===----------------------------------------------------------------------===//
5046
5047/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5048/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00005049bool
5050ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5051 ObjCProtocolDecl *rProto) const {
Steve Naroff4084c302009-07-23 01:01:38 +00005052 if (lProto == rProto)
5053 return true;
5054 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5055 E = rProto->protocol_end(); PI != E; ++PI)
5056 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5057 return true;
5058 return false;
5059}
5060
Steve Naroff4084c302009-07-23 01:01:38 +00005061/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5062/// return true if lhs's protocols conform to rhs's protocol; false
5063/// otherwise.
5064bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5065 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5066 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5067 return false;
5068}
5069
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005070/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5071/// Class<p1, ...>.
5072bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5073 QualType rhs) {
5074 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5075 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5076 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5077
5078 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5079 E = lhsQID->qual_end(); I != E; ++I) {
5080 bool match = false;
5081 ObjCProtocolDecl *lhsProto = *I;
5082 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5083 E = rhsOPT->qual_end(); J != E; ++J) {
5084 ObjCProtocolDecl *rhsProto = *J;
5085 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5086 match = true;
5087 break;
5088 }
5089 }
5090 if (!match)
5091 return false;
5092 }
5093 return true;
5094}
5095
Steve Naroff4084c302009-07-23 01:01:38 +00005096/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5097/// ObjCQualifiedIDType.
5098bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5099 bool compare) {
5100 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00005101 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005102 lhs->isObjCIdType() || lhs->isObjCClassType())
5103 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005104 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005105 rhs->isObjCIdType() || rhs->isObjCClassType())
5106 return true;
5107
5108 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00005109 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005110
Steve Naroff4084c302009-07-23 01:01:38 +00005111 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005112
Steve Naroff4084c302009-07-23 01:01:38 +00005113 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005114 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00005115 // make sure we check the class hierarchy.
5116 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5117 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5118 E = lhsQID->qual_end(); I != E; ++I) {
5119 // when comparing an id<P> on lhs with a static type on rhs,
5120 // see if static class implements all of id's protocols, directly or
5121 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005122 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00005123 return false;
5124 }
5125 }
5126 // If there are no qualifiers and no interface, we have an 'id'.
5127 return true;
5128 }
Mike Stump1eb44332009-09-09 15:08:12 +00005129 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005130 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5131 E = lhsQID->qual_end(); I != E; ++I) {
5132 ObjCProtocolDecl *lhsProto = *I;
5133 bool match = false;
5134
5135 // when comparing an id<P> on lhs with a static type on rhs,
5136 // see if static class implements all of id's protocols, directly or
5137 // through its super class and categories.
5138 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5139 E = rhsOPT->qual_end(); J != E; ++J) {
5140 ObjCProtocolDecl *rhsProto = *J;
5141 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5142 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5143 match = true;
5144 break;
5145 }
5146 }
Mike Stump1eb44332009-09-09 15:08:12 +00005147 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00005148 // make sure we check the class hierarchy.
5149 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5150 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5151 E = lhsQID->qual_end(); I != E; ++I) {
5152 // when comparing an id<P> on lhs with a static type on rhs,
5153 // see if static class implements all of id's protocols, directly or
5154 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005155 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00005156 match = true;
5157 break;
5158 }
5159 }
5160 }
5161 if (!match)
5162 return false;
5163 }
Mike Stump1eb44332009-09-09 15:08:12 +00005164
Steve Naroff4084c302009-07-23 01:01:38 +00005165 return true;
5166 }
Mike Stump1eb44332009-09-09 15:08:12 +00005167
Steve Naroff4084c302009-07-23 01:01:38 +00005168 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5169 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5170
Mike Stump1eb44332009-09-09 15:08:12 +00005171 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00005172 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005173 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005174 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5175 E = lhsOPT->qual_end(); I != E; ++I) {
5176 ObjCProtocolDecl *lhsProto = *I;
5177 bool match = false;
5178
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005179 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00005180 // see if static class implements all of id's protocols, directly or
5181 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005182 // First, lhs protocols in the qualifier list must be found, direct
5183 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00005184 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5185 E = rhsQID->qual_end(); J != E; ++J) {
5186 ObjCProtocolDecl *rhsProto = *J;
5187 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5188 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5189 match = true;
5190 break;
5191 }
5192 }
5193 if (!match)
5194 return false;
5195 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005196
5197 // Static class's protocols, or its super class or category protocols
5198 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5199 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5200 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5201 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5202 // This is rather dubious but matches gcc's behavior. If lhs has
5203 // no type qualifier and its class has no static protocol(s)
5204 // assume that it is mismatch.
5205 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5206 return false;
5207 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5208 LHSInheritedProtocols.begin(),
5209 E = LHSInheritedProtocols.end(); I != E; ++I) {
5210 bool match = false;
5211 ObjCProtocolDecl *lhsProto = (*I);
5212 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5213 E = rhsQID->qual_end(); J != E; ++J) {
5214 ObjCProtocolDecl *rhsProto = *J;
5215 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5216 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5217 match = true;
5218 break;
5219 }
5220 }
5221 if (!match)
5222 return false;
5223 }
5224 }
Steve Naroff4084c302009-07-23 01:01:38 +00005225 return true;
5226 }
5227 return false;
5228}
5229
Eli Friedman3d815e72008-08-22 00:56:42 +00005230/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005231/// compatible for assignment from RHS to LHS. This handles validation of any
5232/// protocol qualifiers on the LHS or RHS.
5233///
Steve Naroff14108da2009-07-10 23:34:53 +00005234bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5235 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00005236 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5237 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5238
Steve Naroffde2e22d2009-07-15 18:40:39 +00005239 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00005240 if (LHS->isObjCUnqualifiedIdOrClass() ||
5241 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00005242 return true;
5243
John McCallc12c5bb2010-05-15 11:32:37 +00005244 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00005245 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5246 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00005247 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005248
5249 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5250 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5251 QualType(RHSOPT,0));
5252
John McCallc12c5bb2010-05-15 11:32:37 +00005253 // If we have 2 user-defined types, fall into that path.
5254 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00005255 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00005256
Steve Naroff4084c302009-07-23 01:01:38 +00005257 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005258}
5259
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005260/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00005261/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005262/// arguments in block literals. When passed as arguments, passing 'A*' where
5263/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5264/// not OK. For the return type, the opposite is not OK.
5265bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5266 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005267 const ObjCObjectPointerType *RHSOPT,
5268 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005269 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005270 return true;
5271
5272 if (LHSOPT->isObjCBuiltinType()) {
5273 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5274 }
5275
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005276 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005277 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5278 QualType(RHSOPT,0),
5279 false);
5280
5281 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5282 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5283 if (LHS && RHS) { // We have 2 user-defined types.
5284 if (LHS != RHS) {
5285 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005286 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005287 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005288 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005289 }
5290 else
5291 return true;
5292 }
5293 return false;
5294}
5295
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005296/// getIntersectionOfProtocols - This routine finds the intersection of set
5297/// of protocols inherited from two distinct objective-c pointer objects.
5298/// It is used to build composite qualifier list of the composite type of
5299/// the conditional expression involving two objective-c pointer objects.
5300static
5301void getIntersectionOfProtocols(ASTContext &Context,
5302 const ObjCObjectPointerType *LHSOPT,
5303 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005304 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005305
John McCallc12c5bb2010-05-15 11:32:37 +00005306 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5307 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5308 assert(LHS->getInterface() && "LHS must have an interface base");
5309 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005310
5311 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5312 unsigned LHSNumProtocols = LHS->getNumProtocols();
5313 if (LHSNumProtocols > 0)
5314 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5315 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005316 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005317 Context.CollectInheritedProtocols(LHS->getInterface(),
5318 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005319 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5320 LHSInheritedProtocols.end());
5321 }
5322
5323 unsigned RHSNumProtocols = RHS->getNumProtocols();
5324 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00005325 ObjCProtocolDecl **RHSProtocols =
5326 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005327 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5328 if (InheritedProtocolSet.count(RHSProtocols[i]))
5329 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00005330 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005331 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005332 Context.CollectInheritedProtocols(RHS->getInterface(),
5333 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005334 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5335 RHSInheritedProtocols.begin(),
5336 E = RHSInheritedProtocols.end(); I != E; ++I)
5337 if (InheritedProtocolSet.count((*I)))
5338 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005339 }
5340}
5341
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005342/// areCommonBaseCompatible - Returns common base class of the two classes if
5343/// one found. Note that this is O'2 algorithm. But it will be called as the
5344/// last type comparison in a ?-exp of ObjC pointer types before a
5345/// warning is issued. So, its invokation is extremely rare.
5346QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00005347 const ObjCObjectPointerType *Lptr,
5348 const ObjCObjectPointerType *Rptr) {
5349 const ObjCObjectType *LHS = Lptr->getObjectType();
5350 const ObjCObjectType *RHS = Rptr->getObjectType();
5351 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5352 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005353 if (!LDecl || !RDecl || (LDecl == RDecl))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005354 return QualType();
5355
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005356 do {
John McCallc12c5bb2010-05-15 11:32:37 +00005357 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005358 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005359 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005360 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5361
5362 QualType Result = QualType(LHS, 0);
5363 if (!Protocols.empty())
5364 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5365 Result = getObjCObjectPointerType(Result);
5366 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005367 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005368 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005369
5370 return QualType();
5371}
5372
John McCallc12c5bb2010-05-15 11:32:37 +00005373bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5374 const ObjCObjectType *RHS) {
5375 assert(LHS->getInterface() && "LHS is not an interface type");
5376 assert(RHS->getInterface() && "RHS is not an interface type");
5377
Chris Lattner6ac46a42008-04-07 06:51:04 +00005378 // Verify that the base decls are compatible: the RHS must be a subclass of
5379 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00005380 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00005381 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005382
Chris Lattner6ac46a42008-04-07 06:51:04 +00005383 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5384 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00005385 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00005386 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005387
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005388 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5389 // more detailed analysis is required.
5390 if (RHS->getNumProtocols() == 0) {
5391 // OK, if LHS is a superclass of RHS *and*
5392 // this superclass is assignment compatible with LHS.
5393 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005394 bool IsSuperClass =
5395 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5396 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005397 // OK if conversion of LHS to SuperClass results in narrowing of types
5398 // ; i.e., SuperClass may implement at least one of the protocols
5399 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5400 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5401 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005402 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005403 // If super class has no protocols, it is not a match.
5404 if (SuperClassInheritedProtocols.empty())
5405 return false;
5406
5407 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5408 LHSPE = LHS->qual_end();
5409 LHSPI != LHSPE; LHSPI++) {
5410 bool SuperImplementsProtocol = false;
5411 ObjCProtocolDecl *LHSProto = (*LHSPI);
5412
5413 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5414 SuperClassInheritedProtocols.begin(),
5415 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5416 ObjCProtocolDecl *SuperClassProto = (*I);
5417 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5418 SuperImplementsProtocol = true;
5419 break;
5420 }
5421 }
5422 if (!SuperImplementsProtocol)
5423 return false;
5424 }
5425 return true;
5426 }
5427 return false;
5428 }
Mike Stump1eb44332009-09-09 15:08:12 +00005429
John McCallc12c5bb2010-05-15 11:32:37 +00005430 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5431 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005432 LHSPI != LHSPE; LHSPI++) {
5433 bool RHSImplementsProtocol = false;
5434
5435 // If the RHS doesn't implement the protocol on the left, the types
5436 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00005437 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5438 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00005439 RHSPI != RHSPE; RHSPI++) {
5440 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005441 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00005442 break;
5443 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005444 }
5445 // FIXME: For better diagnostics, consider passing back the protocol name.
5446 if (!RHSImplementsProtocol)
5447 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005448 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005449 // The RHS implements all protocols listed on the LHS.
5450 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005451}
5452
Steve Naroff389bf462009-02-12 17:52:19 +00005453bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5454 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00005455 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5456 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005457
Steve Naroff14108da2009-07-10 23:34:53 +00005458 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00005459 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005460
5461 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5462 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00005463}
5464
Douglas Gregor569c3162010-08-07 11:51:51 +00005465bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5466 return canAssignObjCInterfaces(
5467 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5468 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5469}
5470
Mike Stump1eb44332009-09-09 15:08:12 +00005471/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00005472/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00005473/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00005474/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00005475bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5476 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005477 if (getLangOptions().CPlusPlus)
5478 return hasSameType(LHS, RHS);
5479
Douglas Gregor447234d2010-07-29 15:18:02 +00005480 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00005481}
5482
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005483bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00005484 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005485}
5486
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005487bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5488 return !mergeTypes(LHS, RHS, true).isNull();
5489}
5490
Peter Collingbourne48466752010-10-24 18:30:18 +00005491/// mergeTransparentUnionType - if T is a transparent union type and a member
5492/// of T is compatible with SubType, return the merged type, else return
5493/// QualType()
5494QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5495 bool OfBlockPointer,
5496 bool Unqualified) {
5497 if (const RecordType *UT = T->getAsUnionType()) {
5498 RecordDecl *UD = UT->getDecl();
5499 if (UD->hasAttr<TransparentUnionAttr>()) {
5500 for (RecordDecl::field_iterator it = UD->field_begin(),
5501 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00005502 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005503 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5504 if (!MT.isNull())
5505 return MT;
5506 }
5507 }
5508 }
5509
5510 return QualType();
5511}
5512
5513/// mergeFunctionArgumentTypes - merge two types which appear as function
5514/// argument types
5515QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5516 bool OfBlockPointer,
5517 bool Unqualified) {
5518 // GNU extension: two types are compatible if they appear as a function
5519 // argument, one of the types is a transparent union type and the other
5520 // type is compatible with a union member
5521 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5522 Unqualified);
5523 if (!lmerge.isNull())
5524 return lmerge;
5525
5526 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5527 Unqualified);
5528 if (!rmerge.isNull())
5529 return rmerge;
5530
5531 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5532}
5533
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005534QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00005535 bool OfBlockPointer,
5536 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00005537 const FunctionType *lbase = lhs->getAs<FunctionType>();
5538 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00005539 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5540 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00005541 bool allLTypes = true;
5542 bool allRTypes = true;
5543
5544 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005545 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005546 if (OfBlockPointer) {
5547 QualType RHS = rbase->getResultType();
5548 QualType LHS = lbase->getResultType();
5549 bool UnqualifiedResult = Unqualified;
5550 if (!UnqualifiedResult)
5551 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005552 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005553 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005554 else
John McCall8cc246c2010-12-15 01:06:38 +00005555 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5556 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005557 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005558
5559 if (Unqualified)
5560 retType = retType.getUnqualifiedType();
5561
5562 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5563 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5564 if (Unqualified) {
5565 LRetType = LRetType.getUnqualifiedType();
5566 RRetType = RRetType.getUnqualifiedType();
5567 }
5568
5569 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005570 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00005571 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005572 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005573
Daniel Dunbar6a15c852010-04-28 16:20:58 +00005574 // FIXME: double check this
5575 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5576 // rbase->getRegParmAttr() != 0 &&
5577 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00005578 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5579 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00005580
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005581 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00005582 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005583 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005584
John McCall8cc246c2010-12-15 01:06:38 +00005585 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00005586 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5587 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00005588 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5589 return QualType();
5590
John McCallf85e1932011-06-15 23:02:42 +00005591 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5592 return QualType();
5593
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005594 // functypes which return are preferred over those that do not.
5595 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5596 allLTypes = false;
5597 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5598 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005599 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5600 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00005601
John McCallf85e1932011-06-15 23:02:42 +00005602 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00005603
Eli Friedman3d815e72008-08-22 00:56:42 +00005604 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00005605 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5606 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005607 unsigned lproto_nargs = lproto->getNumArgs();
5608 unsigned rproto_nargs = rproto->getNumArgs();
5609
5610 // Compatible functions must have the same number of arguments
5611 if (lproto_nargs != rproto_nargs)
5612 return QualType();
5613
5614 // Variadic and non-variadic functions aren't compatible
5615 if (lproto->isVariadic() != rproto->isVariadic())
5616 return QualType();
5617
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00005618 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5619 return QualType();
5620
Fariborz Jahanian78213e42011-09-28 21:52:05 +00005621 if (LangOpts.ObjCAutoRefCount &&
5622 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5623 return QualType();
5624
Eli Friedman3d815e72008-08-22 00:56:42 +00005625 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00005626 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00005627 for (unsigned i = 0; i < lproto_nargs; i++) {
5628 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5629 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005630 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5631 OfBlockPointer,
5632 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005633 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005634
5635 if (Unqualified)
5636 argtype = argtype.getUnqualifiedType();
5637
Eli Friedman3d815e72008-08-22 00:56:42 +00005638 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00005639 if (Unqualified) {
5640 largtype = largtype.getUnqualifiedType();
5641 rargtype = rargtype.getUnqualifiedType();
5642 }
5643
Chris Lattner61710852008-10-05 17:34:18 +00005644 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5645 allLTypes = false;
5646 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5647 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00005648 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00005649
Eli Friedman3d815e72008-08-22 00:56:42 +00005650 if (allLTypes) return lhs;
5651 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005652
5653 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5654 EPI.ExtInfo = einfo;
5655 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005656 }
5657
5658 if (lproto) allRTypes = false;
5659 if (rproto) allLTypes = false;
5660
Douglas Gregor72564e72009-02-26 23:50:07 +00005661 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00005662 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00005663 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005664 if (proto->isVariadic()) return QualType();
5665 // Check that the types are compatible with the types that
5666 // would result from default argument promotions (C99 6.7.5.3p15).
5667 // The only types actually affected are promotable integer
5668 // types and floats, which would be passed as a different
5669 // type depending on whether the prototype is visible.
5670 unsigned proto_nargs = proto->getNumArgs();
5671 for (unsigned i = 0; i < proto_nargs; ++i) {
5672 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00005673
5674 // Look at the promotion type of enum types, since that is the type used
5675 // to pass enum values.
5676 if (const EnumType *Enum = argTy->getAs<EnumType>())
5677 argTy = Enum->getDecl()->getPromotionType();
5678
Eli Friedman3d815e72008-08-22 00:56:42 +00005679 if (argTy->isPromotableIntegerType() ||
5680 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5681 return QualType();
5682 }
5683
5684 if (allLTypes) return lhs;
5685 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005686
5687 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5688 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00005689 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005690 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005691 }
5692
5693 if (allLTypes) return lhs;
5694 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00005695 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00005696}
5697
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005698QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00005699 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005700 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00005701 // C++ [expr]: If an expression initially has the type "reference to T", the
5702 // type is adjusted to "T" prior to any further analysis, the expression
5703 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005704 // expression is an lvalue unless the reference is an rvalue reference and
5705 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005706 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5707 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00005708
5709 if (Unqualified) {
5710 LHS = LHS.getUnqualifiedType();
5711 RHS = RHS.getUnqualifiedType();
5712 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005713
Eli Friedman3d815e72008-08-22 00:56:42 +00005714 QualType LHSCan = getCanonicalType(LHS),
5715 RHSCan = getCanonicalType(RHS);
5716
5717 // If two types are identical, they are compatible.
5718 if (LHSCan == RHSCan)
5719 return LHS;
5720
John McCall0953e762009-09-24 19:53:00 +00005721 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005722 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5723 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00005724 if (LQuals != RQuals) {
5725 // If any of these qualifiers are different, we have a type
5726 // mismatch.
5727 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00005728 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5729 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00005730 return QualType();
5731
5732 // Exactly one GC qualifier difference is allowed: __strong is
5733 // okay if the other type has no GC qualifier but is an Objective
5734 // C object pointer (i.e. implicitly strong by default). We fix
5735 // this by pretending that the unqualified type was actually
5736 // qualified __strong.
5737 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5738 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5739 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5740
5741 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5742 return QualType();
5743
5744 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5745 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5746 }
5747 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5748 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5749 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005750 return QualType();
John McCall0953e762009-09-24 19:53:00 +00005751 }
5752
5753 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00005754
Eli Friedman852d63b2009-06-01 01:22:52 +00005755 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5756 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00005757
Chris Lattner1adb8832008-01-14 05:45:46 +00005758 // We want to consider the two function types to be the same for these
5759 // comparisons, just force one to the other.
5760 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5761 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00005762
5763 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00005764 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5765 LHSClass = Type::ConstantArray;
5766 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5767 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00005768
John McCallc12c5bb2010-05-15 11:32:37 +00005769 // ObjCInterfaces are just specialized ObjCObjects.
5770 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5771 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5772
Nate Begeman213541a2008-04-18 23:10:10 +00005773 // Canonicalize ExtVector -> Vector.
5774 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5775 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00005776
Chris Lattnera36a61f2008-04-07 05:43:21 +00005777 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005778 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00005779 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00005780 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00005781 // Compatibility is based on the underlying type, not the promotion
5782 // type.
John McCall183700f2009-09-21 23:43:11 +00005783 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005784 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5785 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005786 }
John McCall183700f2009-09-21 23:43:11 +00005787 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005788 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5789 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005790 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005791
Eli Friedman3d815e72008-08-22 00:56:42 +00005792 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005793 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005794
Steve Naroff4a746782008-01-09 22:43:08 +00005795 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005796 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00005797#define TYPE(Class, Base)
5798#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00005799#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00005800#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5801#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5802#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00005803 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00005804
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005805 case Type::LValueReference:
5806 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00005807 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00005808 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00005809
John McCallc12c5bb2010-05-15 11:32:37 +00005810 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00005811 case Type::IncompleteArray:
5812 case Type::VariableArray:
5813 case Type::FunctionProto:
5814 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00005815 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00005816
Chris Lattner1adb8832008-01-14 05:45:46 +00005817 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00005818 {
5819 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005820 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5821 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005822 if (Unqualified) {
5823 LHSPointee = LHSPointee.getUnqualifiedType();
5824 RHSPointee = RHSPointee.getUnqualifiedType();
5825 }
5826 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5827 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005828 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00005829 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005830 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00005831 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005832 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005833 return getPointerType(ResultType);
5834 }
Steve Naroffc0febd52008-12-10 17:49:55 +00005835 case Type::BlockPointer:
5836 {
5837 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005838 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5839 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005840 if (Unqualified) {
5841 LHSPointee = LHSPointee.getUnqualifiedType();
5842 RHSPointee = RHSPointee.getUnqualifiedType();
5843 }
5844 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5845 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00005846 if (ResultType.isNull()) return QualType();
5847 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5848 return LHS;
5849 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5850 return RHS;
5851 return getBlockPointerType(ResultType);
5852 }
Eli Friedmanb001de72011-10-06 23:00:33 +00005853 case Type::Atomic:
5854 {
5855 // Merge two pointer types, while trying to preserve typedef info
5856 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
5857 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
5858 if (Unqualified) {
5859 LHSValue = LHSValue.getUnqualifiedType();
5860 RHSValue = RHSValue.getUnqualifiedType();
5861 }
5862 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
5863 Unqualified);
5864 if (ResultType.isNull()) return QualType();
5865 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
5866 return LHS;
5867 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
5868 return RHS;
5869 return getAtomicType(ResultType);
5870 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005871 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00005872 {
5873 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5874 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5875 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5876 return QualType();
5877
5878 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5879 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005880 if (Unqualified) {
5881 LHSElem = LHSElem.getUnqualifiedType();
5882 RHSElem = RHSElem.getUnqualifiedType();
5883 }
5884
5885 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005886 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00005887 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5888 return LHS;
5889 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5890 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00005891 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5892 ArrayType::ArraySizeModifier(), 0);
5893 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5894 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005895 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5896 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00005897 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5898 return LHS;
5899 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5900 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005901 if (LVAT) {
5902 // FIXME: This isn't correct! But tricky to implement because
5903 // the array's size has to be the size of LHS, but the type
5904 // has to be different.
5905 return LHS;
5906 }
5907 if (RVAT) {
5908 // FIXME: This isn't correct! But tricky to implement because
5909 // the array's size has to be the size of RHS, but the type
5910 // has to be different.
5911 return RHS;
5912 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00005913 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5914 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00005915 return getIncompleteArrayType(ResultType,
5916 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005917 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005918 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00005919 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00005920 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00005921 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00005922 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00005923 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005924 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00005925 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00005926 case Type::Complex:
5927 // Distinct complex types are incompatible.
5928 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005929 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005930 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00005931 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5932 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005933 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00005934 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00005935 case Type::ObjCObject: {
5936 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005937 // FIXME: This should be type compatibility, e.g. whether
5938 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00005939 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5940 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5941 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00005942 return LHS;
5943
Eli Friedman3d815e72008-08-22 00:56:42 +00005944 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00005945 }
Steve Naroff14108da2009-07-10 23:34:53 +00005946 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005947 if (OfBlockPointer) {
5948 if (canAssignObjCInterfacesInBlockPointer(
5949 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005950 RHS->getAs<ObjCObjectPointerType>(),
5951 BlockReturnType))
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005952 return LHS;
5953 return QualType();
5954 }
John McCall183700f2009-09-21 23:43:11 +00005955 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5956 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00005957 return LHS;
5958
Steve Naroffbc76dd02008-12-10 22:14:21 +00005959 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005960 }
Steve Naroffec0550f2007-10-15 20:41:53 +00005961 }
Douglas Gregor72564e72009-02-26 23:50:07 +00005962
5963 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005964}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00005965
Fariborz Jahanian78213e42011-09-28 21:52:05 +00005966bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
5967 const FunctionProtoType *FromFunctionType,
5968 const FunctionProtoType *ToFunctionType) {
5969 if (FromFunctionType->hasAnyConsumedArgs() !=
5970 ToFunctionType->hasAnyConsumedArgs())
5971 return false;
5972 FunctionProtoType::ExtProtoInfo FromEPI =
5973 FromFunctionType->getExtProtoInfo();
5974 FunctionProtoType::ExtProtoInfo ToEPI =
5975 ToFunctionType->getExtProtoInfo();
5976 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
5977 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
5978 ArgIdx != NumArgs; ++ArgIdx) {
5979 if (FromEPI.ConsumedArguments[ArgIdx] !=
5980 ToEPI.ConsumedArguments[ArgIdx])
5981 return false;
5982 }
5983 return true;
5984}
5985
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005986/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5987/// 'RHS' attributes and returns the merged version; including for function
5988/// return types.
5989QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5990 QualType LHSCan = getCanonicalType(LHS),
5991 RHSCan = getCanonicalType(RHS);
5992 // If two types are identical, they are compatible.
5993 if (LHSCan == RHSCan)
5994 return LHS;
5995 if (RHSCan->isFunctionType()) {
5996 if (!LHSCan->isFunctionType())
5997 return QualType();
5998 QualType OldReturnType =
5999 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6000 QualType NewReturnType =
6001 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6002 QualType ResReturnType =
6003 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6004 if (ResReturnType.isNull())
6005 return QualType();
6006 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6007 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6008 // In either case, use OldReturnType to build the new function type.
6009 const FunctionType *F = LHS->getAs<FunctionType>();
6010 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00006011 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6012 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006013 QualType ResultType
6014 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006015 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006016 return ResultType;
6017 }
6018 }
6019 return QualType();
6020 }
6021
6022 // If the qualifiers are different, the types can still be merged.
6023 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6024 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6025 if (LQuals != RQuals) {
6026 // If any of these qualifiers are different, we have a type mismatch.
6027 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6028 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6029 return QualType();
6030
6031 // Exactly one GC qualifier difference is allowed: __strong is
6032 // okay if the other type has no GC qualifier but is an Objective
6033 // C object pointer (i.e. implicitly strong by default). We fix
6034 // this by pretending that the unqualified type was actually
6035 // qualified __strong.
6036 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6037 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6038 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6039
6040 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6041 return QualType();
6042
6043 if (GC_L == Qualifiers::Strong)
6044 return LHS;
6045 if (GC_R == Qualifiers::Strong)
6046 return RHS;
6047 return QualType();
6048 }
6049
6050 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6051 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6052 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6053 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6054 if (ResQT == LHSBaseQT)
6055 return LHS;
6056 if (ResQT == RHSBaseQT)
6057 return RHS;
6058 }
6059 return QualType();
6060}
6061
Chris Lattner5426bf62008-04-07 07:01:58 +00006062//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00006063// Integer Predicates
6064//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00006065
Jay Foad4ba2a172011-01-12 09:06:06 +00006066unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00006067 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00006068 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006069 if (T->isBooleanType())
6070 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00006071 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00006072 return (unsigned)getTypeSize(T);
6073}
6074
6075QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00006076 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00006077
6078 // Turn <4 x signed int> -> <4 x unsigned int>
6079 if (const VectorType *VTy = T->getAs<VectorType>())
6080 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00006081 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00006082
6083 // For enums, we return the unsigned version of the base type.
6084 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00006085 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00006086
6087 const BuiltinType *BTy = T->getAs<BuiltinType>();
6088 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006089 switch (BTy->getKind()) {
6090 case BuiltinType::Char_S:
6091 case BuiltinType::SChar:
6092 return UnsignedCharTy;
6093 case BuiltinType::Short:
6094 return UnsignedShortTy;
6095 case BuiltinType::Int:
6096 return UnsignedIntTy;
6097 case BuiltinType::Long:
6098 return UnsignedLongTy;
6099 case BuiltinType::LongLong:
6100 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00006101 case BuiltinType::Int128:
6102 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00006103 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00006104 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006105 }
6106}
6107
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00006108ASTMutationListener::~ASTMutationListener() { }
6109
Chris Lattner86df27b2009-06-14 00:45:47 +00006110
6111//===----------------------------------------------------------------------===//
6112// Builtin Type Computation
6113//===----------------------------------------------------------------------===//
6114
6115/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00006116/// pointer over the consumed characters. This returns the resultant type. If
6117/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6118/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6119/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00006120///
6121/// RequiresICE is filled in on return to indicate whether the value is required
6122/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00006123static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00006124 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00006125 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00006126 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00006127 // Modifiers.
6128 int HowLong = 0;
6129 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00006130 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006131
Chris Lattner33daae62010-10-01 22:42:38 +00006132 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00006133 bool Done = false;
6134 while (!Done) {
6135 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00006136 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006137 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00006138 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006139 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006140 case 'S':
6141 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6142 assert(!Signed && "Can't use 'S' modifier multiple times!");
6143 Signed = true;
6144 break;
6145 case 'U':
6146 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6147 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6148 Unsigned = true;
6149 break;
6150 case 'L':
6151 assert(HowLong <= 2 && "Can't have LLLL modifier");
6152 ++HowLong;
6153 break;
6154 }
6155 }
6156
6157 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00006158
Chris Lattner86df27b2009-06-14 00:45:47 +00006159 // Read the base type.
6160 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00006161 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00006162 case 'v':
6163 assert(HowLong == 0 && !Signed && !Unsigned &&
6164 "Bad modifiers used with 'v'!");
6165 Type = Context.VoidTy;
6166 break;
6167 case 'f':
6168 assert(HowLong == 0 && !Signed && !Unsigned &&
6169 "Bad modifiers used with 'f'!");
6170 Type = Context.FloatTy;
6171 break;
6172 case 'd':
6173 assert(HowLong < 2 && !Signed && !Unsigned &&
6174 "Bad modifiers used with 'd'!");
6175 if (HowLong)
6176 Type = Context.LongDoubleTy;
6177 else
6178 Type = Context.DoubleTy;
6179 break;
6180 case 's':
6181 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6182 if (Unsigned)
6183 Type = Context.UnsignedShortTy;
6184 else
6185 Type = Context.ShortTy;
6186 break;
6187 case 'i':
6188 if (HowLong == 3)
6189 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6190 else if (HowLong == 2)
6191 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6192 else if (HowLong == 1)
6193 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6194 else
6195 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6196 break;
6197 case 'c':
6198 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6199 if (Signed)
6200 Type = Context.SignedCharTy;
6201 else if (Unsigned)
6202 Type = Context.UnsignedCharTy;
6203 else
6204 Type = Context.CharTy;
6205 break;
6206 case 'b': // boolean
6207 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6208 Type = Context.BoolTy;
6209 break;
6210 case 'z': // size_t.
6211 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6212 Type = Context.getSizeType();
6213 break;
6214 case 'F':
6215 Type = Context.getCFConstantStringType();
6216 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00006217 case 'G':
6218 Type = Context.getObjCIdType();
6219 break;
6220 case 'H':
6221 Type = Context.getObjCSelType();
6222 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006223 case 'a':
6224 Type = Context.getBuiltinVaListType();
6225 assert(!Type.isNull() && "builtin va list type not initialized!");
6226 break;
6227 case 'A':
6228 // This is a "reference" to a va_list; however, what exactly
6229 // this means depends on how va_list is defined. There are two
6230 // different kinds of va_list: ones passed by value, and ones
6231 // passed by reference. An example of a by-value va_list is
6232 // x86, where va_list is a char*. An example of by-ref va_list
6233 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6234 // we want this argument to be a char*&; for x86-64, we want
6235 // it to be a __va_list_tag*.
6236 Type = Context.getBuiltinVaListType();
6237 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00006238 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00006239 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00006240 else
Chris Lattner86df27b2009-06-14 00:45:47 +00006241 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00006242 break;
6243 case 'V': {
6244 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00006245 unsigned NumElements = strtoul(Str, &End, 10);
6246 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00006247 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00006248
Chris Lattner14e0e742010-10-01 22:53:11 +00006249 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6250 RequiresICE, false);
6251 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00006252
6253 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00006254 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00006255 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00006256 break;
6257 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00006258 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00006259 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6260 false);
6261 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00006262 Type = Context.getComplexType(ElementType);
6263 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00006264 }
6265 case 'Y' : {
6266 Type = Context.getPointerDiffType();
6267 break;
6268 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006269 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00006270 Type = Context.getFILEType();
6271 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006272 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00006273 return QualType();
6274 }
Mike Stumpfd612db2009-07-28 23:47:15 +00006275 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006276 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00006277 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00006278 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00006279 else
6280 Type = Context.getjmp_bufType();
6281
Mike Stumpfd612db2009-07-28 23:47:15 +00006282 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006283 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00006284 return QualType();
6285 }
6286 break;
Mike Stump782fa302009-07-28 02:25:19 +00006287 }
Mike Stump1eb44332009-09-09 15:08:12 +00006288
Chris Lattner33daae62010-10-01 22:42:38 +00006289 // If there are modifiers and if we're allowed to parse them, go for it.
6290 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00006291 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00006292 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00006293 default: Done = true; --Str; break;
6294 case '*':
6295 case '&': {
6296 // Both pointers and references can have their pointee types
6297 // qualified with an address space.
6298 char *End;
6299 unsigned AddrSpace = strtoul(Str, &End, 10);
6300 if (End != Str && AddrSpace != 0) {
6301 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6302 Str = End;
6303 }
6304 if (c == '*')
6305 Type = Context.getPointerType(Type);
6306 else
6307 Type = Context.getLValueReferenceType(Type);
6308 break;
6309 }
6310 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6311 case 'C':
6312 Type = Type.withConst();
6313 break;
6314 case 'D':
6315 Type = Context.getVolatileType(Type);
6316 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006317 }
6318 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00006319
Chris Lattner14e0e742010-10-01 22:53:11 +00006320 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00006321 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00006322
Chris Lattner86df27b2009-06-14 00:45:47 +00006323 return Type;
6324}
6325
6326/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00006327QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00006328 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00006329 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00006330 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00006331
Chris Lattner5f9e2722011-07-23 10:55:15 +00006332 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00006333
Chris Lattner14e0e742010-10-01 22:53:11 +00006334 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00006335 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00006336 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6337 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006338 if (Error != GE_None)
6339 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00006340
6341 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6342
Chris Lattner86df27b2009-06-14 00:45:47 +00006343 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00006344 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006345 if (Error != GE_None)
6346 return QualType();
6347
Chris Lattner14e0e742010-10-01 22:53:11 +00006348 // If this argument is required to be an IntegerConstantExpression and the
6349 // caller cares, fill in the bitmask we return.
6350 if (RequiresICE && IntegerConstantArgs)
6351 *IntegerConstantArgs |= 1 << ArgTypes.size();
6352
Chris Lattner86df27b2009-06-14 00:45:47 +00006353 // Do array -> pointer decay. The builtin should use the decayed type.
6354 if (Ty->isArrayType())
6355 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00006356
Chris Lattner86df27b2009-06-14 00:45:47 +00006357 ArgTypes.push_back(Ty);
6358 }
6359
6360 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6361 "'.' should only occur at end of builtin type list!");
6362
John McCall00ccbef2010-12-21 00:44:39 +00006363 FunctionType::ExtInfo EI;
6364 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6365
6366 bool Variadic = (TypeStr[0] == '.');
6367
6368 // We really shouldn't be making a no-proto type here, especially in C++.
6369 if (ArgTypes.empty() && Variadic)
6370 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00006371
John McCalle23cf432010-12-14 08:05:40 +00006372 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00006373 EPI.ExtInfo = EI;
6374 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00006375
6376 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00006377}
Eli Friedmana95d7572009-08-19 07:44:53 +00006378
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006379GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6380 GVALinkage External = GVA_StrongExternal;
6381
6382 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006383 switch (L) {
6384 case NoLinkage:
6385 case InternalLinkage:
6386 case UniqueExternalLinkage:
6387 return GVA_Internal;
6388
6389 case ExternalLinkage:
6390 switch (FD->getTemplateSpecializationKind()) {
6391 case TSK_Undeclared:
6392 case TSK_ExplicitSpecialization:
6393 External = GVA_StrongExternal;
6394 break;
6395
6396 case TSK_ExplicitInstantiationDefinition:
6397 return GVA_ExplicitTemplateInstantiation;
6398
6399 case TSK_ExplicitInstantiationDeclaration:
6400 case TSK_ImplicitInstantiation:
6401 External = GVA_TemplateInstantiation;
6402 break;
6403 }
6404 }
6405
6406 if (!FD->isInlined())
6407 return External;
6408
6409 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6410 // GNU or C99 inline semantics. Determine whether this symbol should be
6411 // externally visible.
6412 if (FD->isInlineDefinitionExternallyVisible())
6413 return External;
6414
6415 // C99 inline semantics, where the symbol is not externally visible.
6416 return GVA_C99Inline;
6417 }
6418
6419 // C++0x [temp.explicit]p9:
6420 // [ Note: The intent is that an inline function that is the subject of
6421 // an explicit instantiation declaration will still be implicitly
6422 // instantiated when used so that the body can be considered for
6423 // inlining, but that no out-of-line copy of the inline function would be
6424 // generated in the translation unit. -- end note ]
6425 if (FD->getTemplateSpecializationKind()
6426 == TSK_ExplicitInstantiationDeclaration)
6427 return GVA_C99Inline;
6428
6429 return GVA_CXXInline;
6430}
6431
6432GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6433 // If this is a static data member, compute the kind of template
6434 // specialization. Otherwise, this variable is not part of a
6435 // template.
6436 TemplateSpecializationKind TSK = TSK_Undeclared;
6437 if (VD->isStaticDataMember())
6438 TSK = VD->getTemplateSpecializationKind();
6439
6440 Linkage L = VD->getLinkage();
6441 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6442 VD->getType()->getLinkage() == UniqueExternalLinkage)
6443 L = UniqueExternalLinkage;
6444
6445 switch (L) {
6446 case NoLinkage:
6447 case InternalLinkage:
6448 case UniqueExternalLinkage:
6449 return GVA_Internal;
6450
6451 case ExternalLinkage:
6452 switch (TSK) {
6453 case TSK_Undeclared:
6454 case TSK_ExplicitSpecialization:
6455 return GVA_StrongExternal;
6456
6457 case TSK_ExplicitInstantiationDeclaration:
6458 llvm_unreachable("Variable should not be instantiated");
6459 // Fall through to treat this like any other instantiation.
6460
6461 case TSK_ExplicitInstantiationDefinition:
6462 return GVA_ExplicitTemplateInstantiation;
6463
6464 case TSK_ImplicitInstantiation:
6465 return GVA_TemplateInstantiation;
6466 }
6467 }
6468
6469 return GVA_StrongExternal;
6470}
6471
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00006472bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006473 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6474 if (!VD->isFileVarDecl())
6475 return false;
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00006476 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006477 return false;
6478
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006479 // Weak references don't produce any output by themselves.
6480 if (D->hasAttr<WeakRefAttr>())
6481 return false;
6482
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006483 // Aliases and used decls are required.
6484 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6485 return true;
6486
6487 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6488 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00006489 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00006490 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006491
6492 // Constructors and destructors are required.
6493 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6494 return true;
6495
6496 // The key function for a class is required.
6497 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6498 const CXXRecordDecl *RD = MD->getParent();
6499 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6500 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6501 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6502 return true;
6503 }
6504 }
6505
6506 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6507
6508 // static, static inline, always_inline, and extern inline functions can
6509 // always be deferred. Normal inline functions can be deferred in C99/C++.
6510 // Implicit template instantiations can also be deferred in C++.
6511 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6512 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6513 return false;
6514 return true;
6515 }
Douglas Gregor94da1582011-09-10 00:22:34 +00006516
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006517 const VarDecl *VD = cast<VarDecl>(D);
6518 assert(VD->isFileVarDecl() && "Expected file scoped var");
6519
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006520 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6521 return false;
6522
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006523 // Structs that have non-trivial constructors or destructors are required.
6524
6525 // FIXME: Handle references.
Sean Hunt023df372011-05-09 18:22:59 +00006526 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006527 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6528 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Sean Hunt023df372011-05-09 18:22:59 +00006529 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6530 RD->hasTrivialCopyConstructor() &&
6531 RD->hasTrivialMoveConstructor() &&
6532 RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006533 return true;
6534 }
6535 }
6536
6537 GVALinkage L = GetGVALinkageForVariable(VD);
6538 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6539 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6540 return false;
6541 }
6542
6543 return true;
6544}
Charles Davis071cc7d2010-08-16 03:33:14 +00006545
Charles Davisee743f92010-11-09 18:04:24 +00006546CallingConv ASTContext::getDefaultMethodCallConv() {
6547 // Pass through to the C++ ABI object
6548 return ABI->getDefaultMethodCallConv();
6549}
6550
Jay Foad4ba2a172011-01-12 09:06:06 +00006551bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00006552 // Pass through to the C++ ABI object
6553 return ABI->isNearlyEmpty(RD);
6554}
6555
Peter Collingbourne14110472011-01-13 18:57:25 +00006556MangleContext *ASTContext::createMangleContext() {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00006557 switch (Target->getCXXABI()) {
Peter Collingbourne14110472011-01-13 18:57:25 +00006558 case CXXABI_ARM:
6559 case CXXABI_Itanium:
6560 return createItaniumMangleContext(*this, getDiagnostics());
6561 case CXXABI_Microsoft:
6562 return createMicrosoftMangleContext(*this, getDiagnostics());
6563 }
David Blaikieb219cfc2011-09-23 05:06:16 +00006564 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00006565}
6566
Charles Davis071cc7d2010-08-16 03:33:14 +00006567CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00006568
6569size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00006570 return ASTRecordLayouts.getMemorySize()
6571 + llvm::capacity_in_bytes(ObjCLayouts)
6572 + llvm::capacity_in_bytes(KeyFunctions)
6573 + llvm::capacity_in_bytes(ObjCImpls)
6574 + llvm::capacity_in_bytes(BlockVarCopyInits)
6575 + llvm::capacity_in_bytes(DeclAttrs)
6576 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6577 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6578 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6579 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6580 + llvm::capacity_in_bytes(OverriddenMethods)
6581 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00006582 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00006583 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00006584}
Ted Kremenekd211cb72011-10-06 05:00:56 +00006585
6586void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6587 ParamIndices[D] = index;
6588}
6589
6590unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6591 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6592 assert(I != ParamIndices.end() &&
6593 "ParmIndices lacks entry set by ParmVarDecl");
6594 return I->second;
6595}