blob: 2e898f188e562a8cdc0b578378ae6cbb3cc23ae8 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCallea1471e2010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +000033#include "llvm/Support/Capacity.h"
Charles Davis071cc7d2010-08-16 03:33:14 +000034#include "CXXABI.h"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000035#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000036
Reid Spencer5f016e22007-07-11 17:01:13 +000037using namespace clang;
38
Douglas Gregor18274032010-07-03 00:47:00 +000039unsigned ASTContext::NumImplicitDefaultConstructors;
40unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000041unsigned ASTContext::NumImplicitCopyConstructors;
42unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000043unsigned ASTContext::NumImplicitMoveConstructors;
44unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000045unsigned ASTContext::NumImplicitCopyAssignmentOperators;
46unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000047unsigned ASTContext::NumImplicitMoveAssignmentOperators;
48unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000049unsigned ASTContext::NumImplicitDestructors;
50unsigned ASTContext::NumImplicitDestructorsDeclared;
51
Reid Spencer5f016e22007-07-11 17:01:13 +000052enum FloatingRank {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +000053 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Reid Spencer5f016e22007-07-11 17:01:13 +000054};
55
Douglas Gregor3e1274f2010-06-16 21:09:37 +000056void
57ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
58 TemplateTemplateParmDecl *Parm) {
59 ID.AddInteger(Parm->getDepth());
60 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +000061 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000062
63 TemplateParameterList *Params = Parm->getTemplateParameters();
64 ID.AddInteger(Params->size());
65 for (TemplateParameterList::const_iterator P = Params->begin(),
66 PEnd = Params->end();
67 P != PEnd; ++P) {
68 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
69 ID.AddInteger(0);
70 ID.AddBoolean(TTP->isParameterPack());
71 continue;
72 }
73
74 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
75 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +000076 ID.AddBoolean(NTTP->isParameterPack());
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),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000230 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
231 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
232 cudaConfigureCallDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000233 NullTypeSourceInfo(QualType()),
234 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000235 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000236 Idents(idents), Selectors(sels),
237 BuiltinInfo(builtins),
238 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000239 ExternalSource(0), Listener(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000240 LastSDM(0, 0),
241 UniqueBlockByRefTypeID(0)
242{
Mike Stump1eb44332009-09-09 15:08:12 +0000243 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000244 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000245
246 if (!DelayInitialization) {
247 assert(t && "No target supplied for ASTContext initialization");
248 InitBuiltinTypes(*t);
249 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000250}
251
Reid Spencer5f016e22007-07-11 17:01:13 +0000252ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000253 // Release the DenseMaps associated with DeclContext objects.
254 // FIXME: Is this the ideal solution?
255 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000256
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000257 // Call all of the deallocation functions.
258 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
259 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000260
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000261 // Release all of the memory associated with overridden C++ methods.
262 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
263 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
264 OM != OMEnd; ++OM)
265 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +0000266
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000267 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000268 // because they can contain DenseMaps.
269 for (llvm::DenseMap<const ObjCContainerDecl*,
270 const ASTRecordLayout*>::iterator
271 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
272 // Increment in loop to prevent using deallocated memory.
273 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
274 R->Destroy(*this);
275
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000276 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
277 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
278 // Increment in loop to prevent using deallocated memory.
279 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
280 R->Destroy(*this);
281 }
Douglas Gregor63200642010-08-30 16:49:28 +0000282
283 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
284 AEnd = DeclAttrs.end();
285 A != AEnd; ++A)
286 A->second->~AttrVec();
287}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000288
Douglas Gregor00545312010-05-23 18:26:36 +0000289void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
290 Deallocations.push_back(std::make_pair(Callback, Data));
291}
292
Mike Stump1eb44332009-09-09 15:08:12 +0000293void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000294ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
295 ExternalSource.reset(Source.take());
296}
297
Reid Spencer5f016e22007-07-11 17:01:13 +0000298void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000299 llvm::errs() << "\n*** AST Context Stats:\n";
300 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000301
Douglas Gregordbe833d2009-05-26 14:40:08 +0000302 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000303#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000304#define ABSTRACT_TYPE(Name, Parent)
305#include "clang/AST/TypeNodes.def"
306 0 // Extra
307 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000308
Reid Spencer5f016e22007-07-11 17:01:13 +0000309 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
310 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000311 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000312 }
313
Douglas Gregordbe833d2009-05-26 14:40:08 +0000314 unsigned Idx = 0;
315 unsigned TotalBytes = 0;
316#define TYPE(Name, Parent) \
317 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000318 llvm::errs() << " " << counts[Idx] << " " << #Name \
319 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000320 TotalBytes += counts[Idx] * sizeof(Name##Type); \
321 ++Idx;
322#define ABSTRACT_TYPE(Name, Parent)
323#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000324
Chandler Carruthcd92a652011-07-04 05:32:14 +0000325 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
326
Douglas Gregor4923aa22010-07-02 20:37:36 +0000327 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000328 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
329 << NumImplicitDefaultConstructors
330 << " implicit default constructors created\n";
331 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
332 << NumImplicitCopyConstructors
333 << " implicit copy constructors created\n";
Sean Huntffe37fd2011-05-25 20:50:04 +0000334 if (getLangOptions().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000335 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
336 << NumImplicitMoveConstructors
337 << " implicit move constructors created\n";
338 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
339 << NumImplicitCopyAssignmentOperators
340 << " implicit copy assignment operators created\n";
Sean Huntffe37fd2011-05-25 20:50:04 +0000341 if (getLangOptions().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000342 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
343 << NumImplicitMoveAssignmentOperators
344 << " implicit move assignment operators created\n";
345 llvm::errs() << NumImplicitDestructorsDeclared << "/"
346 << NumImplicitDestructors
347 << " implicit destructors created\n";
348
Douglas Gregor2cf26342009-04-09 22:27:44 +0000349 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000350 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000351 ExternalSource->PrintStats();
352 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000353
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000354 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000355}
356
Douglas Gregor772eeae2011-08-12 06:49:56 +0000357TypedefDecl *ASTContext::getInt128Decl() const {
358 if (!Int128Decl) {
359 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
360 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
361 getTranslationUnitDecl(),
362 SourceLocation(),
363 SourceLocation(),
364 &Idents.get("__int128_t"),
365 TInfo);
366 }
367
368 return Int128Decl;
369}
370
371TypedefDecl *ASTContext::getUInt128Decl() const {
372 if (!UInt128Decl) {
373 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
374 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
375 getTranslationUnitDecl(),
376 SourceLocation(),
377 SourceLocation(),
378 &Idents.get("__uint128_t"),
379 TInfo);
380 }
381
382 return UInt128Decl;
383}
Reid Spencer5f016e22007-07-11 17:01:13 +0000384
John McCalle27ec8a2009-10-23 23:03:21 +0000385void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000386 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000387 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000388 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000389}
390
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000391void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
392 assert((!this->Target || this->Target == &Target) &&
393 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000394 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000396 this->Target = &Target;
397
398 ABI.reset(createCXXABI(Target));
399 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
400
Reid Spencer5f016e22007-07-11 17:01:13 +0000401 // C99 6.2.5p19.
402 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Reid Spencer5f016e22007-07-11 17:01:13 +0000404 // C99 6.2.5p2.
405 InitBuiltinType(BoolTy, BuiltinType::Bool);
406 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000407 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000408 InitBuiltinType(CharTy, BuiltinType::Char_S);
409 else
410 InitBuiltinType(CharTy, BuiltinType::Char_U);
411 // C99 6.2.5p4.
412 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
413 InitBuiltinType(ShortTy, BuiltinType::Short);
414 InitBuiltinType(IntTy, BuiltinType::Int);
415 InitBuiltinType(LongTy, BuiltinType::Long);
416 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Reid Spencer5f016e22007-07-11 17:01:13 +0000418 // C99 6.2.5p6.
419 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
420 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
421 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
422 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
423 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Reid Spencer5f016e22007-07-11 17:01:13 +0000425 // C99 6.2.5p10.
426 InitBuiltinType(FloatTy, BuiltinType::Float);
427 InitBuiltinType(DoubleTy, BuiltinType::Double);
428 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000429
Chris Lattner2df9ced2009-04-30 02:43:43 +0000430 // GNU extension, 128-bit integers.
431 InitBuiltinType(Int128Ty, BuiltinType::Int128);
432 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
433
Chris Lattner3f59c972010-12-25 23:25:43 +0000434 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedmand3d77cd2011-04-30 19:24:24 +0000435 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattner3f59c972010-12-25 23:25:43 +0000436 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
437 else // -fshort-wchar makes wchar_t be unsigned.
438 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
439 } else // C99
Chris Lattner3a250322009-02-26 23:43:47 +0000440 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000441
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000442 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
443 InitBuiltinType(Char16Ty, BuiltinType::Char16);
444 else // C99
445 Char16Ty = getFromTargetType(Target.getChar16Type());
446
447 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
448 InitBuiltinType(Char32Ty, BuiltinType::Char32);
449 else // C99
450 Char32Ty = getFromTargetType(Target.getChar32Type());
451
Douglas Gregor898574e2008-12-05 23:32:09 +0000452 // Placeholder type for type-dependent expressions whose type is
453 // completely unknown. No code should ever check a type against
454 // DependentTy and users should never see it; however, it is here to
455 // help diagnose failures to properly check for type-dependent
456 // expressions.
457 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000458
John McCall2a984ca2010-10-12 00:20:44 +0000459 // Placeholder type for functions.
460 InitBuiltinType(OverloadTy, BuiltinType::Overload);
461
John McCall864c0412011-04-26 20:42:42 +0000462 // Placeholder type for bound members.
463 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
464
John McCall3c3b7f92011-10-25 17:37:35 +0000465 // Placeholder type for pseudo-objects.
466 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
467
John McCall1de4d4e2011-04-07 08:22:57 +0000468 // "any" type; useful for debugger-like clients.
469 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
470
John McCall0ddaeb92011-10-17 18:09:15 +0000471 // Placeholder type for unbridged ARC casts.
472 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
473
Reid Spencer5f016e22007-07-11 17:01:13 +0000474 // C99 6.2.5p11.
475 FloatComplexTy = getComplexType(FloatTy);
476 DoubleComplexTy = getComplexType(DoubleTy);
477 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000478
Steve Naroff7e219e42007-10-15 14:41:52 +0000479 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000481 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000482 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
483 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000484 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000485
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000486 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000487
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000488 // void * type
489 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000490
491 // nullptr type (C++0x 2.14.7)
492 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000493
494 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
495 InitBuiltinType(HalfTy, BuiltinType::Half);
Reid Spencer5f016e22007-07-11 17:01:13 +0000496}
497
David Blaikied6471f72011-09-25 23:23:43 +0000498DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000499 return SourceMgr.getDiagnostics();
500}
501
Douglas Gregor63200642010-08-30 16:49:28 +0000502AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
503 AttrVec *&Result = DeclAttrs[D];
504 if (!Result) {
505 void *Mem = Allocate(sizeof(AttrVec));
506 Result = new (Mem) AttrVec;
507 }
508
509 return *Result;
510}
511
512/// \brief Erase the attributes corresponding to the given declaration.
513void ASTContext::eraseDeclAttrs(const Decl *D) {
514 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
515 if (Pos != DeclAttrs.end()) {
516 Pos->second->~AttrVec();
517 DeclAttrs.erase(Pos);
518 }
519}
520
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000521MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000522ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000523 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000524 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000525 = InstantiatedFromStaticDataMember.find(Var);
526 if (Pos == InstantiatedFromStaticDataMember.end())
527 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Douglas Gregor7caa6822009-07-24 20:34:43 +0000529 return Pos->second;
530}
531
Mike Stump1eb44332009-09-09 15:08:12 +0000532void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000533ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000534 TemplateSpecializationKind TSK,
535 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000536 assert(Inst->isStaticDataMember() && "Not a static data member");
537 assert(Tmpl->isStaticDataMember() && "Not a static data member");
538 assert(!InstantiatedFromStaticDataMember[Inst] &&
539 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000540 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000541 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000542}
543
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000544FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
545 const FunctionDecl *FD){
546 assert(FD && "Specialization is 0");
547 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000548 = ClassScopeSpecializationPattern.find(FD);
549 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000550 return 0;
551
552 return Pos->second;
553}
554
555void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
556 FunctionDecl *Pattern) {
557 assert(FD && "Specialization is 0");
558 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000559 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000560}
561
John McCall7ba107a2009-11-18 02:36:19 +0000562NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000563ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000564 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000565 = InstantiatedFromUsingDecl.find(UUD);
566 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000567 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Anders Carlsson0d8df782009-08-29 19:37:28 +0000569 return Pos->second;
570}
571
572void
John McCalled976492009-12-04 22:46:56 +0000573ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
574 assert((isa<UsingDecl>(Pattern) ||
575 isa<UnresolvedUsingValueDecl>(Pattern) ||
576 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
577 "pattern decl is not a using decl");
578 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
579 InstantiatedFromUsingDecl[Inst] = Pattern;
580}
581
582UsingShadowDecl *
583ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
584 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
585 = InstantiatedFromUsingShadowDecl.find(Inst);
586 if (Pos == InstantiatedFromUsingShadowDecl.end())
587 return 0;
588
589 return Pos->second;
590}
591
592void
593ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
594 UsingShadowDecl *Pattern) {
595 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
596 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000597}
598
Anders Carlssond8b285f2009-09-01 04:26:58 +0000599FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
600 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
601 = InstantiatedFromUnnamedFieldDecl.find(Field);
602 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
603 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000604
Anders Carlssond8b285f2009-09-01 04:26:58 +0000605 return Pos->second;
606}
607
608void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
609 FieldDecl *Tmpl) {
610 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
611 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
612 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
613 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000614
Anders Carlssond8b285f2009-09-01 04:26:58 +0000615 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
616}
617
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000618bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
619 const FieldDecl *LastFD) const {
620 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000621 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000622}
623
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000624bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
625 const FieldDecl *LastFD) const {
626 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000627 FD->getBitWidthValue(*this) == 0 &&
628 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000629}
630
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000631bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
632 const FieldDecl *LastFD) const {
633 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000634 FD->getBitWidthValue(*this) &&
635 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000636}
637
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000638bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000639 const FieldDecl *LastFD) const {
640 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000641 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000642}
643
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000644bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000645 const FieldDecl *LastFD) const {
646 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000647 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000648}
649
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000650ASTContext::overridden_cxx_method_iterator
651ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
652 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
653 = OverriddenMethods.find(Method);
654 if (Pos == OverriddenMethods.end())
655 return 0;
656
657 return Pos->second.begin();
658}
659
660ASTContext::overridden_cxx_method_iterator
661ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
662 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
663 = OverriddenMethods.find(Method);
664 if (Pos == OverriddenMethods.end())
665 return 0;
666
667 return Pos->second.end();
668}
669
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000670unsigned
671ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
672 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
673 = OverriddenMethods.find(Method);
674 if (Pos == OverriddenMethods.end())
675 return 0;
676
677 return Pos->second.size();
678}
679
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000680void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
681 const CXXMethodDecl *Overridden) {
682 OverriddenMethods[Method].push_back(Overridden);
683}
684
Chris Lattner464175b2007-07-18 17:52:12 +0000685//===----------------------------------------------------------------------===//
686// Type Sizing and Analysis
687//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000688
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000689/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
690/// scalar floating point type.
691const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000692 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000693 assert(BT && "Not a floating point type!");
694 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000695 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000696 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000697 case BuiltinType::Float: return Target->getFloatFormat();
698 case BuiltinType::Double: return Target->getDoubleFormat();
699 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000700 }
701}
702
Ken Dyck8b752f12010-01-27 17:10:57 +0000703/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000704/// specified decl. Note that bitfields do not have a valid alignment, so
705/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000706/// If @p RefAsPointee, references are treated like their underlying type
707/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +0000708CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000709 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +0000710
John McCall4081a5c2010-10-08 18:24:19 +0000711 bool UseAlignAttrOnly = false;
712 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
713 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +0000714
John McCall4081a5c2010-10-08 18:24:19 +0000715 // __attribute__((aligned)) can increase or decrease alignment
716 // *except* on a struct or struct member, where it only increases
717 // alignment unless 'packed' is also specified.
718 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +0000719 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +0000720 // ignore that possibility; Sema should diagnose it.
721 if (isa<FieldDecl>(D)) {
722 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
723 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
724 } else {
725 UseAlignAttrOnly = true;
726 }
727 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +0000728 else if (isa<FieldDecl>(D))
729 UseAlignAttrOnly =
730 D->hasAttr<PackedAttr>() ||
731 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +0000732
John McCallba4f5d52011-01-20 07:57:12 +0000733 // If we're using the align attribute only, just ignore everything
734 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +0000735 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +0000736 // do nothing
737
John McCall4081a5c2010-10-08 18:24:19 +0000738 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +0000739 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000740 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000741 if (RefAsPointee)
742 T = RT->getPointeeType();
743 else
744 T = getPointerType(RT->getPointeeType());
745 }
746 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +0000747 // Adjust alignments of declarations with array type by the
748 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000749 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +0000750 const ArrayType *arrayType;
751 if (MinWidth && (arrayType = getAsArrayType(T))) {
752 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000753 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +0000754 else if (isa<ConstantArrayType>(arrayType) &&
755 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000756 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000757
John McCall3b657512011-01-19 10:06:00 +0000758 // Walk through any array types while we're at it.
759 T = getBaseElementType(arrayType);
760 }
Chad Rosier9f1210c2011-07-26 07:03:04 +0000761 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedmandcdafb62009-02-22 02:56:25 +0000762 }
John McCallba4f5d52011-01-20 07:57:12 +0000763
764 // Fields can be subject to extra alignment constraints, like if
765 // the field is packed, the struct is packed, or the struct has a
766 // a max-field-alignment constraint (#pragma pack). So calculate
767 // the actual alignment of the field within the struct, and then
768 // (as we're expected to) constrain that by the alignment of the type.
769 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
770 // So calculate the alignment of the field.
771 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
772
773 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +0000774 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +0000775
776 // Use the GCD of that and the offset within the record.
777 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
778 if (offset > 0) {
779 // Alignment is always a power of 2, so the GCD will be a power of 2,
780 // which means we get to do this crazy thing instead of Euclid's.
781 uint64_t lowBitOfOffset = offset & (~offset + 1);
782 if (lowBitOfOffset < fieldAlign)
783 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
784 }
785
786 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +0000787 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000788 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000789
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000790 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +0000791}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000792
John McCallea1471e2010-05-20 01:18:31 +0000793std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000794ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +0000795 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000796 return std::make_pair(toCharUnitsFromBits(Info.first),
797 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +0000798}
799
800std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000801ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +0000802 return getTypeInfoInChars(T.getTypePtr());
803}
804
Chris Lattnera7674d82007-07-13 22:13:22 +0000805/// getTypeSize - Return the size of the specified type, in bits. This method
806/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000807///
808/// FIXME: Pointers into different addr spaces could have different sizes and
809/// alignment requirements: getPointerInfo should take an AddrSpace, this
810/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000811std::pair<uint64_t, unsigned>
Jay Foad4ba2a172011-01-12 09:06:06 +0000812ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +0000813 uint64_t Width=0;
814 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000815 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000816#define TYPE(Class, Base)
817#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000818#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000819#define DEPENDENT_TYPE(Class, Base) case Type::Class:
820#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +0000821 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000822 break;
823
Chris Lattner692233e2007-07-13 22:27:08 +0000824 case Type::FunctionNoProto:
825 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000826 // GCC extension: alignof(function) = 32 bits
827 Width = 0;
828 Align = 32;
829 break;
830
Douglas Gregor72564e72009-02-26 23:50:07 +0000831 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000832 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000833 Width = 0;
834 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
835 break;
836
Steve Narofffb22d962007-08-30 01:06:46 +0000837 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000838 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000839
Chris Lattner98be4942008-03-05 18:54:05 +0000840 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000841 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000842 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +0000843 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000844 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000845 }
Nate Begeman213541a2008-04-18 23:10:10 +0000846 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000847 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000848 const VectorType *VT = cast<VectorType>(T);
849 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
850 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000851 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000852 // If the alignment is not a power of 2, round up to the next power of 2.
853 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000854 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000855 Align = llvm::NextPowerOf2(Align);
856 Width = llvm::RoundUpToAlignment(Width, Align);
857 }
Chris Lattner030d8842007-07-19 22:06:24 +0000858 break;
859 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000860
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000861 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000862 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000863 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000864 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000865 // GCC extension: alignof(void) = 8 bits.
866 Width = 0;
867 Align = 8;
868 break;
869
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000870 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000871 Width = Target->getBoolWidth();
872 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000873 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000874 case BuiltinType::Char_S:
875 case BuiltinType::Char_U:
876 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000877 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000878 Width = Target->getCharWidth();
879 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000880 break;
Chris Lattner3f59c972010-12-25 23:25:43 +0000881 case BuiltinType::WChar_S:
882 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000883 Width = Target->getWCharWidth();
884 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000885 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000886 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000887 Width = Target->getChar16Width();
888 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000889 break;
890 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000891 Width = Target->getChar32Width();
892 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000893 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000894 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000895 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000896 Width = Target->getShortWidth();
897 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000898 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000899 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000900 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000901 Width = Target->getIntWidth();
902 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000903 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000904 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000905 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000906 Width = Target->getLongWidth();
907 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000908 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000909 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000910 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000911 Width = Target->getLongLongWidth();
912 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000913 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000914 case BuiltinType::Int128:
915 case BuiltinType::UInt128:
916 Width = 128;
917 Align = 128; // int128_t is 128-bit aligned on all targets.
918 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000919 case BuiltinType::Half:
920 Width = Target->getHalfWidth();
921 Align = Target->getHalfAlign();
922 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000923 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000924 Width = Target->getFloatWidth();
925 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000926 break;
927 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000928 Width = Target->getDoubleWidth();
929 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000930 break;
931 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000932 Width = Target->getLongDoubleWidth();
933 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000934 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000935 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000936 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
937 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000938 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000939 case BuiltinType::ObjCId:
940 case BuiltinType::ObjCClass:
941 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000942 Width = Target->getPointerWidth(0);
943 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000944 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000945 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000946 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000947 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000948 Width = Target->getPointerWidth(0);
949 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000950 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000951 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000952 unsigned AS = getTargetAddressSpace(
953 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000954 Width = Target->getPointerWidth(AS);
955 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +0000956 break;
957 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000958 case Type::LValueReference:
959 case Type::RValueReference: {
960 // alignof and sizeof should never enter this code path here, so we go
961 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000962 unsigned AS = getTargetAddressSpace(
963 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000964 Width = Target->getPointerWidth(AS);
965 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +0000966 break;
967 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000968 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000969 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000970 Width = Target->getPointerWidth(AS);
971 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000972 break;
973 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000974 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +0000975 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000976 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000977 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +0000978 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000979 Align = PtrDiffInfo.second;
980 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000981 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000982 case Type::Complex: {
983 // Complex types have the same alignment as their elements, but twice the
984 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000985 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000986 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000987 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000988 Align = EltInfo.second;
989 break;
990 }
John McCallc12c5bb2010-05-15 11:32:37 +0000991 case Type::ObjCObject:
992 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000993 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000994 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000995 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +0000996 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +0000997 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +0000998 break;
999 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001000 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001001 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001002 const TagType *TT = cast<TagType>(T);
1003
1004 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001005 Width = 8;
1006 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001007 break;
1008 }
Mike Stump1eb44332009-09-09 15:08:12 +00001009
Daniel Dunbar1d751182008-11-08 05:48:37 +00001010 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001011 return getTypeInfo(ET->getDecl()->getIntegerType());
1012
Daniel Dunbar1d751182008-11-08 05:48:37 +00001013 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001014 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001015 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001016 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001017 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001018 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001019
Chris Lattner9fcfe922009-10-22 05:17:15 +00001020 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001021 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1022 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001023
Richard Smith34b41d92011-02-20 03:19:35 +00001024 case Type::Auto: {
1025 const AutoType *A = cast<AutoType>(T);
1026 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001027 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001028 }
1029
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001030 case Type::Paren:
1031 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1032
Douglas Gregor18857642009-04-30 17:32:17 +00001033 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001034 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001035 std::pair<uint64_t, unsigned> Info
1036 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001037 // If the typedef has an aligned attribute on it, it overrides any computed
1038 // alignment we have. This violates the GCC documentation (which says that
1039 // attribute(aligned) can only round up) but matches its implementation.
1040 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1041 Align = AttrAlign;
1042 else
1043 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001044 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001045 break;
Chris Lattner71763312008-04-06 22:05:18 +00001046 }
Douglas Gregor18857642009-04-30 17:32:17 +00001047
1048 case Type::TypeOfExpr:
1049 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1050 .getTypePtr());
1051
1052 case Type::TypeOf:
1053 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1054
Anders Carlsson395b4752009-06-24 19:06:50 +00001055 case Type::Decltype:
1056 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1057 .getTypePtr());
1058
Sean Huntca63c202011-05-24 22:41:36 +00001059 case Type::UnaryTransform:
1060 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1061
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001062 case Type::Elaborated:
1063 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001064
John McCall9d156a72011-01-06 01:58:22 +00001065 case Type::Attributed:
1066 return getTypeInfo(
1067 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1068
Richard Smith3e4c6c42011-05-05 21:57:07 +00001069 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001070 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001071 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001072 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1073 // A type alias template specialization may refer to a typedef with the
1074 // aligned attribute on it.
1075 if (TST->isTypeAlias())
1076 return getTypeInfo(TST->getAliasedType().getTypePtr());
1077 else
1078 return getTypeInfo(getCanonicalType(T));
1079 }
1080
Eli Friedmanb001de72011-10-06 23:00:33 +00001081 case Type::Atomic: {
Eli Friedman2be46072011-10-14 20:59:01 +00001082 std::pair<uint64_t, unsigned> Info
1083 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1084 Width = Info.first;
1085 Align = Info.second;
1086 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1087 llvm::isPowerOf2_64(Width)) {
1088 // We can potentially perform lock-free atomic operations for this
1089 // type; promote the alignment appropriately.
1090 // FIXME: We could potentially promote the width here as well...
1091 // is that worthwhile? (Non-struct atomic types generally have
1092 // power-of-two size anyway, but structs might not. Requires a bit
1093 // of implementation work to make sure we zero out the extra bits.)
1094 Align = static_cast<unsigned>(Width);
1095 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001096 }
1097
Douglas Gregor18857642009-04-30 17:32:17 +00001098 }
Mike Stump1eb44332009-09-09 15:08:12 +00001099
Eli Friedman2be46072011-10-14 20:59:01 +00001100 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001101 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001102}
1103
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001104/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1105CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1106 return CharUnits::fromQuantity(BitSize / getCharWidth());
1107}
1108
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001109/// toBits - Convert a size in characters to a size in characters.
1110int64_t ASTContext::toBits(CharUnits CharSize) const {
1111 return CharSize.getQuantity() * getCharWidth();
1112}
1113
Ken Dyckbdc601b2009-12-22 14:23:30 +00001114/// getTypeSizeInChars - Return the size of the specified type, in characters.
1115/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001116CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001117 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001118}
Jay Foad4ba2a172011-01-12 09:06:06 +00001119CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001120 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001121}
1122
Ken Dyck16e20cc2010-01-26 17:25:18 +00001123/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001124/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001125CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001126 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001127}
Jay Foad4ba2a172011-01-12 09:06:06 +00001128CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001129 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001130}
1131
Chris Lattner34ebde42009-01-27 18:08:34 +00001132/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1133/// type for the current target in bits. This can be different than the ABI
1134/// alignment in cases where it is beneficial for performance to overalign
1135/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001136unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001137 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001138
1139 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001140 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001141 T = CT->getElementType().getTypePtr();
1142 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1143 T->isSpecificBuiltinType(BuiltinType::LongLong))
1144 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1145
Chris Lattner34ebde42009-01-27 18:08:34 +00001146 return ABIAlign;
1147}
1148
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001149/// DeepCollectObjCIvars -
1150/// This routine first collects all declared, but not synthesized, ivars in
1151/// super class and then collects all ivars, including those synthesized for
1152/// current class. This routine is used for implementation of current class
1153/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001154///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001155void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1156 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001157 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001158 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1159 DeepCollectObjCIvars(SuperClass, false, Ivars);
1160 if (!leafClass) {
1161 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1162 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanian11062e12010-02-19 00:31:17 +00001163 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001164 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001165 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001166 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001167 Iv= Iv->getNextIvar())
1168 Ivars.push_back(Iv);
1169 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001170}
1171
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001172/// CollectInheritedProtocols - Collect all protocols in current class and
1173/// those inherited by it.
1174void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001175 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001176 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001177 // We can use protocol_iterator here instead of
1178 // all_referenced_protocol_iterator since we are walking all categories.
1179 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1180 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001181 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001182 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001183 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001184 PE = Proto->protocol_end(); P != PE; ++P) {
1185 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001186 CollectInheritedProtocols(*P, Protocols);
1187 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001188 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001189
1190 // Categories of this Interface.
1191 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1192 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1193 CollectInheritedProtocols(CDeclChain, Protocols);
1194 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1195 while (SD) {
1196 CollectInheritedProtocols(SD, Protocols);
1197 SD = SD->getSuperClass();
1198 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001199 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001200 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001201 PE = OC->protocol_end(); P != PE; ++P) {
1202 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001203 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001204 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1205 PE = Proto->protocol_end(); P != PE; ++P)
1206 CollectInheritedProtocols(*P, Protocols);
1207 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001208 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001209 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1210 PE = OP->protocol_end(); P != PE; ++P) {
1211 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001212 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001213 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1214 PE = Proto->protocol_end(); P != PE; ++P)
1215 CollectInheritedProtocols(*P, Protocols);
1216 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001217 }
1218}
1219
Jay Foad4ba2a172011-01-12 09:06:06 +00001220unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001221 unsigned count = 0;
1222 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001223 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1224 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001225 count += CDecl->ivar_size();
1226
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001227 // Count ivar defined in this class's implementation. This
1228 // includes synthesized ivars.
1229 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001230 count += ImplDecl->ivar_size();
1231
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001232 return count;
1233}
1234
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001235/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1236ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1237 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1238 I = ObjCImpls.find(D);
1239 if (I != ObjCImpls.end())
1240 return cast<ObjCImplementationDecl>(I->second);
1241 return 0;
1242}
1243/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1244ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1245 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1246 I = ObjCImpls.find(D);
1247 if (I != ObjCImpls.end())
1248 return cast<ObjCCategoryImplDecl>(I->second);
1249 return 0;
1250}
1251
1252/// \brief Set the implementation of ObjCInterfaceDecl.
1253void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1254 ObjCImplementationDecl *ImplD) {
1255 assert(IFaceD && ImplD && "Passed null params");
1256 ObjCImpls[IFaceD] = ImplD;
1257}
1258/// \brief Set the implementation of ObjCCategoryDecl.
1259void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1260 ObjCCategoryImplDecl *ImplD) {
1261 assert(CatD && ImplD && "Passed null params");
1262 ObjCImpls[CatD] = ImplD;
1263}
1264
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001265ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1266 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1267 return ID;
1268 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1269 return CD->getClassInterface();
1270 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1271 return IMD->getClassInterface();
1272
1273 return 0;
1274}
1275
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001276/// \brief Get the copy initialization expression of VarDecl,or NULL if
1277/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001278Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001279 assert(VD && "Passed null params");
1280 assert(VD->hasAttr<BlocksAttr>() &&
1281 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001282 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001283 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001284 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1285}
1286
1287/// \brief Set the copy inialization expression of a block var decl.
1288void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1289 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001290 assert(VD->hasAttr<BlocksAttr>() &&
1291 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001292 BlockVarCopyInits[VD] = Init;
1293}
1294
John McCalla93c9342009-12-07 02:54:59 +00001295/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001296///
John McCalla93c9342009-12-07 02:54:59 +00001297/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001298/// the TypeLoc wrappers.
1299///
1300/// \param T the type that will be the basis for type source info. This type
1301/// should refer to how the declarator was written in source code, not to
1302/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001303TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001304 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001305 if (!DataSize)
1306 DataSize = TypeLoc::getFullDataSizeForType(T);
1307 else
1308 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001309 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001310
John McCalla93c9342009-12-07 02:54:59 +00001311 TypeSourceInfo *TInfo =
1312 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1313 new (TInfo) TypeSourceInfo(T);
1314 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001315}
1316
John McCalla93c9342009-12-07 02:54:59 +00001317TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001318 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001319 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001320 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001321 return DI;
1322}
1323
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001324const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001325ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001326 return getObjCLayout(D, 0);
1327}
1328
1329const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001330ASTContext::getASTObjCImplementationLayout(
1331 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001332 return getObjCLayout(D->getClassInterface(), D);
1333}
1334
Chris Lattnera7674d82007-07-13 22:13:22 +00001335//===----------------------------------------------------------------------===//
1336// Type creation/memoization methods
1337//===----------------------------------------------------------------------===//
1338
Jay Foad4ba2a172011-01-12 09:06:06 +00001339QualType
John McCall3b657512011-01-19 10:06:00 +00001340ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1341 unsigned fastQuals = quals.getFastQualifiers();
1342 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001343
1344 // Check if we've already instantiated this type.
1345 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001346 ExtQuals::Profile(ID, baseType, quals);
1347 void *insertPos = 0;
1348 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1349 assert(eq->getQualifiers() == quals);
1350 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001351 }
1352
John McCall3b657512011-01-19 10:06:00 +00001353 // If the base type is not canonical, make the appropriate canonical type.
1354 QualType canon;
1355 if (!baseType->isCanonicalUnqualified()) {
1356 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1357 canonSplit.second.addConsistentQualifiers(quals);
1358 canon = getExtQualType(canonSplit.first, canonSplit.second);
1359
1360 // Re-find the insert position.
1361 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1362 }
1363
1364 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1365 ExtQualNodes.InsertNode(eq, insertPos);
1366 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001367}
1368
Jay Foad4ba2a172011-01-12 09:06:06 +00001369QualType
1370ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001371 QualType CanT = getCanonicalType(T);
1372 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001373 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001374
John McCall0953e762009-09-24 19:53:00 +00001375 // If we are composing extended qualifiers together, merge together
1376 // into one ExtQuals node.
1377 QualifierCollector Quals;
1378 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001379
John McCall0953e762009-09-24 19:53:00 +00001380 // If this type already has an address space specified, it cannot get
1381 // another one.
1382 assert(!Quals.hasAddressSpace() &&
1383 "Type cannot be in multiple addr spaces!");
1384 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001385
John McCall0953e762009-09-24 19:53:00 +00001386 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001387}
1388
Chris Lattnerb7d25532009-02-18 22:53:11 +00001389QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001390 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001391 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001392 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001393 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001394
John McCall7f040a92010-12-24 02:08:15 +00001395 if (const PointerType *ptr = T->getAs<PointerType>()) {
1396 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001397 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001398 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1399 return getPointerType(ResultType);
1400 }
1401 }
Mike Stump1eb44332009-09-09 15:08:12 +00001402
John McCall0953e762009-09-24 19:53:00 +00001403 // If we are composing extended qualifiers together, merge together
1404 // into one ExtQuals node.
1405 QualifierCollector Quals;
1406 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001407
John McCall0953e762009-09-24 19:53:00 +00001408 // If this type already has an ObjCGC specified, it cannot get
1409 // another one.
1410 assert(!Quals.hasObjCGCAttr() &&
1411 "Type cannot have multiple ObjCGCs!");
1412 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001413
John McCall0953e762009-09-24 19:53:00 +00001414 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001415}
Chris Lattnera7674d82007-07-13 22:13:22 +00001416
John McCalle6a365d2010-12-19 02:44:49 +00001417const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1418 FunctionType::ExtInfo Info) {
1419 if (T->getExtInfo() == Info)
1420 return T;
1421
1422 QualType Result;
1423 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1424 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1425 } else {
1426 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1427 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1428 EPI.ExtInfo = Info;
1429 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1430 FPT->getNumArgs(), EPI);
1431 }
1432
1433 return cast<FunctionType>(Result.getTypePtr());
1434}
1435
Reid Spencer5f016e22007-07-11 17:01:13 +00001436/// getComplexType - Return the uniqued reference to the type for a complex
1437/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001438QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001439 // Unique pointers, to guarantee there is only one pointer of a particular
1440 // structure.
1441 llvm::FoldingSetNodeID ID;
1442 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Reid Spencer5f016e22007-07-11 17:01:13 +00001444 void *InsertPos = 0;
1445 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1446 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001447
Reid Spencer5f016e22007-07-11 17:01:13 +00001448 // If the pointee type isn't canonical, this won't be a canonical type either,
1449 // so fill in the canonical type field.
1450 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001451 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001452 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001453
Reid Spencer5f016e22007-07-11 17:01:13 +00001454 // Get the new insert position for the node we care about.
1455 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001456 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001457 }
John McCall6b304a02009-09-24 23:30:46 +00001458 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001459 Types.push_back(New);
1460 ComplexTypes.InsertNode(New, InsertPos);
1461 return QualType(New, 0);
1462}
1463
Reid Spencer5f016e22007-07-11 17:01:13 +00001464/// getPointerType - Return the uniqued reference to the type for a pointer to
1465/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001466QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001467 // Unique pointers, to guarantee there is only one pointer of a particular
1468 // structure.
1469 llvm::FoldingSetNodeID ID;
1470 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001471
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 void *InsertPos = 0;
1473 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1474 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001475
Reid Spencer5f016e22007-07-11 17:01:13 +00001476 // If the pointee type isn't canonical, this won't be a canonical type either,
1477 // so fill in the canonical type field.
1478 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001479 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001480 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001481
Reid Spencer5f016e22007-07-11 17:01:13 +00001482 // Get the new insert position for the node we care about.
1483 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001484 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001485 }
John McCall6b304a02009-09-24 23:30:46 +00001486 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001487 Types.push_back(New);
1488 PointerTypes.InsertNode(New, InsertPos);
1489 return QualType(New, 0);
1490}
1491
Mike Stump1eb44332009-09-09 15:08:12 +00001492/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001493/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001494QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001495 assert(T->isFunctionType() && "block of function types only");
1496 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001497 // structure.
1498 llvm::FoldingSetNodeID ID;
1499 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001500
Steve Naroff5618bd42008-08-27 16:04:49 +00001501 void *InsertPos = 0;
1502 if (BlockPointerType *PT =
1503 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1504 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001505
1506 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001507 // type either so fill in the canonical type field.
1508 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001509 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001510 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001511
Steve Naroff5618bd42008-08-27 16:04:49 +00001512 // Get the new insert position for the node we care about.
1513 BlockPointerType *NewIP =
1514 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001515 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001516 }
John McCall6b304a02009-09-24 23:30:46 +00001517 BlockPointerType *New
1518 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001519 Types.push_back(New);
1520 BlockPointerTypes.InsertNode(New, InsertPos);
1521 return QualType(New, 0);
1522}
1523
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001524/// getLValueReferenceType - Return the uniqued reference to the type for an
1525/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001526QualType
1527ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00001528 assert(getCanonicalType(T) != OverloadTy &&
1529 "Unresolved overloaded function type");
1530
Reid Spencer5f016e22007-07-11 17:01:13 +00001531 // Unique pointers, to guarantee there is only one pointer of a particular
1532 // structure.
1533 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001534 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001535
1536 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001537 if (LValueReferenceType *RT =
1538 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001539 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001540
John McCall54e14c42009-10-22 22:37:11 +00001541 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1542
Reid Spencer5f016e22007-07-11 17:01:13 +00001543 // If the referencee type isn't canonical, this won't be a canonical type
1544 // either, so fill in the canonical type field.
1545 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001546 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1547 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1548 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001549
Reid Spencer5f016e22007-07-11 17:01:13 +00001550 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001551 LValueReferenceType *NewIP =
1552 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001553 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001554 }
1555
John McCall6b304a02009-09-24 23:30:46 +00001556 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001557 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1558 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001559 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001560 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001561
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001562 return QualType(New, 0);
1563}
1564
1565/// getRValueReferenceType - Return the uniqued reference to the type for an
1566/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001567QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001568 // Unique pointers, to guarantee there is only one pointer of a particular
1569 // structure.
1570 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001571 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001572
1573 void *InsertPos = 0;
1574 if (RValueReferenceType *RT =
1575 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1576 return QualType(RT, 0);
1577
John McCall54e14c42009-10-22 22:37:11 +00001578 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1579
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001580 // If the referencee type isn't canonical, this won't be a canonical type
1581 // either, so fill in the canonical type field.
1582 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001583 if (InnerRef || !T.isCanonical()) {
1584 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1585 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001586
1587 // Get the new insert position for the node we care about.
1588 RValueReferenceType *NewIP =
1589 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001590 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001591 }
1592
John McCall6b304a02009-09-24 23:30:46 +00001593 RValueReferenceType *New
1594 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001595 Types.push_back(New);
1596 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001597 return QualType(New, 0);
1598}
1599
Sebastian Redlf30208a2009-01-24 21:16:55 +00001600/// getMemberPointerType - Return the uniqued reference to the type for a
1601/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00001602QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001603 // Unique pointers, to guarantee there is only one pointer of a particular
1604 // structure.
1605 llvm::FoldingSetNodeID ID;
1606 MemberPointerType::Profile(ID, T, Cls);
1607
1608 void *InsertPos = 0;
1609 if (MemberPointerType *PT =
1610 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1611 return QualType(PT, 0);
1612
1613 // If the pointee or class type isn't canonical, this won't be a canonical
1614 // type either, so fill in the canonical type field.
1615 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001616 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001617 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1618
1619 // Get the new insert position for the node we care about.
1620 MemberPointerType *NewIP =
1621 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001622 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001623 }
John McCall6b304a02009-09-24 23:30:46 +00001624 MemberPointerType *New
1625 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001626 Types.push_back(New);
1627 MemberPointerTypes.InsertNode(New, InsertPos);
1628 return QualType(New, 0);
1629}
1630
Mike Stump1eb44332009-09-09 15:08:12 +00001631/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001632/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001633QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001634 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001635 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001636 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001637 assert((EltTy->isDependentType() ||
1638 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001639 "Constant array of VLAs is illegal!");
1640
Chris Lattner38aeec72009-05-13 04:12:56 +00001641 // Convert the array size into a canonical width matching the pointer size for
1642 // the target.
1643 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001644 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001645 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00001646
Reid Spencer5f016e22007-07-11 17:01:13 +00001647 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001648 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001649
Reid Spencer5f016e22007-07-11 17:01:13 +00001650 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001651 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001652 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001653 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001654
John McCall3b657512011-01-19 10:06:00 +00001655 // If the element type isn't canonical or has qualifiers, this won't
1656 // be a canonical type either, so fill in the canonical type field.
1657 QualType Canon;
1658 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1659 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1660 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001661 ASM, IndexTypeQuals);
John McCall3b657512011-01-19 10:06:00 +00001662 Canon = getQualifiedType(Canon, canonSplit.second);
1663
Reid Spencer5f016e22007-07-11 17:01:13 +00001664 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001665 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001666 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001667 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001668 }
Mike Stump1eb44332009-09-09 15:08:12 +00001669
John McCall6b304a02009-09-24 23:30:46 +00001670 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001671 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001672 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001673 Types.push_back(New);
1674 return QualType(New, 0);
1675}
1676
John McCallce889032011-01-18 08:40:38 +00001677/// getVariableArrayDecayedType - Turns the given type, which may be
1678/// variably-modified, into the corresponding type with all the known
1679/// sizes replaced with [*].
1680QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1681 // Vastly most common case.
1682 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001683
John McCallce889032011-01-18 08:40:38 +00001684 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001685
John McCallce889032011-01-18 08:40:38 +00001686 SplitQualType split = type.getSplitDesugaredType();
1687 const Type *ty = split.first;
1688 switch (ty->getTypeClass()) {
1689#define TYPE(Class, Base)
1690#define ABSTRACT_TYPE(Class, Base)
1691#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1692#include "clang/AST/TypeNodes.def"
1693 llvm_unreachable("didn't desugar past all non-canonical types?");
1694
1695 // These types should never be variably-modified.
1696 case Type::Builtin:
1697 case Type::Complex:
1698 case Type::Vector:
1699 case Type::ExtVector:
1700 case Type::DependentSizedExtVector:
1701 case Type::ObjCObject:
1702 case Type::ObjCInterface:
1703 case Type::ObjCObjectPointer:
1704 case Type::Record:
1705 case Type::Enum:
1706 case Type::UnresolvedUsing:
1707 case Type::TypeOfExpr:
1708 case Type::TypeOf:
1709 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00001710 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00001711 case Type::DependentName:
1712 case Type::InjectedClassName:
1713 case Type::TemplateSpecialization:
1714 case Type::DependentTemplateSpecialization:
1715 case Type::TemplateTypeParm:
1716 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00001717 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00001718 case Type::PackExpansion:
1719 llvm_unreachable("type should never be variably-modified");
1720
1721 // These types can be variably-modified but should never need to
1722 // further decay.
1723 case Type::FunctionNoProto:
1724 case Type::FunctionProto:
1725 case Type::BlockPointer:
1726 case Type::MemberPointer:
1727 return type;
1728
1729 // These types can be variably-modified. All these modifications
1730 // preserve structure except as noted by comments.
1731 // TODO: if we ever care about optimizing VLAs, there are no-op
1732 // optimizations available here.
1733 case Type::Pointer:
1734 result = getPointerType(getVariableArrayDecayedType(
1735 cast<PointerType>(ty)->getPointeeType()));
1736 break;
1737
1738 case Type::LValueReference: {
1739 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1740 result = getLValueReferenceType(
1741 getVariableArrayDecayedType(lv->getPointeeType()),
1742 lv->isSpelledAsLValue());
1743 break;
1744 }
1745
1746 case Type::RValueReference: {
1747 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1748 result = getRValueReferenceType(
1749 getVariableArrayDecayedType(lv->getPointeeType()));
1750 break;
1751 }
1752
Eli Friedmanb001de72011-10-06 23:00:33 +00001753 case Type::Atomic: {
1754 const AtomicType *at = cast<AtomicType>(ty);
1755 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1756 break;
1757 }
1758
John McCallce889032011-01-18 08:40:38 +00001759 case Type::ConstantArray: {
1760 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1761 result = getConstantArrayType(
1762 getVariableArrayDecayedType(cat->getElementType()),
1763 cat->getSize(),
1764 cat->getSizeModifier(),
1765 cat->getIndexTypeCVRQualifiers());
1766 break;
1767 }
1768
1769 case Type::DependentSizedArray: {
1770 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1771 result = getDependentSizedArrayType(
1772 getVariableArrayDecayedType(dat->getElementType()),
1773 dat->getSizeExpr(),
1774 dat->getSizeModifier(),
1775 dat->getIndexTypeCVRQualifiers(),
1776 dat->getBracketsRange());
1777 break;
1778 }
1779
1780 // Turn incomplete types into [*] types.
1781 case Type::IncompleteArray: {
1782 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1783 result = getVariableArrayType(
1784 getVariableArrayDecayedType(iat->getElementType()),
1785 /*size*/ 0,
1786 ArrayType::Normal,
1787 iat->getIndexTypeCVRQualifiers(),
1788 SourceRange());
1789 break;
1790 }
1791
1792 // Turn VLA types into [*] types.
1793 case Type::VariableArray: {
1794 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1795 result = getVariableArrayType(
1796 getVariableArrayDecayedType(vat->getElementType()),
1797 /*size*/ 0,
1798 ArrayType::Star,
1799 vat->getIndexTypeCVRQualifiers(),
1800 vat->getBracketsRange());
1801 break;
1802 }
1803 }
1804
1805 // Apply the top-level qualifiers from the original.
1806 return getQualifiedType(result, split.second);
1807}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001808
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001809/// getVariableArrayType - Returns a non-unique reference to the type for a
1810/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001811QualType ASTContext::getVariableArrayType(QualType EltTy,
1812 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001813 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001814 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00001815 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001816 // Since we don't unique expressions, it isn't possible to unique VLA's
1817 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00001818 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00001819
John McCall3b657512011-01-19 10:06:00 +00001820 // Be sure to pull qualifiers off the element type.
1821 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1822 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1823 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001824 IndexTypeQuals, Brackets);
John McCall3b657512011-01-19 10:06:00 +00001825 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor715e9c82010-05-23 16:10:32 +00001826 }
1827
John McCall6b304a02009-09-24 23:30:46 +00001828 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001829 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001830
1831 VariableArrayTypes.push_back(New);
1832 Types.push_back(New);
1833 return QualType(New, 0);
1834}
1835
Douglas Gregor898574e2008-12-05 23:32:09 +00001836/// getDependentSizedArrayType - Returns a non-unique reference to
1837/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001838/// type.
John McCall3b657512011-01-19 10:06:00 +00001839QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1840 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00001841 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001842 unsigned elementTypeQuals,
1843 SourceRange brackets) const {
1844 assert((!numElements || numElements->isTypeDependent() ||
1845 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001846 "Size must be type- or value-dependent!");
1847
John McCall3b657512011-01-19 10:06:00 +00001848 // Dependently-sized array types that do not have a specified number
1849 // of elements will have their sizes deduced from a dependent
1850 // initializer. We do no canonicalization here at all, which is okay
1851 // because they can't be used in most locations.
1852 if (!numElements) {
1853 DependentSizedArrayType *newType
1854 = new (*this, TypeAlignment)
1855 DependentSizedArrayType(*this, elementType, QualType(),
1856 numElements, ASM, elementTypeQuals,
1857 brackets);
1858 Types.push_back(newType);
1859 return QualType(newType, 0);
1860 }
1861
1862 // Otherwise, we actually build a new type every time, but we
1863 // also build a canonical type.
1864
1865 SplitQualType canonElementType = getCanonicalType(elementType).split();
1866
1867 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001868 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001869 DependentSizedArrayType::Profile(ID, *this,
1870 QualType(canonElementType.first, 0),
1871 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001872
John McCall3b657512011-01-19 10:06:00 +00001873 // Look for an existing type with these properties.
1874 DependentSizedArrayType *canonTy =
1875 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001876
John McCall3b657512011-01-19 10:06:00 +00001877 // If we don't have one, build one.
1878 if (!canonTy) {
1879 canonTy = new (*this, TypeAlignment)
1880 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1881 QualType(), numElements, ASM, elementTypeQuals,
1882 brackets);
1883 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1884 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001885 }
1886
John McCall3b657512011-01-19 10:06:00 +00001887 // Apply qualifiers from the element type to the array.
1888 QualType canon = getQualifiedType(QualType(canonTy,0),
1889 canonElementType.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001890
John McCall3b657512011-01-19 10:06:00 +00001891 // If we didn't need extra canonicalization for the element type,
1892 // then just use that as our result.
1893 if (QualType(canonElementType.first, 0) == elementType)
1894 return canon;
1895
1896 // Otherwise, we need to build a type which follows the spelling
1897 // of the element type.
1898 DependentSizedArrayType *sugaredType
1899 = new (*this, TypeAlignment)
1900 DependentSizedArrayType(*this, elementType, canon, numElements,
1901 ASM, elementTypeQuals, brackets);
1902 Types.push_back(sugaredType);
1903 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00001904}
1905
John McCall3b657512011-01-19 10:06:00 +00001906QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00001907 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001908 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001909 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001910 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001911
John McCall3b657512011-01-19 10:06:00 +00001912 void *insertPos = 0;
1913 if (IncompleteArrayType *iat =
1914 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1915 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001916
1917 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00001918 // either, so fill in the canonical type field. We also have to pull
1919 // qualifiers off the element type.
1920 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00001921
John McCall3b657512011-01-19 10:06:00 +00001922 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1923 SplitQualType canonSplit = getCanonicalType(elementType).split();
1924 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1925 ASM, elementTypeQuals);
1926 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001927
1928 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00001929 IncompleteArrayType *existing =
1930 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1931 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001932 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001933
John McCall3b657512011-01-19 10:06:00 +00001934 IncompleteArrayType *newType = new (*this, TypeAlignment)
1935 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001936
John McCall3b657512011-01-19 10:06:00 +00001937 IncompleteArrayTypes.InsertNode(newType, insertPos);
1938 Types.push_back(newType);
1939 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001940}
1941
Steve Naroff73322922007-07-18 18:00:27 +00001942/// getVectorType - Return the unique reference to a vector type of
1943/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001944QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00001945 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00001946 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001947
Reid Spencer5f016e22007-07-11 17:01:13 +00001948 // Check if we've already instantiated a vector of this type.
1949 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00001950 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00001951
Reid Spencer5f016e22007-07-11 17:01:13 +00001952 void *InsertPos = 0;
1953 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1954 return QualType(VTP, 0);
1955
1956 // If the element type isn't canonical, this won't be a canonical type either,
1957 // so fill in the canonical type field.
1958 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00001959 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00001960 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00001961
Reid Spencer5f016e22007-07-11 17:01:13 +00001962 // Get the new insert position for the node we care about.
1963 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001964 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001965 }
John McCall6b304a02009-09-24 23:30:46 +00001966 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00001967 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001968 VectorTypes.InsertNode(New, InsertPos);
1969 Types.push_back(New);
1970 return QualType(New, 0);
1971}
1972
Nate Begeman213541a2008-04-18 23:10:10 +00001973/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001974/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001975QualType
1976ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00001977 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00001978
Steve Naroff73322922007-07-18 18:00:27 +00001979 // Check if we've already instantiated a vector of this type.
1980 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001981 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001982 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00001983 void *InsertPos = 0;
1984 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1985 return QualType(VTP, 0);
1986
1987 // If the element type isn't canonical, this won't be a canonical type either,
1988 // so fill in the canonical type field.
1989 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001990 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001991 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001992
Steve Naroff73322922007-07-18 18:00:27 +00001993 // Get the new insert position for the node we care about.
1994 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001995 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001996 }
John McCall6b304a02009-09-24 23:30:46 +00001997 ExtVectorType *New = new (*this, TypeAlignment)
1998 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001999 VectorTypes.InsertNode(New, InsertPos);
2000 Types.push_back(New);
2001 return QualType(New, 0);
2002}
2003
Jay Foad4ba2a172011-01-12 09:06:06 +00002004QualType
2005ASTContext::getDependentSizedExtVectorType(QualType vecType,
2006 Expr *SizeExpr,
2007 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002008 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002009 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002010 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002011
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002012 void *InsertPos = 0;
2013 DependentSizedExtVectorType *Canon
2014 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2015 DependentSizedExtVectorType *New;
2016 if (Canon) {
2017 // We already have a canonical version of this array type; use it as
2018 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002019 New = new (*this, TypeAlignment)
2020 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2021 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002022 } else {
2023 QualType CanonVecTy = getCanonicalType(vecType);
2024 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002025 New = new (*this, TypeAlignment)
2026 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2027 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002028
2029 DependentSizedExtVectorType *CanonCheck
2030 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2031 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2032 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002033 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2034 } else {
2035 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2036 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002037 New = new (*this, TypeAlignment)
2038 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002039 }
2040 }
Mike Stump1eb44332009-09-09 15:08:12 +00002041
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002042 Types.push_back(New);
2043 return QualType(New, 0);
2044}
2045
Douglas Gregor72564e72009-02-26 23:50:07 +00002046/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002047///
Jay Foad4ba2a172011-01-12 09:06:06 +00002048QualType
2049ASTContext::getFunctionNoProtoType(QualType ResultTy,
2050 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002051 const CallingConv DefaultCC = Info.getCC();
2052 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2053 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002054 // Unique functions, to guarantee there is only one function of a particular
2055 // structure.
2056 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002057 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002058
Reid Spencer5f016e22007-07-11 17:01:13 +00002059 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002060 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002061 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002062 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002063
Reid Spencer5f016e22007-07-11 17:01:13 +00002064 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002065 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002066 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002067 Canonical =
2068 getFunctionNoProtoType(getCanonicalType(ResultTy),
2069 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002070
Reid Spencer5f016e22007-07-11 17:01:13 +00002071 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002072 FunctionNoProtoType *NewIP =
2073 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002074 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002075 }
Mike Stump1eb44332009-09-09 15:08:12 +00002076
Roman Divackycfe9af22011-03-01 17:40:53 +00002077 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002078 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002079 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002080 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002081 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002082 return QualType(New, 0);
2083}
2084
2085/// getFunctionType - Return a normal function type with a typed argument
2086/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002087QualType
2088ASTContext::getFunctionType(QualType ResultTy,
2089 const QualType *ArgArray, unsigned NumArgs,
2090 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002091 // Unique functions, to guarantee there is only one function of a particular
2092 // structure.
2093 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002094 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002095
2096 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002097 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002098 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002099 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002100
2101 // Determine whether the type being created is already canonical or not.
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002102 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00002103 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002104 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002105 isCanonical = false;
2106
Roman Divackycfe9af22011-03-01 17:40:53 +00002107 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2108 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2109 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002110
Reid Spencer5f016e22007-07-11 17:01:13 +00002111 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002112 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002113 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002114 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002115 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002116 CanonicalArgs.reserve(NumArgs);
2117 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002118 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002119
John McCalle23cf432010-12-14 08:05:40 +00002120 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002121 CanonicalEPI.ExceptionSpecType = EST_None;
2122 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002123 CanonicalEPI.ExtInfo
2124 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2125
Chris Lattnerf52ab252008-04-06 22:59:24 +00002126 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00002127 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002128 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002129
Reid Spencer5f016e22007-07-11 17:01:13 +00002130 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002131 FunctionProtoType *NewIP =
2132 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002133 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002134 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002135
John McCallf85e1932011-06-15 23:02:42 +00002136 // FunctionProtoType objects are allocated with extra bytes after
2137 // them for three variable size arrays at the end:
2138 // - parameter types
2139 // - exception types
2140 // - consumed-arguments flags
2141 // Instead of the exception types, there could be a noexcept
2142 // expression.
John McCalle23cf432010-12-14 08:05:40 +00002143 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002144 NumArgs * sizeof(QualType);
2145 if (EPI.ExceptionSpecType == EST_Dynamic)
2146 Size += EPI.NumExceptions * sizeof(QualType);
2147 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002148 Size += sizeof(Expr*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002149 }
John McCallf85e1932011-06-15 23:02:42 +00002150 if (EPI.ConsumedArguments)
2151 Size += NumArgs * sizeof(bool);
2152
John McCalle23cf432010-12-14 08:05:40 +00002153 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002154 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2155 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002156 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002157 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002158 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002159 return QualType(FTP, 0);
2160}
2161
John McCall3cb0ebd2010-03-10 03:28:59 +00002162#ifndef NDEBUG
2163static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2164 if (!isa<CXXRecordDecl>(D)) return false;
2165 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2166 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2167 return true;
2168 if (RD->getDescribedClassTemplate() &&
2169 !isa<ClassTemplateSpecializationDecl>(RD))
2170 return true;
2171 return false;
2172}
2173#endif
2174
2175/// getInjectedClassNameType - Return the unique reference to the
2176/// injected class name type for the specified templated declaration.
2177QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002178 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002179 assert(NeedsInjectedClassNameType(Decl));
2180 if (Decl->TypeForDecl) {
2181 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00002182 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002183 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2184 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2185 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2186 } else {
John McCallf4c73712011-01-19 06:33:43 +00002187 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002188 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002189 Decl->TypeForDecl = newType;
2190 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002191 }
2192 return QualType(Decl->TypeForDecl, 0);
2193}
2194
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002195/// getTypeDeclType - Return the unique reference to the type for the
2196/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002197QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002198 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002199 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002200
Richard Smith162e1c12011-04-15 14:24:37 +00002201 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002202 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002203
John McCallbecb8d52010-03-10 06:48:02 +00002204 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2205 "Template type parameter types are always available.");
2206
John McCall19c85762010-02-16 03:57:14 +00002207 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002208 assert(!Record->getPreviousDeclaration() &&
2209 "struct/union has previous declaration");
2210 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002211 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002212 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002213 assert(!Enum->getPreviousDeclaration() &&
2214 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002215 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002216 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002217 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002218 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2219 Decl->TypeForDecl = newType;
2220 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002221 } else
John McCallbecb8d52010-03-10 06:48:02 +00002222 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002223
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002224 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002225}
2226
Reid Spencer5f016e22007-07-11 17:01:13 +00002227/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002228/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002229QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002230ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2231 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002232 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002233
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002234 if (Canonical.isNull())
2235 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002236 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002237 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002238 Decl->TypeForDecl = newType;
2239 Types.push_back(newType);
2240 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002241}
2242
Jay Foad4ba2a172011-01-12 09:06:06 +00002243QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002244 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2245
2246 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2247 if (PrevDecl->TypeForDecl)
2248 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2249
John McCallf4c73712011-01-19 06:33:43 +00002250 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2251 Decl->TypeForDecl = newType;
2252 Types.push_back(newType);
2253 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002254}
2255
Jay Foad4ba2a172011-01-12 09:06:06 +00002256QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002257 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2258
2259 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2260 if (PrevDecl->TypeForDecl)
2261 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2262
John McCallf4c73712011-01-19 06:33:43 +00002263 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2264 Decl->TypeForDecl = newType;
2265 Types.push_back(newType);
2266 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002267}
2268
John McCall9d156a72011-01-06 01:58:22 +00002269QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2270 QualType modifiedType,
2271 QualType equivalentType) {
2272 llvm::FoldingSetNodeID id;
2273 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2274
2275 void *insertPos = 0;
2276 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2277 if (type) return QualType(type, 0);
2278
2279 QualType canon = getCanonicalType(equivalentType);
2280 type = new (*this, TypeAlignment)
2281 AttributedType(canon, attrKind, modifiedType, equivalentType);
2282
2283 Types.push_back(type);
2284 AttributedTypes.InsertNode(type, insertPos);
2285
2286 return QualType(type, 0);
2287}
2288
2289
John McCall49a832b2009-10-18 09:09:24 +00002290/// \brief Retrieve a substitution-result type.
2291QualType
2292ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002293 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002294 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002295 && "replacement types must always be canonical");
2296
2297 llvm::FoldingSetNodeID ID;
2298 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2299 void *InsertPos = 0;
2300 SubstTemplateTypeParmType *SubstParm
2301 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2302
2303 if (!SubstParm) {
2304 SubstParm = new (*this, TypeAlignment)
2305 SubstTemplateTypeParmType(Parm, Replacement);
2306 Types.push_back(SubstParm);
2307 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2308 }
2309
2310 return QualType(SubstParm, 0);
2311}
2312
Douglas Gregorc3069d62011-01-14 02:55:32 +00002313/// \brief Retrieve a
2314QualType ASTContext::getSubstTemplateTypeParmPackType(
2315 const TemplateTypeParmType *Parm,
2316 const TemplateArgument &ArgPack) {
2317#ifndef NDEBUG
2318 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2319 PEnd = ArgPack.pack_end();
2320 P != PEnd; ++P) {
2321 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2322 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2323 }
2324#endif
2325
2326 llvm::FoldingSetNodeID ID;
2327 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2328 void *InsertPos = 0;
2329 if (SubstTemplateTypeParmPackType *SubstParm
2330 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2331 return QualType(SubstParm, 0);
2332
2333 QualType Canon;
2334 if (!Parm->isCanonicalUnqualified()) {
2335 Canon = getCanonicalType(QualType(Parm, 0));
2336 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2337 ArgPack);
2338 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2339 }
2340
2341 SubstTemplateTypeParmPackType *SubstParm
2342 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2343 ArgPack);
2344 Types.push_back(SubstParm);
2345 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2346 return QualType(SubstParm, 0);
2347}
2348
Douglas Gregorfab9d672009-02-05 23:33:38 +00002349/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002350/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002351/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002352QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002353 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002354 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002355 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002356 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002357 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002358 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002359 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2360
2361 if (TypeParm)
2362 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002363
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002364 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002365 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002366 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002367
2368 TemplateTypeParmType *TypeCheck
2369 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2370 assert(!TypeCheck && "Template type parameter canonical type broken");
2371 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002372 } else
John McCall6b304a02009-09-24 23:30:46 +00002373 TypeParm = new (*this, TypeAlignment)
2374 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002375
2376 Types.push_back(TypeParm);
2377 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2378
2379 return QualType(TypeParm, 0);
2380}
2381
John McCall3cb0ebd2010-03-10 03:28:59 +00002382TypeSourceInfo *
2383ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2384 SourceLocation NameLoc,
2385 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002386 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002387 assert(!Name.getAsDependentTemplateName() &&
2388 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002389 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002390
2391 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2392 TemplateSpecializationTypeLoc TL
2393 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2394 TL.setTemplateNameLoc(NameLoc);
2395 TL.setLAngleLoc(Args.getLAngleLoc());
2396 TL.setRAngleLoc(Args.getRAngleLoc());
2397 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2398 TL.setArgLocInfo(i, Args[i].getLocInfo());
2399 return DI;
2400}
2401
Mike Stump1eb44332009-09-09 15:08:12 +00002402QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002403ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002404 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002405 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002406 assert(!Template.getAsDependentTemplateName() &&
2407 "No dependent template names here!");
2408
John McCalld5532b62009-11-23 01:53:49 +00002409 unsigned NumArgs = Args.size();
2410
Chris Lattner5f9e2722011-07-23 10:55:15 +00002411 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002412 ArgVec.reserve(NumArgs);
2413 for (unsigned i = 0; i != NumArgs; ++i)
2414 ArgVec.push_back(Args[i].getArgument());
2415
John McCall31f17ec2010-04-27 00:57:59 +00002416 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002417 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002418}
2419
2420QualType
2421ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002422 const TemplateArgument *Args,
2423 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002424 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002425 assert(!Template.getAsDependentTemplateName() &&
2426 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002427 // Look through qualified template names.
2428 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2429 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002430
Richard Smith3e4c6c42011-05-05 21:57:07 +00002431 bool isTypeAlias =
2432 Template.getAsTemplateDecl() &&
2433 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2434
2435 QualType CanonType;
2436 if (!Underlying.isNull())
2437 CanonType = getCanonicalType(Underlying);
2438 else {
2439 assert(!isTypeAlias &&
2440 "Underlying type for template alias must be computed by caller");
2441 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2442 NumArgs);
2443 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002444
Douglas Gregor1275ae02009-07-28 23:00:59 +00002445 // Allocate the (non-canonical) template specialization type, but don't
2446 // try to unique it: these types typically have location information that
2447 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002448 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2449 sizeof(TemplateArgument) * NumArgs +
2450 (isTypeAlias ? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00002451 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002452 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00002453 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00002454 Args, NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002455 CanonType,
2456 isTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00002457
Douglas Gregor55f6b142009-02-09 18:46:07 +00002458 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002459 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002460}
2461
Mike Stump1eb44332009-09-09 15:08:12 +00002462QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002463ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2464 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002465 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002466 assert(!Template.getAsDependentTemplateName() &&
2467 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002468 assert((!Template.getAsTemplateDecl() ||
2469 !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2470 "Underlying type for template alias must be computed by caller");
2471
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002472 // Look through qualified template names.
2473 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2474 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002475
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002476 // Build the canonical template specialization type.
2477 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002478 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002479 CanonArgs.reserve(NumArgs);
2480 for (unsigned I = 0; I != NumArgs; ++I)
2481 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2482
2483 // Determine whether this canonical template specialization type already
2484 // exists.
2485 llvm::FoldingSetNodeID ID;
2486 TemplateSpecializationType::Profile(ID, CanonTemplate,
2487 CanonArgs.data(), NumArgs, *this);
2488
2489 void *InsertPos = 0;
2490 TemplateSpecializationType *Spec
2491 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2492
2493 if (!Spec) {
2494 // Allocate a new canonical template specialization type.
2495 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2496 sizeof(TemplateArgument) * NumArgs),
2497 TypeAlignment);
2498 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2499 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002500 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002501 Types.push_back(Spec);
2502 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2503 }
2504
2505 assert(Spec->isDependentType() &&
2506 "Non-dependent template-id type must have a canonical type");
2507 return QualType(Spec, 0);
2508}
2509
2510QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002511ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2512 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002513 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002514 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002515 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002516
2517 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002518 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002519 if (T)
2520 return QualType(T, 0);
2521
Douglas Gregor789b1f62010-02-04 18:10:26 +00002522 QualType Canon = NamedType;
2523 if (!Canon.isCanonical()) {
2524 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002525 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2526 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002527 (void)CheckT;
2528 }
2529
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002530 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002531 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002532 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002533 return QualType(T, 0);
2534}
2535
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002536QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002537ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002538 llvm::FoldingSetNodeID ID;
2539 ParenType::Profile(ID, InnerType);
2540
2541 void *InsertPos = 0;
2542 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2543 if (T)
2544 return QualType(T, 0);
2545
2546 QualType Canon = InnerType;
2547 if (!Canon.isCanonical()) {
2548 Canon = getCanonicalType(InnerType);
2549 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2550 assert(!CheckT && "Paren canonical type broken");
2551 (void)CheckT;
2552 }
2553
2554 T = new (*this) ParenType(InnerType, Canon);
2555 Types.push_back(T);
2556 ParenTypes.InsertNode(T, InsertPos);
2557 return QualType(T, 0);
2558}
2559
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002560QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2561 NestedNameSpecifier *NNS,
2562 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002563 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002564 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2565
2566 if (Canon.isNull()) {
2567 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002568 ElaboratedTypeKeyword CanonKeyword = Keyword;
2569 if (Keyword == ETK_None)
2570 CanonKeyword = ETK_Typename;
2571
2572 if (CanonNNS != NNS || CanonKeyword != Keyword)
2573 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002574 }
2575
2576 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002577 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002578
2579 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002580 DependentNameType *T
2581 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002582 if (T)
2583 return QualType(T, 0);
2584
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002585 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002586 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002587 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002588 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002589}
2590
Mike Stump1eb44332009-09-09 15:08:12 +00002591QualType
John McCall33500952010-06-11 00:33:02 +00002592ASTContext::getDependentTemplateSpecializationType(
2593 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002594 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002595 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002596 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00002597 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00002598 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00002599 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2600 ArgCopy.push_back(Args[I].getArgument());
2601 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2602 ArgCopy.size(),
2603 ArgCopy.data());
2604}
2605
2606QualType
2607ASTContext::getDependentTemplateSpecializationType(
2608 ElaboratedTypeKeyword Keyword,
2609 NestedNameSpecifier *NNS,
2610 const IdentifierInfo *Name,
2611 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002612 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00002613 assert((!NNS || NNS->isDependent()) &&
2614 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00002615
Douglas Gregor789b1f62010-02-04 18:10:26 +00002616 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002617 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2618 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002619
2620 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002621 DependentTemplateSpecializationType *T
2622 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002623 if (T)
2624 return QualType(T, 0);
2625
John McCall33500952010-06-11 00:33:02 +00002626 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002627
John McCall33500952010-06-11 00:33:02 +00002628 ElaboratedTypeKeyword CanonKeyword = Keyword;
2629 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2630
2631 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002632 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00002633 for (unsigned I = 0; I != NumArgs; ++I) {
2634 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2635 if (!CanonArgs[I].structurallyEquals(Args[I]))
2636 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002637 }
2638
John McCall33500952010-06-11 00:33:02 +00002639 QualType Canon;
2640 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2641 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2642 Name, NumArgs,
2643 CanonArgs.data());
2644
2645 // Find the insert position again.
2646 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2647 }
2648
2649 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2650 sizeof(TemplateArgument) * NumArgs),
2651 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002652 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002653 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002654 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002655 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002656 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002657}
2658
Douglas Gregorcded4f62011-01-14 17:04:44 +00002659QualType ASTContext::getPackExpansionType(QualType Pattern,
2660 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00002661 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002662 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002663
2664 assert(Pattern->containsUnexpandedParameterPack() &&
2665 "Pack expansions must expand one or more parameter packs");
2666 void *InsertPos = 0;
2667 PackExpansionType *T
2668 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2669 if (T)
2670 return QualType(T, 0);
2671
2672 QualType Canon;
2673 if (!Pattern.isCanonical()) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002674 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002675
2676 // Find the insert position again.
2677 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2678 }
2679
Douglas Gregorcded4f62011-01-14 17:04:44 +00002680 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002681 Types.push_back(T);
2682 PackExpansionTypes.InsertNode(T, InsertPos);
2683 return QualType(T, 0);
2684}
2685
Chris Lattner88cb27a2008-04-07 04:56:42 +00002686/// CmpProtocolNames - Comparison predicate for sorting protocols
2687/// alphabetically.
2688static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2689 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002690 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002691}
2692
John McCallc12c5bb2010-05-15 11:32:37 +00002693static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002694 unsigned NumProtocols) {
2695 if (NumProtocols == 0) return true;
2696
2697 for (unsigned i = 1; i != NumProtocols; ++i)
2698 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2699 return false;
2700 return true;
2701}
2702
2703static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002704 unsigned &NumProtocols) {
2705 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002706
Chris Lattner88cb27a2008-04-07 04:56:42 +00002707 // Sort protocols, keyed by name.
2708 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2709
2710 // Remove duplicates.
2711 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2712 NumProtocols = ProtocolsEnd-Protocols;
2713}
2714
John McCallc12c5bb2010-05-15 11:32:37 +00002715QualType ASTContext::getObjCObjectType(QualType BaseType,
2716 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00002717 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002718 // If the base type is an interface and there aren't any protocols
2719 // to add, then the interface type will do just fine.
2720 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2721 return BaseType;
2722
2723 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002724 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002725 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002726 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002727 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2728 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002729
John McCallc12c5bb2010-05-15 11:32:37 +00002730 // Build the canonical type, which has the canonical base type and
2731 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002732 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002733 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2734 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2735 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002736 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00002737 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002738 unsigned UniqueCount = NumProtocols;
2739
John McCall54e14c42009-10-22 22:37:11 +00002740 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002741 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2742 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002743 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002744 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2745 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002746 }
2747
2748 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002749 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2750 }
2751
2752 unsigned Size = sizeof(ObjCObjectTypeImpl);
2753 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2754 void *Mem = Allocate(Size, TypeAlignment);
2755 ObjCObjectTypeImpl *T =
2756 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2757
2758 Types.push_back(T);
2759 ObjCObjectTypes.InsertNode(T, InsertPos);
2760 return QualType(T, 0);
2761}
2762
2763/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2764/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002765QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002766 llvm::FoldingSetNodeID ID;
2767 ObjCObjectPointerType::Profile(ID, ObjectT);
2768
2769 void *InsertPos = 0;
2770 if (ObjCObjectPointerType *QT =
2771 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2772 return QualType(QT, 0);
2773
2774 // Find the canonical object type.
2775 QualType Canonical;
2776 if (!ObjectT.isCanonical()) {
2777 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2778
2779 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002780 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2781 }
2782
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002783 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002784 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2785 ObjCObjectPointerType *QType =
2786 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002787
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002788 Types.push_back(QType);
2789 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002790 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002791}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002792
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002793/// getObjCInterfaceType - Return the unique reference to the type for the
2794/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad4ba2a172011-01-12 09:06:06 +00002795QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002796 if (Decl->TypeForDecl)
2797 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002798
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002799 // FIXME: redeclarations?
2800 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2801 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2802 Decl->TypeForDecl = T;
2803 Types.push_back(T);
2804 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002805}
2806
Douglas Gregor72564e72009-02-26 23:50:07 +00002807/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2808/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002809/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002810/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002811/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002812QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002813 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002814 if (tofExpr->isTypeDependent()) {
2815 llvm::FoldingSetNodeID ID;
2816 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002817
Douglas Gregorb1975722009-07-30 23:18:24 +00002818 void *InsertPos = 0;
2819 DependentTypeOfExprType *Canon
2820 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2821 if (Canon) {
2822 // We already have a "canonical" version of an identical, dependent
2823 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002824 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002825 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00002826 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00002827 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002828 Canon
2829 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002830 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2831 toe = Canon;
2832 }
2833 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002834 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002835 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002836 }
Steve Naroff9752f252007-08-01 18:02:17 +00002837 Types.push_back(toe);
2838 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002839}
2840
Steve Naroff9752f252007-08-01 18:02:17 +00002841/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2842/// TypeOfType AST's. The only motivation to unique these nodes would be
2843/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002844/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002845/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002846QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002847 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002848 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002849 Types.push_back(tot);
2850 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002851}
2852
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002853/// getDecltypeForExpr - Given an expr, will return the decltype for that
2854/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad4ba2a172011-01-12 09:06:06 +00002855static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002856 if (e->isTypeDependent())
2857 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002858
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002859 // If e is an id expression or a class member access, decltype(e) is defined
2860 // as the type of the entity named by e.
2861 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2862 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2863 return VD->getType();
2864 }
2865 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2866 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2867 return FD->getType();
2868 }
2869 // If e is a function call or an invocation of an overloaded operator,
2870 // (parentheses around e are ignored), decltype(e) is defined as the
2871 // return type of that function.
2872 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2873 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002874
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002875 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002876
2877 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002878 // defined as T&, otherwise decltype(e) is defined as T.
John McCall7eb0a9e2010-11-24 05:12:34 +00002879 if (e->isLValue())
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002880 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002881
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002882 return T;
2883}
2884
Anders Carlsson395b4752009-06-24 19:06:50 +00002885/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2886/// DecltypeType AST's. The only motivation to unique these nodes would be
2887/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002888/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00002889/// on canonical types (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002890QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002891 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00002892
2893 // C++0x [temp.type]p2:
2894 // If an expression e involves a template parameter, decltype(e) denotes a
2895 // unique dependent type. Two such decltype-specifiers refer to the same
2896 // type only if their expressions are equivalent (14.5.6.1).
2897 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002898 llvm::FoldingSetNodeID ID;
2899 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002900
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002901 void *InsertPos = 0;
2902 DependentDecltypeType *Canon
2903 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2904 if (Canon) {
2905 // We already have a "canonical" version of an equivalent, dependent
2906 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002907 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002908 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00002909 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002910 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002911 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002912 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2913 dt = Canon;
2914 }
2915 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002916 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002917 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002918 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002919 Types.push_back(dt);
2920 return QualType(dt, 0);
2921}
2922
Sean Huntca63c202011-05-24 22:41:36 +00002923/// getUnaryTransformationType - We don't unique these, since the memory
2924/// savings are minimal and these are rare.
2925QualType ASTContext::getUnaryTransformType(QualType BaseType,
2926 QualType UnderlyingType,
2927 UnaryTransformType::UTTKind Kind)
2928 const {
2929 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00002930 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2931 Kind,
2932 UnderlyingType->isDependentType() ?
2933 QualType() : UnderlyingType);
Sean Huntca63c202011-05-24 22:41:36 +00002934 Types.push_back(Ty);
2935 return QualType(Ty, 0);
2936}
2937
Richard Smith483b9f32011-02-21 20:05:19 +00002938/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00002939QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00002940 void *InsertPos = 0;
2941 if (!DeducedType.isNull()) {
2942 // Look in the folding set for an existing type.
2943 llvm::FoldingSetNodeID ID;
2944 AutoType::Profile(ID, DeducedType);
2945 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2946 return QualType(AT, 0);
2947 }
2948
2949 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2950 Types.push_back(AT);
2951 if (InsertPos)
2952 AutoTypes.InsertNode(AT, InsertPos);
2953 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00002954}
2955
Eli Friedmanb001de72011-10-06 23:00:33 +00002956/// getAtomicType - Return the uniqued reference to the atomic type for
2957/// the given value type.
2958QualType ASTContext::getAtomicType(QualType T) const {
2959 // Unique pointers, to guarantee there is only one pointer of a particular
2960 // structure.
2961 llvm::FoldingSetNodeID ID;
2962 AtomicType::Profile(ID, T);
2963
2964 void *InsertPos = 0;
2965 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
2966 return QualType(AT, 0);
2967
2968 // If the atomic value type isn't canonical, this won't be a canonical type
2969 // either, so fill in the canonical type field.
2970 QualType Canonical;
2971 if (!T.isCanonical()) {
2972 Canonical = getAtomicType(getCanonicalType(T));
2973
2974 // Get the new insert position for the node we care about.
2975 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
2976 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2977 }
2978 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
2979 Types.push_back(New);
2980 AtomicTypes.InsertNode(New, InsertPos);
2981 return QualType(New, 0);
2982}
2983
Richard Smithad762fc2011-04-14 22:09:26 +00002984/// getAutoDeductType - Get type pattern for deducing against 'auto'.
2985QualType ASTContext::getAutoDeductType() const {
2986 if (AutoDeductTy.isNull())
2987 AutoDeductTy = getAutoType(QualType());
2988 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
2989 return AutoDeductTy;
2990}
2991
2992/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
2993QualType ASTContext::getAutoRRefDeductType() const {
2994 if (AutoRRefDeductTy.isNull())
2995 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
2996 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
2997 return AutoRRefDeductTy;
2998}
2999
Reid Spencer5f016e22007-07-11 17:01:13 +00003000/// getTagDeclType - Return the unique reference to the type for the
3001/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003002QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003003 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003004 // FIXME: What is the design on getTagDeclType when it requires casting
3005 // away const? mutable?
3006 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003007}
3008
Mike Stump1eb44332009-09-09 15:08:12 +00003009/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3010/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3011/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003012CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003013 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003014}
3015
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003016/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3017CanQualType ASTContext::getIntMaxType() const {
3018 return getFromTargetType(Target->getIntMaxType());
3019}
3020
3021/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3022CanQualType ASTContext::getUIntMaxType() const {
3023 return getFromTargetType(Target->getUIntMaxType());
3024}
3025
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003026/// getSignedWCharType - Return the type of "signed wchar_t".
3027/// Used when in C++, as a GCC extension.
3028QualType ASTContext::getSignedWCharType() const {
3029 // FIXME: derive from "Target" ?
3030 return WCharTy;
3031}
3032
3033/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3034/// Used when in C++, as a GCC extension.
3035QualType ASTContext::getUnsignedWCharType() const {
3036 // FIXME: derive from "Target" ?
3037 return UnsignedIntTy;
3038}
3039
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003040/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003041/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3042QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003043 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003044}
3045
Chris Lattnere6327742008-04-02 05:18:44 +00003046//===----------------------------------------------------------------------===//
3047// Type Operators
3048//===----------------------------------------------------------------------===//
3049
Jay Foad4ba2a172011-01-12 09:06:06 +00003050CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003051 // Push qualifiers into arrays, and then discard any remaining
3052 // qualifiers.
3053 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003054 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003055 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003056 QualType Result;
3057 if (isa<ArrayType>(Ty)) {
3058 Result = getArrayDecayedType(QualType(Ty,0));
3059 } else if (isa<FunctionType>(Ty)) {
3060 Result = getPointerType(QualType(Ty, 0));
3061 } else {
3062 Result = QualType(Ty, 0);
3063 }
3064
3065 return CanQualType::CreateUnsafe(Result);
3066}
3067
John McCall62c28c82011-01-18 07:41:22 +00003068QualType ASTContext::getUnqualifiedArrayType(QualType type,
3069 Qualifiers &quals) {
3070 SplitQualType splitType = type.getSplitUnqualifiedType();
3071
3072 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3073 // the unqualified desugared type and then drops it on the floor.
3074 // We then have to strip that sugar back off with
3075 // getUnqualifiedDesugaredType(), which is silly.
3076 const ArrayType *AT =
3077 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
3078
3079 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003080 if (!AT) {
John McCall62c28c82011-01-18 07:41:22 +00003081 quals = splitType.second;
3082 return QualType(splitType.first, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003083 }
3084
John McCall62c28c82011-01-18 07:41:22 +00003085 // Otherwise, recurse on the array's element type.
3086 QualType elementType = AT->getElementType();
3087 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3088
3089 // If that didn't change the element type, AT has no qualifiers, so we
3090 // can just use the results in splitType.
3091 if (elementType == unqualElementType) {
3092 assert(quals.empty()); // from the recursive call
3093 quals = splitType.second;
3094 return QualType(splitType.first, 0);
3095 }
3096
3097 // Otherwise, add in the qualifiers from the outermost type, then
3098 // build the type back up.
3099 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003100
Douglas Gregor9dadd942010-05-17 18:45:21 +00003101 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003102 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003103 CAT->getSizeModifier(), 0);
3104 }
3105
Douglas Gregor9dadd942010-05-17 18:45:21 +00003106 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003107 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003108 }
3109
Douglas Gregor9dadd942010-05-17 18:45:21 +00003110 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003111 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003112 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003113 VAT->getSizeModifier(),
3114 VAT->getIndexTypeCVRQualifiers(),
3115 VAT->getBracketsRange());
3116 }
3117
3118 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003119 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003120 DSAT->getSizeModifier(), 0,
3121 SourceRange());
3122}
3123
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003124/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3125/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3126/// they point to and return true. If T1 and T2 aren't pointer types
3127/// or pointer-to-member types, or if they are not similar at this
3128/// level, returns false and leaves T1 and T2 unchanged. Top-level
3129/// qualifiers on T1 and T2 are ignored. This function will typically
3130/// be called in a loop that successively "unwraps" pointer and
3131/// pointer-to-member types to compare them at each level.
3132bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3133 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3134 *T2PtrType = T2->getAs<PointerType>();
3135 if (T1PtrType && T2PtrType) {
3136 T1 = T1PtrType->getPointeeType();
3137 T2 = T2PtrType->getPointeeType();
3138 return true;
3139 }
3140
3141 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3142 *T2MPType = T2->getAs<MemberPointerType>();
3143 if (T1MPType && T2MPType &&
3144 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3145 QualType(T2MPType->getClass(), 0))) {
3146 T1 = T1MPType->getPointeeType();
3147 T2 = T2MPType->getPointeeType();
3148 return true;
3149 }
3150
3151 if (getLangOptions().ObjC1) {
3152 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3153 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3154 if (T1OPType && T2OPType) {
3155 T1 = T1OPType->getPointeeType();
3156 T2 = T2OPType->getPointeeType();
3157 return true;
3158 }
3159 }
3160
3161 // FIXME: Block pointers, too?
3162
3163 return false;
3164}
3165
Jay Foad4ba2a172011-01-12 09:06:06 +00003166DeclarationNameInfo
3167ASTContext::getNameForTemplate(TemplateName Name,
3168 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003169 switch (Name.getKind()) {
3170 case TemplateName::QualifiedTemplate:
3171 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003172 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003173 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3174 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003175
John McCall14606042011-06-30 08:33:18 +00003176 case TemplateName::OverloadedTemplate: {
3177 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3178 // DNInfo work in progress: CHECKME: what about DNLoc?
3179 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3180 }
3181
3182 case TemplateName::DependentTemplate: {
3183 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003184 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003185 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003186 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3187 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003188 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003189 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3190 // DNInfo work in progress: FIXME: source locations?
3191 DeclarationNameLoc DNLoc;
3192 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3193 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3194 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003195 }
3196 }
3197
John McCall14606042011-06-30 08:33:18 +00003198 case TemplateName::SubstTemplateTemplateParm: {
3199 SubstTemplateTemplateParmStorage *subst
3200 = Name.getAsSubstTemplateTemplateParm();
3201 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3202 NameLoc);
3203 }
3204
3205 case TemplateName::SubstTemplateTemplateParmPack: {
3206 SubstTemplateTemplateParmPackStorage *subst
3207 = Name.getAsSubstTemplateTemplateParmPack();
3208 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3209 NameLoc);
3210 }
3211 }
3212
3213 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003214}
3215
Jay Foad4ba2a172011-01-12 09:06:06 +00003216TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003217 switch (Name.getKind()) {
3218 case TemplateName::QualifiedTemplate:
3219 case TemplateName::Template: {
3220 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003221 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003222 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003223 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3224
3225 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003226 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003227 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003228
John McCall14606042011-06-30 08:33:18 +00003229 case TemplateName::OverloadedTemplate:
3230 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003231
John McCall14606042011-06-30 08:33:18 +00003232 case TemplateName::DependentTemplate: {
3233 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3234 assert(DTN && "Non-dependent template names must refer to template decls.");
3235 return DTN->CanonicalTemplateName;
3236 }
3237
3238 case TemplateName::SubstTemplateTemplateParm: {
3239 SubstTemplateTemplateParmStorage *subst
3240 = Name.getAsSubstTemplateTemplateParm();
3241 return getCanonicalTemplateName(subst->getReplacement());
3242 }
3243
3244 case TemplateName::SubstTemplateTemplateParmPack: {
3245 SubstTemplateTemplateParmPackStorage *subst
3246 = Name.getAsSubstTemplateTemplateParmPack();
3247 TemplateTemplateParmDecl *canonParameter
3248 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3249 TemplateArgument canonArgPack
3250 = getCanonicalTemplateArgument(subst->getArgumentPack());
3251 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3252 }
3253 }
3254
3255 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003256}
3257
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003258bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3259 X = getCanonicalTemplateName(X);
3260 Y = getCanonicalTemplateName(Y);
3261 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3262}
3263
Mike Stump1eb44332009-09-09 15:08:12 +00003264TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003265ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003266 switch (Arg.getKind()) {
3267 case TemplateArgument::Null:
3268 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003269
Douglas Gregor1275ae02009-07-28 23:00:59 +00003270 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003271 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003272
Douglas Gregor1275ae02009-07-28 23:00:59 +00003273 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00003274 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003275
Douglas Gregor788cd062009-11-11 01:00:40 +00003276 case TemplateArgument::Template:
3277 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003278
3279 case TemplateArgument::TemplateExpansion:
3280 return TemplateArgument(getCanonicalTemplateName(
3281 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003282 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003283
Douglas Gregor1275ae02009-07-28 23:00:59 +00003284 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00003285 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003286 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003287
Douglas Gregor1275ae02009-07-28 23:00:59 +00003288 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003289 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003290
Douglas Gregor1275ae02009-07-28 23:00:59 +00003291 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003292 if (Arg.pack_size() == 0)
3293 return Arg;
3294
Douglas Gregor910f8002010-11-07 23:05:16 +00003295 TemplateArgument *CanonArgs
3296 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003297 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003298 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003299 AEnd = Arg.pack_end();
3300 A != AEnd; (void)++A, ++Idx)
3301 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003302
Douglas Gregor910f8002010-11-07 23:05:16 +00003303 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003304 }
3305 }
3306
3307 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00003308 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00003309}
3310
Douglas Gregord57959a2009-03-27 23:10:48 +00003311NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003312ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003313 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003314 return 0;
3315
3316 switch (NNS->getKind()) {
3317 case NestedNameSpecifier::Identifier:
3318 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003319 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003320 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3321 NNS->getAsIdentifier());
3322
3323 case NestedNameSpecifier::Namespace:
3324 // A namespace is canonical; build a nested-name-specifier with
3325 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003326 return NestedNameSpecifier::Create(*this, 0,
3327 NNS->getAsNamespace()->getOriginalNamespace());
3328
3329 case NestedNameSpecifier::NamespaceAlias:
3330 // A namespace is canonical; build a nested-name-specifier with
3331 // this namespace and no prefix.
3332 return NestedNameSpecifier::Create(*this, 0,
3333 NNS->getAsNamespaceAlias()->getNamespace()
3334 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003335
3336 case NestedNameSpecifier::TypeSpec:
3337 case NestedNameSpecifier::TypeSpecWithTemplate: {
3338 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003339
3340 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3341 // break it apart into its prefix and identifier, then reconsititute those
3342 // as the canonical nested-name-specifier. This is required to canonicalize
3343 // a dependent nested-name-specifier involving typedefs of dependent-name
3344 // types, e.g.,
3345 // typedef typename T::type T1;
3346 // typedef typename T1::type T2;
3347 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3348 NestedNameSpecifier *Prefix
3349 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3350 return NestedNameSpecifier::Create(*this, Prefix,
3351 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3352 }
3353
Douglas Gregor643f8432010-11-04 00:14:23 +00003354 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor264bf662010-11-04 00:09:33 +00003355 if (const DependentTemplateSpecializationType *DTST
3356 = T->getAs<DependentTemplateSpecializationType>()) {
3357 NestedNameSpecifier *Prefix
3358 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003359
3360 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3361 Prefix, DTST->getIdentifier(),
3362 DTST->getNumArgs(),
3363 DTST->getArgs());
Douglas Gregor264bf662010-11-04 00:09:33 +00003364 T = getCanonicalType(T);
3365 }
3366
John McCall3b657512011-01-19 10:06:00 +00003367 return NestedNameSpecifier::Create(*this, 0, false,
3368 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003369 }
3370
3371 case NestedNameSpecifier::Global:
3372 // The global specifier is canonical and unique.
3373 return NNS;
3374 }
3375
3376 // Required to silence a GCC warning
3377 return 0;
3378}
3379
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003380
Jay Foad4ba2a172011-01-12 09:06:06 +00003381const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003382 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003383 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003384 // Handle the common positive case fast.
3385 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3386 return AT;
3387 }
Mike Stump1eb44332009-09-09 15:08:12 +00003388
John McCall0953e762009-09-24 19:53:00 +00003389 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003390 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003391 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003392
John McCall0953e762009-09-24 19:53:00 +00003393 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003394 // implements C99 6.7.3p8: "If the specification of an array type includes
3395 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003396
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003397 // If we get here, we either have type qualifiers on the type, or we have
3398 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003399 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003400
John McCall3b657512011-01-19 10:06:00 +00003401 SplitQualType split = T.getSplitDesugaredType();
3402 Qualifiers qs = split.second;
Mike Stump1eb44332009-09-09 15:08:12 +00003403
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003404 // If we have a simple case, just return now.
John McCall3b657512011-01-19 10:06:00 +00003405 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3406 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003407 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003408
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003409 // Otherwise, we have an array and we have qualifiers on it. Push the
3410 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003411 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003412
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003413 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3414 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3415 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003416 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003417 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3418 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3419 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003420 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003421
Mike Stump1eb44332009-09-09 15:08:12 +00003422 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003423 = dyn_cast<DependentSizedArrayType>(ATy))
3424 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003425 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003426 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003427 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003428 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003429 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003430
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003431 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003432 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003433 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003434 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003435 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003436 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003437}
3438
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003439QualType ASTContext::getAdjustedParameterType(QualType T) {
3440 // C99 6.7.5.3p7:
3441 // A declaration of a parameter as "array of type" shall be
3442 // adjusted to "qualified pointer to type", where the type
3443 // qualifiers (if any) are those specified within the [ and ] of
3444 // the array type derivation.
3445 if (T->isArrayType())
3446 return getArrayDecayedType(T);
3447
3448 // C99 6.7.5.3p8:
3449 // A declaration of a parameter as "function returning type"
3450 // shall be adjusted to "pointer to function returning type", as
3451 // in 6.3.2.1.
3452 if (T->isFunctionType())
3453 return getPointerType(T);
3454
3455 return T;
3456}
3457
3458QualType ASTContext::getSignatureParameterType(QualType T) {
3459 T = getVariableArrayDecayedType(T);
3460 T = getAdjustedParameterType(T);
3461 return T.getUnqualifiedType();
3462}
3463
Chris Lattnere6327742008-04-02 05:18:44 +00003464/// getArrayDecayedType - Return the properly qualified result of decaying the
3465/// specified array type to a pointer. This operation is non-trivial when
3466/// handling typedefs etc. The canonical type of "T" must be an array type,
3467/// this returns a pointer to a properly qualified element of the array.
3468///
3469/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003470QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003471 // Get the element type with 'getAsArrayType' so that we don't lose any
3472 // typedefs in the element type of the array. This also handles propagation
3473 // of type qualifiers from the array type into the element type if present
3474 // (C99 6.7.3p8).
3475 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3476 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003477
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003478 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003479
3480 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003481 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003482}
3483
John McCall3b657512011-01-19 10:06:00 +00003484QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3485 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003486}
3487
John McCall3b657512011-01-19 10:06:00 +00003488QualType ASTContext::getBaseElementType(QualType type) const {
3489 Qualifiers qs;
3490 while (true) {
3491 SplitQualType split = type.getSplitDesugaredType();
3492 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3493 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003494
John McCall3b657512011-01-19 10:06:00 +00003495 type = array->getElementType();
3496 qs.addConsistentQualifiers(split.second);
3497 }
Mike Stump1eb44332009-09-09 15:08:12 +00003498
John McCall3b657512011-01-19 10:06:00 +00003499 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003500}
3501
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003502/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003503uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003504ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3505 uint64_t ElementCount = 1;
3506 do {
3507 ElementCount *= CA->getSize().getZExtValue();
3508 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3509 } while (CA);
3510 return ElementCount;
3511}
3512
Reid Spencer5f016e22007-07-11 17:01:13 +00003513/// getFloatingRank - Return a relative rank for floating point types.
3514/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003515static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003516 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003517 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003518
John McCall183700f2009-09-21 23:43:11 +00003519 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3520 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003521 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00003522 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00003523 case BuiltinType::Float: return FloatRank;
3524 case BuiltinType::Double: return DoubleRank;
3525 case BuiltinType::LongDouble: return LongDoubleRank;
3526 }
3527}
3528
Mike Stump1eb44332009-09-09 15:08:12 +00003529/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3530/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003531/// 'typeDomain' is a real floating point or complex type.
3532/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003533QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3534 QualType Domain) const {
3535 FloatingRank EltRank = getFloatingRank(Size);
3536 if (Domain->isComplexType()) {
3537 switch (EltRank) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003538 default: llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00003539 case FloatRank: return FloatComplexTy;
3540 case DoubleRank: return DoubleComplexTy;
3541 case LongDoubleRank: return LongDoubleComplexTy;
3542 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003543 }
Chris Lattner1361b112008-04-06 23:58:54 +00003544
3545 assert(Domain->isRealFloatingType() && "Unknown domain!");
3546 switch (EltRank) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003547 default: llvm_unreachable("getFloatingRank(): illegal value for rank");
Chris Lattner1361b112008-04-06 23:58:54 +00003548 case FloatRank: return FloatTy;
3549 case DoubleRank: return DoubleTy;
3550 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003551 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003552}
3553
Chris Lattner7cfeb082008-04-06 23:55:33 +00003554/// getFloatingTypeOrder - Compare the rank of the two specified floating
3555/// point types, ignoring the domain of the type (i.e. 'double' ==
3556/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003557/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003558int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003559 FloatingRank LHSR = getFloatingRank(LHS);
3560 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003561
Chris Lattnera75cea32008-04-06 23:38:49 +00003562 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003563 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003564 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003565 return 1;
3566 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003567}
3568
Chris Lattnerf52ab252008-04-06 22:59:24 +00003569/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3570/// routine will assert if passed a built-in type that isn't an integer or enum,
3571/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003572unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003573 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003574
Chris Lattnerf52ab252008-04-06 22:59:24 +00003575 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003576 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00003577 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003578 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003579 case BuiltinType::Char_S:
3580 case BuiltinType::Char_U:
3581 case BuiltinType::SChar:
3582 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003583 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003584 case BuiltinType::Short:
3585 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003586 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003587 case BuiltinType::Int:
3588 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003589 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003590 case BuiltinType::Long:
3591 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003592 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003593 case BuiltinType::LongLong:
3594 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003595 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003596 case BuiltinType::Int128:
3597 case BuiltinType::UInt128:
3598 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003599 }
3600}
3601
Eli Friedman04e83572009-08-20 04:21:42 +00003602/// \brief Whether this is a promotable bitfield reference according
3603/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3604///
3605/// \returns the type this bit-field will promote to, or NULL if no
3606/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00003607QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003608 if (E->isTypeDependent() || E->isValueDependent())
3609 return QualType();
3610
Eli Friedman04e83572009-08-20 04:21:42 +00003611 FieldDecl *Field = E->getBitField();
3612 if (!Field)
3613 return QualType();
3614
3615 QualType FT = Field->getType();
3616
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003617 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00003618 uint64_t IntSize = getTypeSize(IntTy);
3619 // GCC extension compatibility: if the bit-field size is less than or equal
3620 // to the size of int, it gets promoted no matter what its type is.
3621 // For instance, unsigned long bf : 4 gets promoted to signed int.
3622 if (BitWidth < IntSize)
3623 return IntTy;
3624
3625 if (BitWidth == IntSize)
3626 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3627
3628 // Types bigger than int are not subject to promotions, and therefore act
3629 // like the base type.
3630 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3631 // is ridiculous.
3632 return QualType();
3633}
3634
Eli Friedmana95d7572009-08-19 07:44:53 +00003635/// getPromotedIntegerType - Returns the type that Promotable will
3636/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3637/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003638QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003639 assert(!Promotable.isNull());
3640 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003641 if (const EnumType *ET = Promotable->getAs<EnumType>())
3642 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00003643
3644 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3645 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3646 // (3.9.1) can be converted to a prvalue of the first of the following
3647 // types that can represent all the values of its underlying type:
3648 // int, unsigned int, long int, unsigned long int, long long int, or
3649 // unsigned long long int [...]
3650 // FIXME: Is there some better way to compute this?
3651 if (BT->getKind() == BuiltinType::WChar_S ||
3652 BT->getKind() == BuiltinType::WChar_U ||
3653 BT->getKind() == BuiltinType::Char16 ||
3654 BT->getKind() == BuiltinType::Char32) {
3655 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3656 uint64_t FromSize = getTypeSize(BT);
3657 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3658 LongLongTy, UnsignedLongLongTy };
3659 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3660 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3661 if (FromSize < ToSize ||
3662 (FromSize == ToSize &&
3663 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3664 return PromoteTypes[Idx];
3665 }
3666 llvm_unreachable("char type should fit into long long");
3667 }
3668 }
3669
3670 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00003671 if (Promotable->isSignedIntegerType())
3672 return IntTy;
3673 uint64_t PromotableSize = getTypeSize(Promotable);
3674 uint64_t IntSize = getTypeSize(IntTy);
3675 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3676 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3677}
3678
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003679/// \brief Recurses in pointer/array types until it finds an objc retainable
3680/// type and returns its ownership.
3681Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3682 while (!T.isNull()) {
3683 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3684 return T.getObjCLifetime();
3685 if (T->isArrayType())
3686 T = getBaseElementType(T);
3687 else if (const PointerType *PT = T->getAs<PointerType>())
3688 T = PT->getPointeeType();
3689 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00003690 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003691 else
3692 break;
3693 }
3694
3695 return Qualifiers::OCL_None;
3696}
3697
Mike Stump1eb44332009-09-09 15:08:12 +00003698/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003699/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003700/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003701int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00003702 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3703 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003704 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003705
Chris Lattnerf52ab252008-04-06 22:59:24 +00003706 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3707 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003708
Chris Lattner7cfeb082008-04-06 23:55:33 +00003709 unsigned LHSRank = getIntegerRank(LHSC);
3710 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003711
Chris Lattner7cfeb082008-04-06 23:55:33 +00003712 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3713 if (LHSRank == RHSRank) return 0;
3714 return LHSRank > RHSRank ? 1 : -1;
3715 }
Mike Stump1eb44332009-09-09 15:08:12 +00003716
Chris Lattner7cfeb082008-04-06 23:55:33 +00003717 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3718 if (LHSUnsigned) {
3719 // If the unsigned [LHS] type is larger, return it.
3720 if (LHSRank >= RHSRank)
3721 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003722
Chris Lattner7cfeb082008-04-06 23:55:33 +00003723 // If the signed type can represent all values of the unsigned type, it
3724 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003725 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003726 return -1;
3727 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003728
Chris Lattner7cfeb082008-04-06 23:55:33 +00003729 // If the unsigned [RHS] type is larger, return it.
3730 if (RHSRank >= LHSRank)
3731 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003732
Chris Lattner7cfeb082008-04-06 23:55:33 +00003733 // If the signed type can represent all values of the unsigned type, it
3734 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003735 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003736 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003737}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003738
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003739static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003740CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3741 DeclContext *DC, IdentifierInfo *Id) {
3742 SourceLocation Loc;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003743 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003744 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003745 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003746 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003747}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003748
Mike Stump1eb44332009-09-09 15:08:12 +00003749// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003750QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003751 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003752 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003753 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003754 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003755 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003756
Anders Carlssonf06273f2007-11-19 00:25:30 +00003757 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003758
Anders Carlsson71993dd2007-08-17 05:31:46 +00003759 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003760 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003761 // int flags;
3762 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003763 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003764 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003765 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003766 FieldTypes[3] = LongTy;
3767
Anders Carlsson71993dd2007-08-17 05:31:46 +00003768 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003769 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003770 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003771 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00003772 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003773 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003774 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003775 /*Mutable=*/false,
3776 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003777 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003778 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003779 }
3780
Douglas Gregor838db382010-02-11 01:19:42 +00003781 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003782 }
Mike Stump1eb44332009-09-09 15:08:12 +00003783
Anders Carlsson71993dd2007-08-17 05:31:46 +00003784 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003785}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003786
Douglas Gregor319ac892009-04-23 22:29:11 +00003787void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003788 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003789 assert(Rec && "Invalid CFConstantStringType");
3790 CFConstantStringTypeDecl = Rec->getDecl();
3791}
3792
Jay Foad4ba2a172011-01-12 09:06:06 +00003793QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00003794 if (BlockDescriptorType)
3795 return getTagDeclType(BlockDescriptorType);
3796
3797 RecordDecl *T;
3798 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003799 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003800 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003801 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003802
3803 QualType FieldTypes[] = {
3804 UnsignedLongTy,
3805 UnsignedLongTy,
3806 };
3807
3808 const char *FieldNames[] = {
3809 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003810 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003811 };
3812
3813 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003814 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003815 SourceLocation(),
3816 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003817 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003818 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003819 /*Mutable=*/false,
3820 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003821 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003822 T->addDecl(Field);
3823 }
3824
Douglas Gregor838db382010-02-11 01:19:42 +00003825 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003826
3827 BlockDescriptorType = T;
3828
3829 return getTagDeclType(BlockDescriptorType);
3830}
3831
Jay Foad4ba2a172011-01-12 09:06:06 +00003832QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00003833 if (BlockDescriptorExtendedType)
3834 return getTagDeclType(BlockDescriptorExtendedType);
3835
3836 RecordDecl *T;
3837 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003838 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003839 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003840 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003841
3842 QualType FieldTypes[] = {
3843 UnsignedLongTy,
3844 UnsignedLongTy,
3845 getPointerType(VoidPtrTy),
3846 getPointerType(VoidPtrTy)
3847 };
3848
3849 const char *FieldNames[] = {
3850 "reserved",
3851 "Size",
3852 "CopyFuncPtr",
3853 "DestroyFuncPtr"
3854 };
3855
3856 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003857 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00003858 SourceLocation(),
3859 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003860 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003861 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003862 /*Mutable=*/false,
3863 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003864 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003865 T->addDecl(Field);
3866 }
3867
Douglas Gregor838db382010-02-11 01:19:42 +00003868 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003869
3870 BlockDescriptorExtendedType = T;
3871
3872 return getTagDeclType(BlockDescriptorExtendedType);
3873}
3874
Jay Foad4ba2a172011-01-12 09:06:06 +00003875bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCallf85e1932011-06-15 23:02:42 +00003876 if (Ty->isObjCRetainableType())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003877 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003878 if (getLangOptions().CPlusPlus) {
3879 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3880 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Huntffe37fd2011-05-25 20:50:04 +00003881 return RD->hasConstCopyConstructor();
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003882
3883 }
3884 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003885 return false;
3886}
3887
Jay Foad4ba2a172011-01-12 09:06:06 +00003888QualType
Chris Lattner5f9e2722011-07-23 10:55:15 +00003889ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003890 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003891 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003892 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003893 // unsigned int __flags;
3894 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003895 // void *__copy_helper; // as needed
3896 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003897 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003898 // } *
3899
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003900 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3901
3902 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003903 llvm::SmallString<36> Name;
3904 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3905 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003906 RecordDecl *T;
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003907 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003908 T->startDefinition();
3909 QualType Int32Ty = IntTy;
3910 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3911 QualType FieldTypes[] = {
3912 getPointerType(VoidPtrTy),
3913 getPointerType(getTagDeclType(T)),
3914 Int32Ty,
3915 Int32Ty,
3916 getPointerType(VoidPtrTy),
3917 getPointerType(VoidPtrTy),
3918 Ty
3919 };
3920
Chris Lattner5f9e2722011-07-23 10:55:15 +00003921 StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003922 "__isa",
3923 "__forwarding",
3924 "__flags",
3925 "__size",
3926 "__copy_helper",
3927 "__destroy_helper",
3928 DeclName,
3929 };
3930
3931 for (size_t i = 0; i < 7; ++i) {
3932 if (!HasCopyAndDispose && i >=4 && i <= 5)
3933 continue;
3934 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003935 SourceLocation(),
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003936 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003937 FieldTypes[i], /*TInfo=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003938 /*BitWidth=*/0, /*Mutable=*/false,
3939 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003940 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003941 T->addDecl(Field);
3942 }
3943
Douglas Gregor838db382010-02-11 01:19:42 +00003944 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003945
3946 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003947}
3948
Douglas Gregore97179c2011-09-08 01:46:34 +00003949TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
3950 if (!ObjCInstanceTypeDecl)
3951 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
3952 getTranslationUnitDecl(),
3953 SourceLocation(),
3954 SourceLocation(),
3955 &Idents.get("instancetype"),
3956 getTrivialTypeSourceInfo(getObjCIdType()));
3957 return ObjCInstanceTypeDecl;
3958}
3959
Anders Carlssone8c49532007-10-29 06:33:42 +00003960// This returns true if a type has been typedefed to BOOL:
3961// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003962static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003963 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003964 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3965 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003966
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003967 return false;
3968}
3969
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003970/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003971/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00003972CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00003973 if (!type->isIncompleteArrayType() && type->isIncompleteType())
3974 return CharUnits::Zero();
3975
Ken Dyck199c3d62010-01-11 17:06:35 +00003976 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003977
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003978 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003979 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003980 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003981 // Treat arrays as pointers, since that's how they're passed in.
3982 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003983 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003984 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003985}
3986
3987static inline
3988std::string charUnitsToString(const CharUnits &CU) {
3989 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003990}
3991
John McCall6b5a61b2011-02-07 10:33:21 +00003992/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003993/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00003994std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3995 std::string S;
3996
David Chisnall5e530af2009-11-17 19:33:30 +00003997 const BlockDecl *Decl = Expr->getBlockDecl();
3998 QualType BlockTy =
3999 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4000 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00004001 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00004002 // Compute size of all parameters.
4003 // Start with computing size of a pointer in number of bytes.
4004 // FIXME: There might(should) be a better way of doing this computation!
4005 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004006 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4007 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004008 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004009 E = Decl->param_end(); PI != E; ++PI) {
4010 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004011 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00004012 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004013 ParmOffset += sz;
4014 }
4015 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004016 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004017 // Block pointer and offset.
4018 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004019
4020 // Argument types.
4021 ParmOffset = PtrSize;
4022 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4023 Decl->param_end(); PI != E; ++PI) {
4024 ParmVarDecl *PVDecl = *PI;
4025 QualType PType = PVDecl->getOriginalType();
4026 if (const ArrayType *AT =
4027 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4028 // Use array's original type only if it has known number of
4029 // elements.
4030 if (!isa<ConstantArrayType>(AT))
4031 PType = PVDecl->getType();
4032 } else if (PType->isFunctionType())
4033 PType = PVDecl->getType();
4034 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004035 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004036 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004037 }
John McCall6b5a61b2011-02-07 10:33:21 +00004038
4039 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004040}
4041
Douglas Gregorf968d832011-05-27 01:19:52 +00004042bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004043 std::string& S) {
4044 // Encode result type.
4045 getObjCEncodingForType(Decl->getResultType(), S);
4046 CharUnits ParmOffset;
4047 // Compute size of all parameters.
4048 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4049 E = Decl->param_end(); PI != E; ++PI) {
4050 QualType PType = (*PI)->getType();
4051 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004052 if (sz.isZero())
4053 return true;
4054
David Chisnall5389f482010-12-30 14:05:53 +00004055 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004056 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004057 ParmOffset += sz;
4058 }
4059 S += charUnitsToString(ParmOffset);
4060 ParmOffset = CharUnits::Zero();
4061
4062 // Argument types.
4063 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4064 E = Decl->param_end(); PI != E; ++PI) {
4065 ParmVarDecl *PVDecl = *PI;
4066 QualType PType = PVDecl->getOriginalType();
4067 if (const ArrayType *AT =
4068 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4069 // Use array's original type only if it has known number of
4070 // elements.
4071 if (!isa<ConstantArrayType>(AT))
4072 PType = PVDecl->getType();
4073 } else if (PType->isFunctionType())
4074 PType = PVDecl->getType();
4075 getObjCEncodingForType(PType, S);
4076 S += charUnitsToString(ParmOffset);
4077 ParmOffset += getObjCEncodingTypeSize(PType);
4078 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004079
4080 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004081}
4082
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004083/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004084/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004085bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00004086 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004087 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004088 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004089 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004090 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004091 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004092 // Compute size of all parameters.
4093 // Start with computing size of a pointer in number of bytes.
4094 // FIXME: There might(should) be a better way of doing this computation!
4095 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004096 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004097 // The first two arguments (self and _cmd) are pointers; account for
4098 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004099 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004100 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004101 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004102 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004103 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004104 if (sz.isZero())
4105 return true;
4106
Ken Dyck199c3d62010-01-11 17:06:35 +00004107 assert (sz.isPositive() &&
4108 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004109 ParmOffset += sz;
4110 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004111 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004112 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004113 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004114
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004115 // Argument types.
4116 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004117 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004118 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004119 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004120 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004121 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004122 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4123 // Use array's original type only if it has known number of
4124 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004125 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004126 PType = PVDecl->getType();
4127 } else if (PType->isFunctionType())
4128 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004129 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004130 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004131 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004132 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004133 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004134 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004135 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004136
4137 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004138}
4139
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004140/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004141/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004142/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4143/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004144/// Property attributes are stored as a comma-delimited C string. The simple
4145/// attributes readonly and bycopy are encoded as single characters. The
4146/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4147/// encoded as single characters, followed by an identifier. Property types
4148/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004149/// these attributes are defined by the following enumeration:
4150/// @code
4151/// enum PropertyAttributes {
4152/// kPropertyReadOnly = 'R', // property is read-only.
4153/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4154/// kPropertyByref = '&', // property is a reference to the value last assigned
4155/// kPropertyDynamic = 'D', // property is dynamic
4156/// kPropertyGetter = 'G', // followed by getter selector name
4157/// kPropertySetter = 'S', // followed by setter selector name
4158/// kPropertyInstanceVariable = 'V' // followed by instance variable name
4159/// kPropertyType = 't' // followed by old-style type encoding.
4160/// kPropertyWeak = 'W' // 'weak' property
4161/// kPropertyStrong = 'P' // property GC'able
4162/// kPropertyNonAtomic = 'N' // property non-atomic
4163/// };
4164/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004165void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004166 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004167 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004168 // Collect information from the property implementation decl(s).
4169 bool Dynamic = false;
4170 ObjCPropertyImplDecl *SynthesizePID = 0;
4171
4172 // FIXME: Duplicated code due to poor abstraction.
4173 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004174 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004175 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4176 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004177 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004178 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004179 ObjCPropertyImplDecl *PID = *i;
4180 if (PID->getPropertyDecl() == PD) {
4181 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4182 Dynamic = true;
4183 } else {
4184 SynthesizePID = PID;
4185 }
4186 }
4187 }
4188 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004189 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004190 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004191 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004192 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004193 ObjCPropertyImplDecl *PID = *i;
4194 if (PID->getPropertyDecl() == PD) {
4195 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4196 Dynamic = true;
4197 } else {
4198 SynthesizePID = PID;
4199 }
4200 }
Mike Stump1eb44332009-09-09 15:08:12 +00004201 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004202 }
4203 }
4204
4205 // FIXME: This is not very efficient.
4206 S = "T";
4207
4208 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004209 // GCC has some special rules regarding encoding of properties which
4210 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004211 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004212 true /* outermost type */,
4213 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004214
4215 if (PD->isReadOnly()) {
4216 S += ",R";
4217 } else {
4218 switch (PD->getSetterKind()) {
4219 case ObjCPropertyDecl::Assign: break;
4220 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004221 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004222 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004223 }
4224 }
4225
4226 // It really isn't clear at all what this means, since properties
4227 // are "dynamic by default".
4228 if (Dynamic)
4229 S += ",D";
4230
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004231 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4232 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004233
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004234 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4235 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004236 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004237 }
4238
4239 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4240 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004241 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004242 }
4243
4244 if (SynthesizePID) {
4245 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4246 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004247 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004248 }
4249
4250 // FIXME: OBJCGC: weak & strong
4251}
4252
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004253/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004254/// Another legacy compatibility encoding: 32-bit longs are encoded as
4255/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004256/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4257///
4258void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004259 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004260 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004261 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004262 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004263 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004264 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004265 PointeeTy = IntTy;
4266 }
4267 }
4268}
4269
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004270void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004271 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004272 // We follow the behavior of gcc, expanding structures which are
4273 // directly pointed to, and expanding embedded structures. Note that
4274 // these rules are sufficient to prevent recursive encoding of the
4275 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004276 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004277 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004278}
4279
David Chisnall64fd7e82010-06-04 01:10:52 +00004280static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4281 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004282 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnall64fd7e82010-06-04 01:10:52 +00004283 case BuiltinType::Void: return 'v';
4284 case BuiltinType::Bool: return 'B';
4285 case BuiltinType::Char_U:
4286 case BuiltinType::UChar: return 'C';
4287 case BuiltinType::UShort: return 'S';
4288 case BuiltinType::UInt: return 'I';
4289 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00004290 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004291 case BuiltinType::UInt128: return 'T';
4292 case BuiltinType::ULongLong: return 'Q';
4293 case BuiltinType::Char_S:
4294 case BuiltinType::SChar: return 'c';
4295 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004296 case BuiltinType::WChar_S:
4297 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004298 case BuiltinType::Int: return 'i';
4299 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00004300 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004301 case BuiltinType::LongLong: return 'q';
4302 case BuiltinType::Int128: return 't';
4303 case BuiltinType::Float: return 'f';
4304 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004305 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004306 }
4307}
4308
Douglas Gregor5471bc82011-09-08 17:18:35 +00004309static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4310 EnumDecl *Enum = ET->getDecl();
4311
4312 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4313 if (!Enum->isFixed())
4314 return 'i';
4315
4316 // The encoding of a fixed enum type matches its fixed underlying type.
4317 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4318}
4319
Jay Foad4ba2a172011-01-12 09:06:06 +00004320static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004321 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004322 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004323 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004324 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4325 // The GNU runtime requires more information; bitfields are encoded as b,
4326 // then the offset (in bits) of the first element, then the type of the
4327 // bitfield, then the size in bits. For example, in this structure:
4328 //
4329 // struct
4330 // {
4331 // int integer;
4332 // int flags:2;
4333 // };
4334 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4335 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4336 // information is not especially sensible, but we're stuck with it for
4337 // compatibility with GCC, although providing it breaks anything that
4338 // actually uses runtime introspection and wants to work on both runtimes...
4339 if (!Ctx->getLangOptions().NeXTRuntime) {
4340 const RecordDecl *RD = FD->getParent();
4341 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004342 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00004343 if (const EnumType *ET = T->getAs<EnumType>())
4344 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnallc7ff82c2010-12-26 20:12:30 +00004345 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004346 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004347 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004348 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004349}
4350
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004351// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004352void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4353 bool ExpandPointedToStructures,
4354 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004355 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004356 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004357 bool EncodingProperty,
4358 bool StructField) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004359 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004360 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004361 return EncodeBitField(this, S, T, FD);
4362 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004363 return;
4364 }
Mike Stump1eb44332009-09-09 15:08:12 +00004365
John McCall183700f2009-09-21 23:43:11 +00004366 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004367 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004368 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004369 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004370 return;
4371 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004372
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004373 // encoding for pointer or r3eference types.
4374 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004375 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004376 if (PT->isObjCSelType()) {
4377 S += ':';
4378 return;
4379 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004380 PointeeTy = PT->getPointeeType();
4381 }
4382 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4383 PointeeTy = RT->getPointeeType();
4384 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004385 bool isReadOnly = false;
4386 // For historical/compatibility reasons, the read-only qualifier of the
4387 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4388 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004389 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004390 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004391 if (OutermostType && T.isConstQualified()) {
4392 isReadOnly = true;
4393 S += 'r';
4394 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004395 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004396 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004397 while (P->getAs<PointerType>())
4398 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004399 if (P.isConstQualified()) {
4400 isReadOnly = true;
4401 S += 'r';
4402 }
4403 }
4404 if (isReadOnly) {
4405 // Another legacy compatibility encoding. Some ObjC qualifier and type
4406 // combinations need to be rearranged.
4407 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00004408 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00004409 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004410 }
Mike Stump1eb44332009-09-09 15:08:12 +00004411
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004412 if (PointeeTy->isCharType()) {
4413 // char pointer types should be encoded as '*' unless it is a
4414 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004415 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004416 S += '*';
4417 return;
4418 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004419 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004420 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4421 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4422 S += '#';
4423 return;
4424 }
4425 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4426 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4427 S += '@';
4428 return;
4429 }
4430 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004431 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004432 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004433 getLegacyIntegralTypeEncoding(PointeeTy);
4434
Mike Stump1eb44332009-09-09 15:08:12 +00004435 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004436 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004437 return;
4438 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004439
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004440 if (const ArrayType *AT =
4441 // Ignore type qualifiers etc.
4442 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004443 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004444 // Incomplete arrays are encoded as a pointer to the array element.
4445 S += '^';
4446
Mike Stump1eb44332009-09-09 15:08:12 +00004447 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004448 false, ExpandStructures, FD);
4449 } else {
4450 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004451
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004452 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4453 if (getTypeSize(CAT->getElementType()) == 0)
4454 S += '0';
4455 else
4456 S += llvm::utostr(CAT->getSize().getZExtValue());
4457 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00004458 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004459 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4460 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00004461 S += '0';
4462 }
Mike Stump1eb44332009-09-09 15:08:12 +00004463
4464 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004465 false, ExpandStructures, FD);
4466 S += ']';
4467 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004468 return;
4469 }
Mike Stump1eb44332009-09-09 15:08:12 +00004470
John McCall183700f2009-09-21 23:43:11 +00004471 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004472 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004473 return;
4474 }
Mike Stump1eb44332009-09-09 15:08:12 +00004475
Ted Kremenek6217b802009-07-29 21:53:49 +00004476 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004477 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004478 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004479 // Anonymous structures print as '?'
4480 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4481 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004482 if (ClassTemplateSpecializationDecl *Spec
4483 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4484 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4485 std::string TemplateArgsStr
4486 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004487 TemplateArgs.data(),
4488 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00004489 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004490
4491 S += TemplateArgsStr;
4492 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004493 } else {
4494 S += '?';
4495 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004496 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004497 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004498 if (!RDecl->isUnion()) {
4499 getObjCEncodingForStructureImpl(RDecl, S, FD);
4500 } else {
4501 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4502 FieldEnd = RDecl->field_end();
4503 Field != FieldEnd; ++Field) {
4504 if (FD) {
4505 S += '"';
4506 S += Field->getNameAsString();
4507 S += '"';
4508 }
Mike Stump1eb44332009-09-09 15:08:12 +00004509
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004510 // Special case bit-fields.
4511 if (Field->isBitField()) {
4512 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4513 (*Field));
4514 } else {
4515 QualType qt = Field->getType();
4516 getLegacyIntegralTypeEncoding(qt);
4517 getObjCEncodingForTypeImpl(qt, S, false, true,
4518 FD, /*OutermostType*/false,
4519 /*EncodingProperty*/false,
4520 /*StructField*/true);
4521 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004522 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004523 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004524 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004525 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004526 return;
4527 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004528
Douglas Gregor5471bc82011-09-08 17:18:35 +00004529 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004530 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004531 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004532 else
Douglas Gregor5471bc82011-09-08 17:18:35 +00004533 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004534 return;
4535 }
Mike Stump1eb44332009-09-09 15:08:12 +00004536
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004537 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004538 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004539 return;
4540 }
Mike Stump1eb44332009-09-09 15:08:12 +00004541
John McCallc12c5bb2010-05-15 11:32:37 +00004542 // Ignore protocol qualifiers when mangling at this level.
4543 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4544 T = OT->getBaseType();
4545
John McCall0953e762009-09-24 19:53:00 +00004546 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004547 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004548 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004549 S += '{';
4550 const IdentifierInfo *II = OI->getIdentifier();
4551 S += II->getName();
4552 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00004553 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004554 DeepCollectObjCIvars(OI, true, Ivars);
4555 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00004556 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004557 if (Field->isBitField())
4558 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004559 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004560 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004561 }
4562 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004563 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004564 }
Mike Stump1eb44332009-09-09 15:08:12 +00004565
John McCall183700f2009-09-21 23:43:11 +00004566 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004567 if (OPT->isObjCIdType()) {
4568 S += '@';
4569 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004570 }
Mike Stump1eb44332009-09-09 15:08:12 +00004571
Steve Naroff27d20a22009-10-28 22:03:49 +00004572 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4573 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4574 // Since this is a binary compatibility issue, need to consult with runtime
4575 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004576 S += '#';
4577 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004578 }
Mike Stump1eb44332009-09-09 15:08:12 +00004579
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004580 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004581 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004582 ExpandPointedToStructures,
4583 ExpandStructures, FD);
4584 if (FD || EncodingProperty) {
4585 // Note that we do extended encoding of protocol qualifer list
4586 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004587 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004588 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4589 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004590 S += '<';
4591 S += (*I)->getNameAsString();
4592 S += '>';
4593 }
4594 S += '"';
4595 }
4596 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004597 }
Mike Stump1eb44332009-09-09 15:08:12 +00004598
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004599 QualType PointeeTy = OPT->getPointeeType();
4600 if (!EncodingProperty &&
4601 isa<TypedefType>(PointeeTy.getTypePtr())) {
4602 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004603 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004604 // {...};
4605 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004606 getObjCEncodingForTypeImpl(PointeeTy, S,
4607 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004608 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004609 return;
4610 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004611
4612 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00004613 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004614 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004615 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004616 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4617 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004618 S += '<';
4619 S += (*I)->getNameAsString();
4620 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004621 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004622 S += '"';
4623 }
4624 return;
4625 }
Mike Stump1eb44332009-09-09 15:08:12 +00004626
John McCall532ec7b2010-05-17 23:56:34 +00004627 // gcc just blithely ignores member pointers.
4628 // TODO: maybe there should be a mangling for these
4629 if (T->getAs<MemberPointerType>())
4630 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004631
4632 if (T->isVectorType()) {
4633 // This matches gcc's encoding, even though technically it is
4634 // insufficient.
4635 // FIXME. We should do a better job than gcc.
4636 return;
4637 }
4638
David Blaikieb219cfc2011-09-23 05:06:16 +00004639 llvm_unreachable("@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004640}
4641
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004642void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4643 std::string &S,
4644 const FieldDecl *FD,
4645 bool includeVBases) const {
4646 assert(RDecl && "Expected non-null RecordDecl");
4647 assert(!RDecl->isUnion() && "Should not be called for unions");
4648 if (!RDecl->getDefinition())
4649 return;
4650
4651 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4652 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4653 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4654
4655 if (CXXRec) {
4656 for (CXXRecordDecl::base_class_iterator
4657 BI = CXXRec->bases_begin(),
4658 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4659 if (!BI->isVirtual()) {
4660 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004661 if (base->isEmpty())
4662 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004663 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4664 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4665 std::make_pair(offs, base));
4666 }
4667 }
4668 }
4669
4670 unsigned i = 0;
4671 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4672 FieldEnd = RDecl->field_end();
4673 Field != FieldEnd; ++Field, ++i) {
4674 uint64_t offs = layout.getFieldOffset(i);
4675 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4676 std::make_pair(offs, *Field));
4677 }
4678
4679 if (CXXRec && includeVBases) {
4680 for (CXXRecordDecl::base_class_iterator
4681 BI = CXXRec->vbases_begin(),
4682 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4683 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004684 if (base->isEmpty())
4685 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004686 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00004687 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4688 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4689 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004690 }
4691 }
4692
4693 CharUnits size;
4694 if (CXXRec) {
4695 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4696 } else {
4697 size = layout.getSize();
4698 }
4699
4700 uint64_t CurOffs = 0;
4701 std::multimap<uint64_t, NamedDecl *>::iterator
4702 CurLayObj = FieldOrBaseOffsets.begin();
4703
Argyrios Kyrtzidiscb8061e2011-08-22 16:03:14 +00004704 if ((CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) ||
4705 (CurLayObj == FieldOrBaseOffsets.end() &&
4706 CXXRec && CXXRec->isDynamicClass())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004707 assert(CXXRec && CXXRec->isDynamicClass() &&
4708 "Offset 0 was empty but no VTable ?");
4709 if (FD) {
4710 S += "\"_vptr$";
4711 std::string recname = CXXRec->getNameAsString();
4712 if (recname.empty()) recname = "?";
4713 S += recname;
4714 S += '"';
4715 }
4716 S += "^^?";
4717 CurOffs += getTypeSize(VoidPtrTy);
4718 }
4719
4720 if (!RDecl->hasFlexibleArrayMember()) {
4721 // Mark the end of the structure.
4722 uint64_t offs = toBits(size);
4723 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4724 std::make_pair(offs, (NamedDecl*)0));
4725 }
4726
4727 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4728 assert(CurOffs <= CurLayObj->first);
4729
4730 if (CurOffs < CurLayObj->first) {
4731 uint64_t padding = CurLayObj->first - CurOffs;
4732 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4733 // packing/alignment of members is different that normal, in which case
4734 // the encoding will be out-of-sync with the real layout.
4735 // If the runtime switches to just consider the size of types without
4736 // taking into account alignment, we could make padding explicit in the
4737 // encoding (e.g. using arrays of chars). The encoding strings would be
4738 // longer then though.
4739 CurOffs += padding;
4740 }
4741
4742 NamedDecl *dcl = CurLayObj->second;
4743 if (dcl == 0)
4744 break; // reached end of structure.
4745
4746 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4747 // We expand the bases without their virtual bases since those are going
4748 // in the initial structure. Note that this differs from gcc which
4749 // expands virtual bases each time one is encountered in the hierarchy,
4750 // making the encoding type bigger than it really is.
4751 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004752 assert(!base->isEmpty());
4753 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004754 } else {
4755 FieldDecl *field = cast<FieldDecl>(dcl);
4756 if (FD) {
4757 S += '"';
4758 S += field->getNameAsString();
4759 S += '"';
4760 }
4761
4762 if (field->isBitField()) {
4763 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004764 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004765 } else {
4766 QualType qt = field->getType();
4767 getLegacyIntegralTypeEncoding(qt);
4768 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4769 /*OutermostType*/false,
4770 /*EncodingProperty*/false,
4771 /*StructField*/true);
4772 CurOffs += getTypeSize(field->getType());
4773 }
4774 }
4775 }
4776}
4777
Mike Stump1eb44332009-09-09 15:08:12 +00004778void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004779 std::string& S) const {
4780 if (QT & Decl::OBJC_TQ_In)
4781 S += 'n';
4782 if (QT & Decl::OBJC_TQ_Inout)
4783 S += 'N';
4784 if (QT & Decl::OBJC_TQ_Out)
4785 S += 'o';
4786 if (QT & Decl::OBJC_TQ_Bycopy)
4787 S += 'O';
4788 if (QT & Decl::OBJC_TQ_Byref)
4789 S += 'R';
4790 if (QT & Decl::OBJC_TQ_Oneway)
4791 S += 'V';
4792}
4793
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004794void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004795 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004796
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004797 BuiltinVaListType = T;
4798}
4799
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00004800TypedefDecl *ASTContext::getObjCIdDecl() const {
4801 if (!ObjCIdDecl) {
4802 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4803 T = getObjCObjectPointerType(T);
4804 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4805 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4806 getTranslationUnitDecl(),
4807 SourceLocation(), SourceLocation(),
4808 &Idents.get("id"), IdInfo);
4809 }
4810
4811 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00004812}
4813
Douglas Gregor7a27ea52011-08-12 06:17:30 +00004814TypedefDecl *ASTContext::getObjCSelDecl() const {
4815 if (!ObjCSelDecl) {
4816 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4817 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4818 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4819 getTranslationUnitDecl(),
4820 SourceLocation(), SourceLocation(),
4821 &Idents.get("SEL"), SelInfo);
4822 }
4823 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004824}
4825
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004826void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004827 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00004828}
4829
Douglas Gregor79d67262011-08-12 05:59:41 +00004830TypedefDecl *ASTContext::getObjCClassDecl() const {
4831 if (!ObjCClassDecl) {
4832 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4833 T = getObjCObjectPointerType(T);
4834 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4835 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4836 getTranslationUnitDecl(),
4837 SourceLocation(), SourceLocation(),
4838 &Idents.get("Class"), ClassInfo);
4839 }
4840
4841 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004842}
4843
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004844void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004845 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004846 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004847
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004848 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004849}
4850
John McCall0bd6feb2009-12-02 08:04:21 +00004851/// \brief Retrieve the template name that corresponds to a non-empty
4852/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00004853TemplateName
4854ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4855 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00004856 unsigned size = End - Begin;
4857 assert(size > 1 && "set is not overloaded!");
4858
4859 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4860 size * sizeof(FunctionTemplateDecl*));
4861 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4862
4863 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004864 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004865 NamedDecl *D = *I;
4866 assert(isa<FunctionTemplateDecl>(D) ||
4867 (isa<UsingShadowDecl>(D) &&
4868 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4869 *Storage++ = D;
4870 }
4871
4872 return TemplateName(OT);
4873}
4874
Douglas Gregor7532dc62009-03-30 22:58:21 +00004875/// \brief Retrieve the template name that represents a qualified
4876/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00004877TemplateName
4878ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4879 bool TemplateKeyword,
4880 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00004881 assert(NNS && "Missing nested-name-specifier in qualified template name");
4882
Douglas Gregor789b1f62010-02-04 18:10:26 +00004883 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004884 llvm::FoldingSetNodeID ID;
4885 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4886
4887 void *InsertPos = 0;
4888 QualifiedTemplateName *QTN =
4889 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4890 if (!QTN) {
4891 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4892 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4893 }
4894
4895 return TemplateName(QTN);
4896}
4897
4898/// \brief Retrieve the template name that represents a dependent
4899/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00004900TemplateName
4901ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4902 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004903 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004904 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004905
4906 llvm::FoldingSetNodeID ID;
4907 DependentTemplateName::Profile(ID, NNS, Name);
4908
4909 void *InsertPos = 0;
4910 DependentTemplateName *QTN =
4911 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4912
4913 if (QTN)
4914 return TemplateName(QTN);
4915
4916 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4917 if (CanonNNS == NNS) {
4918 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4919 } else {
4920 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4921 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004922 DependentTemplateName *CheckQTN =
4923 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4924 assert(!CheckQTN && "Dependent type name canonicalization broken");
4925 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004926 }
4927
4928 DependentTemplateNames.InsertNode(QTN, InsertPos);
4929 return TemplateName(QTN);
4930}
4931
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004932/// \brief Retrieve the template name that represents a dependent
4933/// template name such as \c MetaFun::template operator+.
4934TemplateName
4935ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00004936 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004937 assert((!NNS || NNS->isDependent()) &&
4938 "Nested name specifier must be dependent");
4939
4940 llvm::FoldingSetNodeID ID;
4941 DependentTemplateName::Profile(ID, NNS, Operator);
4942
4943 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004944 DependentTemplateName *QTN
4945 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004946
4947 if (QTN)
4948 return TemplateName(QTN);
4949
4950 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4951 if (CanonNNS == NNS) {
4952 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4953 } else {
4954 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4955 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004956
4957 DependentTemplateName *CheckQTN
4958 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4959 assert(!CheckQTN && "Dependent template name canonicalization broken");
4960 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004961 }
4962
4963 DependentTemplateNames.InsertNode(QTN, InsertPos);
4964 return TemplateName(QTN);
4965}
4966
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004967TemplateName
John McCall14606042011-06-30 08:33:18 +00004968ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
4969 TemplateName replacement) const {
4970 llvm::FoldingSetNodeID ID;
4971 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
4972
4973 void *insertPos = 0;
4974 SubstTemplateTemplateParmStorage *subst
4975 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
4976
4977 if (!subst) {
4978 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
4979 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
4980 }
4981
4982 return TemplateName(subst);
4983}
4984
4985TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004986ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4987 const TemplateArgument &ArgPack) const {
4988 ASTContext &Self = const_cast<ASTContext &>(*this);
4989 llvm::FoldingSetNodeID ID;
4990 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4991
4992 void *InsertPos = 0;
4993 SubstTemplateTemplateParmPackStorage *Subst
4994 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4995
4996 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00004997 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004998 ArgPack.pack_size(),
4999 ArgPack.pack_begin());
5000 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5001 }
5002
5003 return TemplateName(Subst);
5004}
5005
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005006/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00005007/// TargetInfo, produce the corresponding type. The unsigned @p Type
5008/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00005009CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005010 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00005011 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005012 case TargetInfo::SignedShort: return ShortTy;
5013 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5014 case TargetInfo::SignedInt: return IntTy;
5015 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5016 case TargetInfo::SignedLong: return LongTy;
5017 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5018 case TargetInfo::SignedLongLong: return LongLongTy;
5019 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5020 }
5021
David Blaikieb219cfc2011-09-23 05:06:16 +00005022 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005023}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00005024
5025//===----------------------------------------------------------------------===//
5026// Type Predicates.
5027//===----------------------------------------------------------------------===//
5028
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005029/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5030/// garbage collection attribute.
5031///
John McCallae278a32011-01-12 00:34:59 +00005032Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
Douglas Gregore289d812011-09-13 17:21:33 +00005033 if (getLangOptions().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00005034 return Qualifiers::GCNone;
5035
5036 assert(getLangOptions().ObjC1);
5037 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5038
5039 // Default behaviour under objective-C's gc is for ObjC pointers
5040 // (or pointers to them) be treated as though they were declared
5041 // as __strong.
5042 if (GCAttrs == Qualifiers::GCNone) {
5043 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5044 return Qualifiers::Strong;
5045 else if (Ty->isPointerType())
5046 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5047 } else {
5048 // It's not valid to set GC attributes on anything that isn't a
5049 // pointer.
5050#ifndef NDEBUG
5051 QualType CT = Ty->getCanonicalTypeInternal();
5052 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5053 CT = AT->getElementType();
5054 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5055#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005056 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00005057 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005058}
5059
Chris Lattner6ac46a42008-04-07 06:51:04 +00005060//===----------------------------------------------------------------------===//
5061// Type Compatibility Testing
5062//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00005063
Mike Stump1eb44332009-09-09 15:08:12 +00005064/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005065/// compatible.
5066static bool areCompatVectorTypes(const VectorType *LHS,
5067 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00005068 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00005069 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00005070 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00005071}
5072
Douglas Gregor255210e2010-08-06 10:14:59 +00005073bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5074 QualType SecondVec) {
5075 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5076 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5077
5078 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5079 return true;
5080
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005081 // Treat Neon vector types and most AltiVec vector types as if they are the
5082 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00005083 const VectorType *First = FirstVec->getAs<VectorType>();
5084 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005085 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00005086 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005087 First->getVectorKind() != VectorType::AltiVecPixel &&
5088 First->getVectorKind() != VectorType::AltiVecBool &&
5089 Second->getVectorKind() != VectorType::AltiVecPixel &&
5090 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00005091 return true;
5092
5093 return false;
5094}
5095
Steve Naroff4084c302009-07-23 01:01:38 +00005096//===----------------------------------------------------------------------===//
5097// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5098//===----------------------------------------------------------------------===//
5099
5100/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5101/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00005102bool
5103ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5104 ObjCProtocolDecl *rProto) const {
Steve Naroff4084c302009-07-23 01:01:38 +00005105 if (lProto == rProto)
5106 return true;
5107 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5108 E = rProto->protocol_end(); PI != E; ++PI)
5109 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5110 return true;
5111 return false;
5112}
5113
Steve Naroff4084c302009-07-23 01:01:38 +00005114/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5115/// return true if lhs's protocols conform to rhs's protocol; false
5116/// otherwise.
5117bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5118 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5119 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5120 return false;
5121}
5122
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005123/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5124/// Class<p1, ...>.
5125bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5126 QualType rhs) {
5127 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5128 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5129 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5130
5131 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5132 E = lhsQID->qual_end(); I != E; ++I) {
5133 bool match = false;
5134 ObjCProtocolDecl *lhsProto = *I;
5135 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5136 E = rhsOPT->qual_end(); J != E; ++J) {
5137 ObjCProtocolDecl *rhsProto = *J;
5138 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5139 match = true;
5140 break;
5141 }
5142 }
5143 if (!match)
5144 return false;
5145 }
5146 return true;
5147}
5148
Steve Naroff4084c302009-07-23 01:01:38 +00005149/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5150/// ObjCQualifiedIDType.
5151bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5152 bool compare) {
5153 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00005154 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005155 lhs->isObjCIdType() || lhs->isObjCClassType())
5156 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005157 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005158 rhs->isObjCIdType() || rhs->isObjCClassType())
5159 return true;
5160
5161 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00005162 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005163
Steve Naroff4084c302009-07-23 01:01:38 +00005164 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005165
Steve Naroff4084c302009-07-23 01:01:38 +00005166 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005167 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00005168 // make sure we check the class hierarchy.
5169 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5170 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5171 E = lhsQID->qual_end(); I != E; ++I) {
5172 // when comparing an id<P> on lhs with a static type on rhs,
5173 // see if static class implements all of id's protocols, directly or
5174 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005175 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00005176 return false;
5177 }
5178 }
5179 // If there are no qualifiers and no interface, we have an 'id'.
5180 return true;
5181 }
Mike Stump1eb44332009-09-09 15:08:12 +00005182 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005183 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5184 E = lhsQID->qual_end(); I != E; ++I) {
5185 ObjCProtocolDecl *lhsProto = *I;
5186 bool match = false;
5187
5188 // when comparing an id<P> on lhs with a static type on rhs,
5189 // see if static class implements all of id's protocols, directly or
5190 // through its super class and categories.
5191 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5192 E = rhsOPT->qual_end(); J != E; ++J) {
5193 ObjCProtocolDecl *rhsProto = *J;
5194 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5195 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5196 match = true;
5197 break;
5198 }
5199 }
Mike Stump1eb44332009-09-09 15:08:12 +00005200 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00005201 // make sure we check the class hierarchy.
5202 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5203 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5204 E = lhsQID->qual_end(); I != E; ++I) {
5205 // when comparing an id<P> on lhs with a static type on rhs,
5206 // see if static class implements all of id's protocols, directly or
5207 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005208 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00005209 match = true;
5210 break;
5211 }
5212 }
5213 }
5214 if (!match)
5215 return false;
5216 }
Mike Stump1eb44332009-09-09 15:08:12 +00005217
Steve Naroff4084c302009-07-23 01:01:38 +00005218 return true;
5219 }
Mike Stump1eb44332009-09-09 15:08:12 +00005220
Steve Naroff4084c302009-07-23 01:01:38 +00005221 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5222 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5223
Mike Stump1eb44332009-09-09 15:08:12 +00005224 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00005225 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005226 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005227 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5228 E = lhsOPT->qual_end(); I != E; ++I) {
5229 ObjCProtocolDecl *lhsProto = *I;
5230 bool match = false;
5231
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005232 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00005233 // see if static class implements all of id's protocols, directly or
5234 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005235 // First, lhs protocols in the qualifier list must be found, direct
5236 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00005237 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5238 E = rhsQID->qual_end(); J != E; ++J) {
5239 ObjCProtocolDecl *rhsProto = *J;
5240 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5241 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5242 match = true;
5243 break;
5244 }
5245 }
5246 if (!match)
5247 return false;
5248 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005249
5250 // Static class's protocols, or its super class or category protocols
5251 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5252 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5253 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5254 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5255 // This is rather dubious but matches gcc's behavior. If lhs has
5256 // no type qualifier and its class has no static protocol(s)
5257 // assume that it is mismatch.
5258 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5259 return false;
5260 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5261 LHSInheritedProtocols.begin(),
5262 E = LHSInheritedProtocols.end(); I != E; ++I) {
5263 bool match = false;
5264 ObjCProtocolDecl *lhsProto = (*I);
5265 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5266 E = rhsQID->qual_end(); J != E; ++J) {
5267 ObjCProtocolDecl *rhsProto = *J;
5268 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5269 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5270 match = true;
5271 break;
5272 }
5273 }
5274 if (!match)
5275 return false;
5276 }
5277 }
Steve Naroff4084c302009-07-23 01:01:38 +00005278 return true;
5279 }
5280 return false;
5281}
5282
Eli Friedman3d815e72008-08-22 00:56:42 +00005283/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005284/// compatible for assignment from RHS to LHS. This handles validation of any
5285/// protocol qualifiers on the LHS or RHS.
5286///
Steve Naroff14108da2009-07-10 23:34:53 +00005287bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5288 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00005289 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5290 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5291
Steve Naroffde2e22d2009-07-15 18:40:39 +00005292 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00005293 if (LHS->isObjCUnqualifiedIdOrClass() ||
5294 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00005295 return true;
5296
John McCallc12c5bb2010-05-15 11:32:37 +00005297 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00005298 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5299 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00005300 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005301
5302 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5303 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5304 QualType(RHSOPT,0));
5305
John McCallc12c5bb2010-05-15 11:32:37 +00005306 // If we have 2 user-defined types, fall into that path.
5307 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00005308 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00005309
Steve Naroff4084c302009-07-23 01:01:38 +00005310 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005311}
5312
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005313/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00005314/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005315/// arguments in block literals. When passed as arguments, passing 'A*' where
5316/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5317/// not OK. For the return type, the opposite is not OK.
5318bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5319 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005320 const ObjCObjectPointerType *RHSOPT,
5321 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005322 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005323 return true;
5324
5325 if (LHSOPT->isObjCBuiltinType()) {
5326 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5327 }
5328
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005329 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005330 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5331 QualType(RHSOPT,0),
5332 false);
5333
5334 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5335 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5336 if (LHS && RHS) { // We have 2 user-defined types.
5337 if (LHS != RHS) {
5338 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005339 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005340 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005341 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005342 }
5343 else
5344 return true;
5345 }
5346 return false;
5347}
5348
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005349/// getIntersectionOfProtocols - This routine finds the intersection of set
5350/// of protocols inherited from two distinct objective-c pointer objects.
5351/// It is used to build composite qualifier list of the composite type of
5352/// the conditional expression involving two objective-c pointer objects.
5353static
5354void getIntersectionOfProtocols(ASTContext &Context,
5355 const ObjCObjectPointerType *LHSOPT,
5356 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005357 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005358
John McCallc12c5bb2010-05-15 11:32:37 +00005359 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5360 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5361 assert(LHS->getInterface() && "LHS must have an interface base");
5362 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005363
5364 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5365 unsigned LHSNumProtocols = LHS->getNumProtocols();
5366 if (LHSNumProtocols > 0)
5367 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5368 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005369 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005370 Context.CollectInheritedProtocols(LHS->getInterface(),
5371 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005372 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5373 LHSInheritedProtocols.end());
5374 }
5375
5376 unsigned RHSNumProtocols = RHS->getNumProtocols();
5377 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00005378 ObjCProtocolDecl **RHSProtocols =
5379 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005380 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5381 if (InheritedProtocolSet.count(RHSProtocols[i]))
5382 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00005383 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005384 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005385 Context.CollectInheritedProtocols(RHS->getInterface(),
5386 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005387 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5388 RHSInheritedProtocols.begin(),
5389 E = RHSInheritedProtocols.end(); I != E; ++I)
5390 if (InheritedProtocolSet.count((*I)))
5391 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005392 }
5393}
5394
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005395/// areCommonBaseCompatible - Returns common base class of the two classes if
5396/// one found. Note that this is O'2 algorithm. But it will be called as the
5397/// last type comparison in a ?-exp of ObjC pointer types before a
5398/// warning is issued. So, its invokation is extremely rare.
5399QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00005400 const ObjCObjectPointerType *Lptr,
5401 const ObjCObjectPointerType *Rptr) {
5402 const ObjCObjectType *LHS = Lptr->getObjectType();
5403 const ObjCObjectType *RHS = Rptr->getObjectType();
5404 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5405 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005406 if (!LDecl || !RDecl || (LDecl == RDecl))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005407 return QualType();
5408
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005409 do {
John McCallc12c5bb2010-05-15 11:32:37 +00005410 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005411 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005412 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005413 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5414
5415 QualType Result = QualType(LHS, 0);
5416 if (!Protocols.empty())
5417 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5418 Result = getObjCObjectPointerType(Result);
5419 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005420 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005421 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005422
5423 return QualType();
5424}
5425
John McCallc12c5bb2010-05-15 11:32:37 +00005426bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5427 const ObjCObjectType *RHS) {
5428 assert(LHS->getInterface() && "LHS is not an interface type");
5429 assert(RHS->getInterface() && "RHS is not an interface type");
5430
Chris Lattner6ac46a42008-04-07 06:51:04 +00005431 // Verify that the base decls are compatible: the RHS must be a subclass of
5432 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00005433 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00005434 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005435
Chris Lattner6ac46a42008-04-07 06:51:04 +00005436 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5437 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00005438 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00005439 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005440
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005441 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5442 // more detailed analysis is required.
5443 if (RHS->getNumProtocols() == 0) {
5444 // OK, if LHS is a superclass of RHS *and*
5445 // this superclass is assignment compatible with LHS.
5446 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005447 bool IsSuperClass =
5448 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5449 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005450 // OK if conversion of LHS to SuperClass results in narrowing of types
5451 // ; i.e., SuperClass may implement at least one of the protocols
5452 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5453 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5454 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005455 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005456 // If super class has no protocols, it is not a match.
5457 if (SuperClassInheritedProtocols.empty())
5458 return false;
5459
5460 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5461 LHSPE = LHS->qual_end();
5462 LHSPI != LHSPE; LHSPI++) {
5463 bool SuperImplementsProtocol = false;
5464 ObjCProtocolDecl *LHSProto = (*LHSPI);
5465
5466 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5467 SuperClassInheritedProtocols.begin(),
5468 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5469 ObjCProtocolDecl *SuperClassProto = (*I);
5470 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5471 SuperImplementsProtocol = true;
5472 break;
5473 }
5474 }
5475 if (!SuperImplementsProtocol)
5476 return false;
5477 }
5478 return true;
5479 }
5480 return false;
5481 }
Mike Stump1eb44332009-09-09 15:08:12 +00005482
John McCallc12c5bb2010-05-15 11:32:37 +00005483 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5484 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005485 LHSPI != LHSPE; LHSPI++) {
5486 bool RHSImplementsProtocol = false;
5487
5488 // If the RHS doesn't implement the protocol on the left, the types
5489 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00005490 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5491 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00005492 RHSPI != RHSPE; RHSPI++) {
5493 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005494 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00005495 break;
5496 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005497 }
5498 // FIXME: For better diagnostics, consider passing back the protocol name.
5499 if (!RHSImplementsProtocol)
5500 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005501 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005502 // The RHS implements all protocols listed on the LHS.
5503 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005504}
5505
Steve Naroff389bf462009-02-12 17:52:19 +00005506bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5507 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00005508 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5509 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005510
Steve Naroff14108da2009-07-10 23:34:53 +00005511 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00005512 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005513
5514 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5515 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00005516}
5517
Douglas Gregor569c3162010-08-07 11:51:51 +00005518bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5519 return canAssignObjCInterfaces(
5520 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5521 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5522}
5523
Mike Stump1eb44332009-09-09 15:08:12 +00005524/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00005525/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00005526/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00005527/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00005528bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5529 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005530 if (getLangOptions().CPlusPlus)
5531 return hasSameType(LHS, RHS);
5532
Douglas Gregor447234d2010-07-29 15:18:02 +00005533 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00005534}
5535
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005536bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00005537 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005538}
5539
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005540bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5541 return !mergeTypes(LHS, RHS, true).isNull();
5542}
5543
Peter Collingbourne48466752010-10-24 18:30:18 +00005544/// mergeTransparentUnionType - if T is a transparent union type and a member
5545/// of T is compatible with SubType, return the merged type, else return
5546/// QualType()
5547QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5548 bool OfBlockPointer,
5549 bool Unqualified) {
5550 if (const RecordType *UT = T->getAsUnionType()) {
5551 RecordDecl *UD = UT->getDecl();
5552 if (UD->hasAttr<TransparentUnionAttr>()) {
5553 for (RecordDecl::field_iterator it = UD->field_begin(),
5554 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00005555 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005556 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5557 if (!MT.isNull())
5558 return MT;
5559 }
5560 }
5561 }
5562
5563 return QualType();
5564}
5565
5566/// mergeFunctionArgumentTypes - merge two types which appear as function
5567/// argument types
5568QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5569 bool OfBlockPointer,
5570 bool Unqualified) {
5571 // GNU extension: two types are compatible if they appear as a function
5572 // argument, one of the types is a transparent union type and the other
5573 // type is compatible with a union member
5574 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5575 Unqualified);
5576 if (!lmerge.isNull())
5577 return lmerge;
5578
5579 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5580 Unqualified);
5581 if (!rmerge.isNull())
5582 return rmerge;
5583
5584 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5585}
5586
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005587QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00005588 bool OfBlockPointer,
5589 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00005590 const FunctionType *lbase = lhs->getAs<FunctionType>();
5591 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00005592 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5593 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00005594 bool allLTypes = true;
5595 bool allRTypes = true;
5596
5597 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005598 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005599 if (OfBlockPointer) {
5600 QualType RHS = rbase->getResultType();
5601 QualType LHS = lbase->getResultType();
5602 bool UnqualifiedResult = Unqualified;
5603 if (!UnqualifiedResult)
5604 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005605 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005606 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005607 else
John McCall8cc246c2010-12-15 01:06:38 +00005608 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5609 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005610 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005611
5612 if (Unqualified)
5613 retType = retType.getUnqualifiedType();
5614
5615 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5616 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5617 if (Unqualified) {
5618 LRetType = LRetType.getUnqualifiedType();
5619 RRetType = RRetType.getUnqualifiedType();
5620 }
5621
5622 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005623 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00005624 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005625 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005626
Daniel Dunbar6a15c852010-04-28 16:20:58 +00005627 // FIXME: double check this
5628 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5629 // rbase->getRegParmAttr() != 0 &&
5630 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00005631 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5632 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00005633
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005634 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00005635 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005636 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005637
John McCall8cc246c2010-12-15 01:06:38 +00005638 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00005639 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5640 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00005641 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5642 return QualType();
5643
John McCallf85e1932011-06-15 23:02:42 +00005644 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5645 return QualType();
5646
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005647 // functypes which return are preferred over those that do not.
5648 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5649 allLTypes = false;
5650 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5651 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005652 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5653 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00005654
John McCallf85e1932011-06-15 23:02:42 +00005655 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00005656
Eli Friedman3d815e72008-08-22 00:56:42 +00005657 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00005658 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5659 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005660 unsigned lproto_nargs = lproto->getNumArgs();
5661 unsigned rproto_nargs = rproto->getNumArgs();
5662
5663 // Compatible functions must have the same number of arguments
5664 if (lproto_nargs != rproto_nargs)
5665 return QualType();
5666
5667 // Variadic and non-variadic functions aren't compatible
5668 if (lproto->isVariadic() != rproto->isVariadic())
5669 return QualType();
5670
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00005671 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5672 return QualType();
5673
Fariborz Jahanian78213e42011-09-28 21:52:05 +00005674 if (LangOpts.ObjCAutoRefCount &&
5675 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5676 return QualType();
5677
Eli Friedman3d815e72008-08-22 00:56:42 +00005678 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00005679 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00005680 for (unsigned i = 0; i < lproto_nargs; i++) {
5681 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5682 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005683 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5684 OfBlockPointer,
5685 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005686 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005687
5688 if (Unqualified)
5689 argtype = argtype.getUnqualifiedType();
5690
Eli Friedman3d815e72008-08-22 00:56:42 +00005691 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00005692 if (Unqualified) {
5693 largtype = largtype.getUnqualifiedType();
5694 rargtype = rargtype.getUnqualifiedType();
5695 }
5696
Chris Lattner61710852008-10-05 17:34:18 +00005697 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5698 allLTypes = false;
5699 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5700 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00005701 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00005702
Eli Friedman3d815e72008-08-22 00:56:42 +00005703 if (allLTypes) return lhs;
5704 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005705
5706 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5707 EPI.ExtInfo = einfo;
5708 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005709 }
5710
5711 if (lproto) allRTypes = false;
5712 if (rproto) allLTypes = false;
5713
Douglas Gregor72564e72009-02-26 23:50:07 +00005714 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00005715 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00005716 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005717 if (proto->isVariadic()) return QualType();
5718 // Check that the types are compatible with the types that
5719 // would result from default argument promotions (C99 6.7.5.3p15).
5720 // The only types actually affected are promotable integer
5721 // types and floats, which would be passed as a different
5722 // type depending on whether the prototype is visible.
5723 unsigned proto_nargs = proto->getNumArgs();
5724 for (unsigned i = 0; i < proto_nargs; ++i) {
5725 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00005726
5727 // Look at the promotion type of enum types, since that is the type used
5728 // to pass enum values.
5729 if (const EnumType *Enum = argTy->getAs<EnumType>())
5730 argTy = Enum->getDecl()->getPromotionType();
5731
Eli Friedman3d815e72008-08-22 00:56:42 +00005732 if (argTy->isPromotableIntegerType() ||
5733 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5734 return QualType();
5735 }
5736
5737 if (allLTypes) return lhs;
5738 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005739
5740 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5741 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00005742 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005743 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005744 }
5745
5746 if (allLTypes) return lhs;
5747 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00005748 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00005749}
5750
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005751QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00005752 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005753 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00005754 // C++ [expr]: If an expression initially has the type "reference to T", the
5755 // type is adjusted to "T" prior to any further analysis, the expression
5756 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005757 // expression is an lvalue unless the reference is an rvalue reference and
5758 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005759 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5760 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00005761
5762 if (Unqualified) {
5763 LHS = LHS.getUnqualifiedType();
5764 RHS = RHS.getUnqualifiedType();
5765 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005766
Eli Friedman3d815e72008-08-22 00:56:42 +00005767 QualType LHSCan = getCanonicalType(LHS),
5768 RHSCan = getCanonicalType(RHS);
5769
5770 // If two types are identical, they are compatible.
5771 if (LHSCan == RHSCan)
5772 return LHS;
5773
John McCall0953e762009-09-24 19:53:00 +00005774 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005775 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5776 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00005777 if (LQuals != RQuals) {
5778 // If any of these qualifiers are different, we have a type
5779 // mismatch.
5780 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00005781 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5782 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00005783 return QualType();
5784
5785 // Exactly one GC qualifier difference is allowed: __strong is
5786 // okay if the other type has no GC qualifier but is an Objective
5787 // C object pointer (i.e. implicitly strong by default). We fix
5788 // this by pretending that the unqualified type was actually
5789 // qualified __strong.
5790 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5791 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5792 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5793
5794 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5795 return QualType();
5796
5797 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5798 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5799 }
5800 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5801 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5802 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005803 return QualType();
John McCall0953e762009-09-24 19:53:00 +00005804 }
5805
5806 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00005807
Eli Friedman852d63b2009-06-01 01:22:52 +00005808 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5809 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00005810
Chris Lattner1adb8832008-01-14 05:45:46 +00005811 // We want to consider the two function types to be the same for these
5812 // comparisons, just force one to the other.
5813 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5814 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00005815
5816 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00005817 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5818 LHSClass = Type::ConstantArray;
5819 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5820 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00005821
John McCallc12c5bb2010-05-15 11:32:37 +00005822 // ObjCInterfaces are just specialized ObjCObjects.
5823 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5824 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5825
Nate Begeman213541a2008-04-18 23:10:10 +00005826 // Canonicalize ExtVector -> Vector.
5827 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5828 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00005829
Chris Lattnera36a61f2008-04-07 05:43:21 +00005830 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005831 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00005832 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00005833 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00005834 // Compatibility is based on the underlying type, not the promotion
5835 // type.
John McCall183700f2009-09-21 23:43:11 +00005836 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005837 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5838 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005839 }
John McCall183700f2009-09-21 23:43:11 +00005840 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005841 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5842 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005843 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005844
Eli Friedman3d815e72008-08-22 00:56:42 +00005845 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005846 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005847
Steve Naroff4a746782008-01-09 22:43:08 +00005848 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005849 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00005850#define TYPE(Class, Base)
5851#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00005852#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00005853#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5854#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5855#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00005856 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00005857
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005858 case Type::LValueReference:
5859 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00005860 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00005861 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00005862
John McCallc12c5bb2010-05-15 11:32:37 +00005863 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00005864 case Type::IncompleteArray:
5865 case Type::VariableArray:
5866 case Type::FunctionProto:
5867 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00005868 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00005869
Chris Lattner1adb8832008-01-14 05:45:46 +00005870 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00005871 {
5872 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005873 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5874 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005875 if (Unqualified) {
5876 LHSPointee = LHSPointee.getUnqualifiedType();
5877 RHSPointee = RHSPointee.getUnqualifiedType();
5878 }
5879 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5880 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005881 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00005882 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005883 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00005884 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005885 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005886 return getPointerType(ResultType);
5887 }
Steve Naroffc0febd52008-12-10 17:49:55 +00005888 case Type::BlockPointer:
5889 {
5890 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005891 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5892 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005893 if (Unqualified) {
5894 LHSPointee = LHSPointee.getUnqualifiedType();
5895 RHSPointee = RHSPointee.getUnqualifiedType();
5896 }
5897 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5898 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00005899 if (ResultType.isNull()) return QualType();
5900 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5901 return LHS;
5902 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5903 return RHS;
5904 return getBlockPointerType(ResultType);
5905 }
Eli Friedmanb001de72011-10-06 23:00:33 +00005906 case Type::Atomic:
5907 {
5908 // Merge two pointer types, while trying to preserve typedef info
5909 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
5910 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
5911 if (Unqualified) {
5912 LHSValue = LHSValue.getUnqualifiedType();
5913 RHSValue = RHSValue.getUnqualifiedType();
5914 }
5915 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
5916 Unqualified);
5917 if (ResultType.isNull()) return QualType();
5918 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
5919 return LHS;
5920 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
5921 return RHS;
5922 return getAtomicType(ResultType);
5923 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005924 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00005925 {
5926 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5927 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5928 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5929 return QualType();
5930
5931 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5932 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005933 if (Unqualified) {
5934 LHSElem = LHSElem.getUnqualifiedType();
5935 RHSElem = RHSElem.getUnqualifiedType();
5936 }
5937
5938 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005939 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00005940 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5941 return LHS;
5942 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5943 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00005944 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5945 ArrayType::ArraySizeModifier(), 0);
5946 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5947 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005948 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5949 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00005950 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5951 return LHS;
5952 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5953 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005954 if (LVAT) {
5955 // FIXME: This isn't correct! But tricky to implement because
5956 // the array's size has to be the size of LHS, but the type
5957 // has to be different.
5958 return LHS;
5959 }
5960 if (RVAT) {
5961 // FIXME: This isn't correct! But tricky to implement because
5962 // the array's size has to be the size of RHS, but the type
5963 // has to be different.
5964 return RHS;
5965 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00005966 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5967 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00005968 return getIncompleteArrayType(ResultType,
5969 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005970 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005971 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00005972 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00005973 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00005974 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00005975 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00005976 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005977 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00005978 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00005979 case Type::Complex:
5980 // Distinct complex types are incompatible.
5981 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005982 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005983 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00005984 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5985 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005986 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00005987 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00005988 case Type::ObjCObject: {
5989 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005990 // FIXME: This should be type compatibility, e.g. whether
5991 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00005992 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5993 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5994 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00005995 return LHS;
5996
Eli Friedman3d815e72008-08-22 00:56:42 +00005997 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00005998 }
Steve Naroff14108da2009-07-10 23:34:53 +00005999 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006000 if (OfBlockPointer) {
6001 if (canAssignObjCInterfacesInBlockPointer(
6002 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006003 RHS->getAs<ObjCObjectPointerType>(),
6004 BlockReturnType))
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006005 return LHS;
6006 return QualType();
6007 }
John McCall183700f2009-09-21 23:43:11 +00006008 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6009 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00006010 return LHS;
6011
Steve Naroffbc76dd02008-12-10 22:14:21 +00006012 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006013 }
Steve Naroffec0550f2007-10-15 20:41:53 +00006014 }
Douglas Gregor72564e72009-02-26 23:50:07 +00006015
6016 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00006017}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00006018
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006019bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6020 const FunctionProtoType *FromFunctionType,
6021 const FunctionProtoType *ToFunctionType) {
6022 if (FromFunctionType->hasAnyConsumedArgs() !=
6023 ToFunctionType->hasAnyConsumedArgs())
6024 return false;
6025 FunctionProtoType::ExtProtoInfo FromEPI =
6026 FromFunctionType->getExtProtoInfo();
6027 FunctionProtoType::ExtProtoInfo ToEPI =
6028 ToFunctionType->getExtProtoInfo();
6029 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6030 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6031 ArgIdx != NumArgs; ++ArgIdx) {
6032 if (FromEPI.ConsumedArguments[ArgIdx] !=
6033 ToEPI.ConsumedArguments[ArgIdx])
6034 return false;
6035 }
6036 return true;
6037}
6038
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006039/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6040/// 'RHS' attributes and returns the merged version; including for function
6041/// return types.
6042QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6043 QualType LHSCan = getCanonicalType(LHS),
6044 RHSCan = getCanonicalType(RHS);
6045 // If two types are identical, they are compatible.
6046 if (LHSCan == RHSCan)
6047 return LHS;
6048 if (RHSCan->isFunctionType()) {
6049 if (!LHSCan->isFunctionType())
6050 return QualType();
6051 QualType OldReturnType =
6052 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6053 QualType NewReturnType =
6054 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6055 QualType ResReturnType =
6056 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6057 if (ResReturnType.isNull())
6058 return QualType();
6059 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6060 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6061 // In either case, use OldReturnType to build the new function type.
6062 const FunctionType *F = LHS->getAs<FunctionType>();
6063 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00006064 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6065 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006066 QualType ResultType
6067 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006068 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006069 return ResultType;
6070 }
6071 }
6072 return QualType();
6073 }
6074
6075 // If the qualifiers are different, the types can still be merged.
6076 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6077 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6078 if (LQuals != RQuals) {
6079 // If any of these qualifiers are different, we have a type mismatch.
6080 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6081 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6082 return QualType();
6083
6084 // Exactly one GC qualifier difference is allowed: __strong is
6085 // okay if the other type has no GC qualifier but is an Objective
6086 // C object pointer (i.e. implicitly strong by default). We fix
6087 // this by pretending that the unqualified type was actually
6088 // qualified __strong.
6089 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6090 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6091 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6092
6093 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6094 return QualType();
6095
6096 if (GC_L == Qualifiers::Strong)
6097 return LHS;
6098 if (GC_R == Qualifiers::Strong)
6099 return RHS;
6100 return QualType();
6101 }
6102
6103 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6104 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6105 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6106 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6107 if (ResQT == LHSBaseQT)
6108 return LHS;
6109 if (ResQT == RHSBaseQT)
6110 return RHS;
6111 }
6112 return QualType();
6113}
6114
Chris Lattner5426bf62008-04-07 07:01:58 +00006115//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00006116// Integer Predicates
6117//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00006118
Jay Foad4ba2a172011-01-12 09:06:06 +00006119unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00006120 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00006121 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006122 if (T->isBooleanType())
6123 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00006124 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00006125 return (unsigned)getTypeSize(T);
6126}
6127
6128QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00006129 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00006130
6131 // Turn <4 x signed int> -> <4 x unsigned int>
6132 if (const VectorType *VTy = T->getAs<VectorType>())
6133 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00006134 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00006135
6136 // For enums, we return the unsigned version of the base type.
6137 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00006138 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00006139
6140 const BuiltinType *BTy = T->getAs<BuiltinType>();
6141 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006142 switch (BTy->getKind()) {
6143 case BuiltinType::Char_S:
6144 case BuiltinType::SChar:
6145 return UnsignedCharTy;
6146 case BuiltinType::Short:
6147 return UnsignedShortTy;
6148 case BuiltinType::Int:
6149 return UnsignedIntTy;
6150 case BuiltinType::Long:
6151 return UnsignedLongTy;
6152 case BuiltinType::LongLong:
6153 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00006154 case BuiltinType::Int128:
6155 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00006156 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00006157 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006158 }
6159}
6160
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00006161ASTMutationListener::~ASTMutationListener() { }
6162
Chris Lattner86df27b2009-06-14 00:45:47 +00006163
6164//===----------------------------------------------------------------------===//
6165// Builtin Type Computation
6166//===----------------------------------------------------------------------===//
6167
6168/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00006169/// pointer over the consumed characters. This returns the resultant type. If
6170/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6171/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6172/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00006173///
6174/// RequiresICE is filled in on return to indicate whether the value is required
6175/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00006176static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00006177 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00006178 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00006179 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00006180 // Modifiers.
6181 int HowLong = 0;
6182 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00006183 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006184
Chris Lattner33daae62010-10-01 22:42:38 +00006185 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00006186 bool Done = false;
6187 while (!Done) {
6188 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00006189 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006190 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00006191 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006192 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006193 case 'S':
6194 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6195 assert(!Signed && "Can't use 'S' modifier multiple times!");
6196 Signed = true;
6197 break;
6198 case 'U':
6199 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6200 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6201 Unsigned = true;
6202 break;
6203 case 'L':
6204 assert(HowLong <= 2 && "Can't have LLLL modifier");
6205 ++HowLong;
6206 break;
6207 }
6208 }
6209
6210 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00006211
Chris Lattner86df27b2009-06-14 00:45:47 +00006212 // Read the base type.
6213 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00006214 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00006215 case 'v':
6216 assert(HowLong == 0 && !Signed && !Unsigned &&
6217 "Bad modifiers used with 'v'!");
6218 Type = Context.VoidTy;
6219 break;
6220 case 'f':
6221 assert(HowLong == 0 && !Signed && !Unsigned &&
6222 "Bad modifiers used with 'f'!");
6223 Type = Context.FloatTy;
6224 break;
6225 case 'd':
6226 assert(HowLong < 2 && !Signed && !Unsigned &&
6227 "Bad modifiers used with 'd'!");
6228 if (HowLong)
6229 Type = Context.LongDoubleTy;
6230 else
6231 Type = Context.DoubleTy;
6232 break;
6233 case 's':
6234 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6235 if (Unsigned)
6236 Type = Context.UnsignedShortTy;
6237 else
6238 Type = Context.ShortTy;
6239 break;
6240 case 'i':
6241 if (HowLong == 3)
6242 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6243 else if (HowLong == 2)
6244 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6245 else if (HowLong == 1)
6246 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6247 else
6248 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6249 break;
6250 case 'c':
6251 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6252 if (Signed)
6253 Type = Context.SignedCharTy;
6254 else if (Unsigned)
6255 Type = Context.UnsignedCharTy;
6256 else
6257 Type = Context.CharTy;
6258 break;
6259 case 'b': // boolean
6260 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6261 Type = Context.BoolTy;
6262 break;
6263 case 'z': // size_t.
6264 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6265 Type = Context.getSizeType();
6266 break;
6267 case 'F':
6268 Type = Context.getCFConstantStringType();
6269 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00006270 case 'G':
6271 Type = Context.getObjCIdType();
6272 break;
6273 case 'H':
6274 Type = Context.getObjCSelType();
6275 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006276 case 'a':
6277 Type = Context.getBuiltinVaListType();
6278 assert(!Type.isNull() && "builtin va list type not initialized!");
6279 break;
6280 case 'A':
6281 // This is a "reference" to a va_list; however, what exactly
6282 // this means depends on how va_list is defined. There are two
6283 // different kinds of va_list: ones passed by value, and ones
6284 // passed by reference. An example of a by-value va_list is
6285 // x86, where va_list is a char*. An example of by-ref va_list
6286 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6287 // we want this argument to be a char*&; for x86-64, we want
6288 // it to be a __va_list_tag*.
6289 Type = Context.getBuiltinVaListType();
6290 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00006291 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00006292 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00006293 else
Chris Lattner86df27b2009-06-14 00:45:47 +00006294 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00006295 break;
6296 case 'V': {
6297 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00006298 unsigned NumElements = strtoul(Str, &End, 10);
6299 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00006300 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00006301
Chris Lattner14e0e742010-10-01 22:53:11 +00006302 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6303 RequiresICE, false);
6304 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00006305
6306 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00006307 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00006308 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00006309 break;
6310 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00006311 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00006312 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6313 false);
6314 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00006315 Type = Context.getComplexType(ElementType);
6316 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00006317 }
6318 case 'Y' : {
6319 Type = Context.getPointerDiffType();
6320 break;
6321 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006322 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00006323 Type = Context.getFILEType();
6324 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006325 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00006326 return QualType();
6327 }
Mike Stumpfd612db2009-07-28 23:47:15 +00006328 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006329 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00006330 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00006331 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00006332 else
6333 Type = Context.getjmp_bufType();
6334
Mike Stumpfd612db2009-07-28 23:47:15 +00006335 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006336 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00006337 return QualType();
6338 }
6339 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00006340 case 'K':
6341 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6342 Type = Context.getucontext_tType();
6343
6344 if (Type.isNull()) {
6345 Error = ASTContext::GE_Missing_ucontext;
6346 return QualType();
6347 }
6348 break;
Mike Stump782fa302009-07-28 02:25:19 +00006349 }
Mike Stump1eb44332009-09-09 15:08:12 +00006350
Chris Lattner33daae62010-10-01 22:42:38 +00006351 // If there are modifiers and if we're allowed to parse them, go for it.
6352 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00006353 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00006354 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00006355 default: Done = true; --Str; break;
6356 case '*':
6357 case '&': {
6358 // Both pointers and references can have their pointee types
6359 // qualified with an address space.
6360 char *End;
6361 unsigned AddrSpace = strtoul(Str, &End, 10);
6362 if (End != Str && AddrSpace != 0) {
6363 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6364 Str = End;
6365 }
6366 if (c == '*')
6367 Type = Context.getPointerType(Type);
6368 else
6369 Type = Context.getLValueReferenceType(Type);
6370 break;
6371 }
6372 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6373 case 'C':
6374 Type = Type.withConst();
6375 break;
6376 case 'D':
6377 Type = Context.getVolatileType(Type);
6378 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006379 }
6380 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00006381
Chris Lattner14e0e742010-10-01 22:53:11 +00006382 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00006383 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00006384
Chris Lattner86df27b2009-06-14 00:45:47 +00006385 return Type;
6386}
6387
6388/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00006389QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00006390 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00006391 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00006392 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00006393
Chris Lattner5f9e2722011-07-23 10:55:15 +00006394 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00006395
Chris Lattner14e0e742010-10-01 22:53:11 +00006396 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00006397 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00006398 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6399 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006400 if (Error != GE_None)
6401 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00006402
6403 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6404
Chris Lattner86df27b2009-06-14 00:45:47 +00006405 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00006406 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006407 if (Error != GE_None)
6408 return QualType();
6409
Chris Lattner14e0e742010-10-01 22:53:11 +00006410 // If this argument is required to be an IntegerConstantExpression and the
6411 // caller cares, fill in the bitmask we return.
6412 if (RequiresICE && IntegerConstantArgs)
6413 *IntegerConstantArgs |= 1 << ArgTypes.size();
6414
Chris Lattner86df27b2009-06-14 00:45:47 +00006415 // Do array -> pointer decay. The builtin should use the decayed type.
6416 if (Ty->isArrayType())
6417 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00006418
Chris Lattner86df27b2009-06-14 00:45:47 +00006419 ArgTypes.push_back(Ty);
6420 }
6421
6422 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6423 "'.' should only occur at end of builtin type list!");
6424
John McCall00ccbef2010-12-21 00:44:39 +00006425 FunctionType::ExtInfo EI;
6426 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6427
6428 bool Variadic = (TypeStr[0] == '.');
6429
6430 // We really shouldn't be making a no-proto type here, especially in C++.
6431 if (ArgTypes.empty() && Variadic)
6432 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00006433
John McCalle23cf432010-12-14 08:05:40 +00006434 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00006435 EPI.ExtInfo = EI;
6436 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00006437
6438 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00006439}
Eli Friedmana95d7572009-08-19 07:44:53 +00006440
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006441GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6442 GVALinkage External = GVA_StrongExternal;
6443
6444 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006445 switch (L) {
6446 case NoLinkage:
6447 case InternalLinkage:
6448 case UniqueExternalLinkage:
6449 return GVA_Internal;
6450
6451 case ExternalLinkage:
6452 switch (FD->getTemplateSpecializationKind()) {
6453 case TSK_Undeclared:
6454 case TSK_ExplicitSpecialization:
6455 External = GVA_StrongExternal;
6456 break;
6457
6458 case TSK_ExplicitInstantiationDefinition:
6459 return GVA_ExplicitTemplateInstantiation;
6460
6461 case TSK_ExplicitInstantiationDeclaration:
6462 case TSK_ImplicitInstantiation:
6463 External = GVA_TemplateInstantiation;
6464 break;
6465 }
6466 }
6467
6468 if (!FD->isInlined())
6469 return External;
6470
6471 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6472 // GNU or C99 inline semantics. Determine whether this symbol should be
6473 // externally visible.
6474 if (FD->isInlineDefinitionExternallyVisible())
6475 return External;
6476
6477 // C99 inline semantics, where the symbol is not externally visible.
6478 return GVA_C99Inline;
6479 }
6480
6481 // C++0x [temp.explicit]p9:
6482 // [ Note: The intent is that an inline function that is the subject of
6483 // an explicit instantiation declaration will still be implicitly
6484 // instantiated when used so that the body can be considered for
6485 // inlining, but that no out-of-line copy of the inline function would be
6486 // generated in the translation unit. -- end note ]
6487 if (FD->getTemplateSpecializationKind()
6488 == TSK_ExplicitInstantiationDeclaration)
6489 return GVA_C99Inline;
6490
6491 return GVA_CXXInline;
6492}
6493
6494GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6495 // If this is a static data member, compute the kind of template
6496 // specialization. Otherwise, this variable is not part of a
6497 // template.
6498 TemplateSpecializationKind TSK = TSK_Undeclared;
6499 if (VD->isStaticDataMember())
6500 TSK = VD->getTemplateSpecializationKind();
6501
6502 Linkage L = VD->getLinkage();
6503 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6504 VD->getType()->getLinkage() == UniqueExternalLinkage)
6505 L = UniqueExternalLinkage;
6506
6507 switch (L) {
6508 case NoLinkage:
6509 case InternalLinkage:
6510 case UniqueExternalLinkage:
6511 return GVA_Internal;
6512
6513 case ExternalLinkage:
6514 switch (TSK) {
6515 case TSK_Undeclared:
6516 case TSK_ExplicitSpecialization:
6517 return GVA_StrongExternal;
6518
6519 case TSK_ExplicitInstantiationDeclaration:
6520 llvm_unreachable("Variable should not be instantiated");
6521 // Fall through to treat this like any other instantiation.
6522
6523 case TSK_ExplicitInstantiationDefinition:
6524 return GVA_ExplicitTemplateInstantiation;
6525
6526 case TSK_ImplicitInstantiation:
6527 return GVA_TemplateInstantiation;
6528 }
6529 }
6530
6531 return GVA_StrongExternal;
6532}
6533
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00006534bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006535 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6536 if (!VD->isFileVarDecl())
6537 return false;
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00006538 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006539 return false;
6540
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006541 // Weak references don't produce any output by themselves.
6542 if (D->hasAttr<WeakRefAttr>())
6543 return false;
6544
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006545 // Aliases and used decls are required.
6546 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6547 return true;
6548
6549 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6550 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00006551 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00006552 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006553
6554 // Constructors and destructors are required.
6555 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6556 return true;
6557
6558 // The key function for a class is required.
6559 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6560 const CXXRecordDecl *RD = MD->getParent();
6561 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6562 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6563 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6564 return true;
6565 }
6566 }
6567
6568 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6569
6570 // static, static inline, always_inline, and extern inline functions can
6571 // always be deferred. Normal inline functions can be deferred in C99/C++.
6572 // Implicit template instantiations can also be deferred in C++.
6573 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6574 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6575 return false;
6576 return true;
6577 }
Douglas Gregor94da1582011-09-10 00:22:34 +00006578
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006579 const VarDecl *VD = cast<VarDecl>(D);
6580 assert(VD->isFileVarDecl() && "Expected file scoped var");
6581
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006582 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6583 return false;
6584
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006585 // Structs that have non-trivial constructors or destructors are required.
6586
6587 // FIXME: Handle references.
Sean Hunt023df372011-05-09 18:22:59 +00006588 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006589 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6590 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Sean Hunt023df372011-05-09 18:22:59 +00006591 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6592 RD->hasTrivialCopyConstructor() &&
6593 RD->hasTrivialMoveConstructor() &&
6594 RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006595 return true;
6596 }
6597 }
6598
6599 GVALinkage L = GetGVALinkageForVariable(VD);
6600 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6601 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6602 return false;
6603 }
6604
6605 return true;
6606}
Charles Davis071cc7d2010-08-16 03:33:14 +00006607
Charles Davisee743f92010-11-09 18:04:24 +00006608CallingConv ASTContext::getDefaultMethodCallConv() {
6609 // Pass through to the C++ ABI object
6610 return ABI->getDefaultMethodCallConv();
6611}
6612
Jay Foad4ba2a172011-01-12 09:06:06 +00006613bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00006614 // Pass through to the C++ ABI object
6615 return ABI->isNearlyEmpty(RD);
6616}
6617
Peter Collingbourne14110472011-01-13 18:57:25 +00006618MangleContext *ASTContext::createMangleContext() {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00006619 switch (Target->getCXXABI()) {
Peter Collingbourne14110472011-01-13 18:57:25 +00006620 case CXXABI_ARM:
6621 case CXXABI_Itanium:
6622 return createItaniumMangleContext(*this, getDiagnostics());
6623 case CXXABI_Microsoft:
6624 return createMicrosoftMangleContext(*this, getDiagnostics());
6625 }
David Blaikieb219cfc2011-09-23 05:06:16 +00006626 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00006627}
6628
Charles Davis071cc7d2010-08-16 03:33:14 +00006629CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00006630
6631size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00006632 return ASTRecordLayouts.getMemorySize()
6633 + llvm::capacity_in_bytes(ObjCLayouts)
6634 + llvm::capacity_in_bytes(KeyFunctions)
6635 + llvm::capacity_in_bytes(ObjCImpls)
6636 + llvm::capacity_in_bytes(BlockVarCopyInits)
6637 + llvm::capacity_in_bytes(DeclAttrs)
6638 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6639 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6640 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6641 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6642 + llvm::capacity_in_bytes(OverriddenMethods)
6643 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00006644 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00006645 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00006646}
Ted Kremenekd211cb72011-10-06 05:00:56 +00006647
6648void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6649 ParamIndices[D] = index;
6650}
6651
6652unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6653 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6654 assert(I != ParamIndices.end() &&
6655 "ParmIndices lacks entry set by ParmVarDecl");
6656 return I->second;
6657}