blob: 8a4c9d333823b8b6c85486ec92405268195772a5 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCallea1471e2010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +000033#include "llvm/Support/Capacity.h"
Charles Davis071cc7d2010-08-16 03:33:14 +000034#include "CXXABI.h"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000035#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000036
Reid Spencer5f016e22007-07-11 17:01:13 +000037using namespace clang;
38
Douglas Gregor18274032010-07-03 00:47:00 +000039unsigned ASTContext::NumImplicitDefaultConstructors;
40unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000041unsigned ASTContext::NumImplicitCopyConstructors;
42unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000043unsigned ASTContext::NumImplicitMoveConstructors;
44unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000045unsigned ASTContext::NumImplicitCopyAssignmentOperators;
46unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000047unsigned ASTContext::NumImplicitMoveAssignmentOperators;
48unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000049unsigned ASTContext::NumImplicitDestructors;
50unsigned ASTContext::NumImplicitDestructorsDeclared;
51
Reid Spencer5f016e22007-07-11 17:01:13 +000052enum FloatingRank {
53 FloatRank, DoubleRank, LongDoubleRank
54};
55
Douglas Gregor3e1274f2010-06-16 21:09:37 +000056void
57ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
58 TemplateTemplateParmDecl *Parm) {
59 ID.AddInteger(Parm->getDepth());
60 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +000061 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000062
63 TemplateParameterList *Params = Parm->getTemplateParameters();
64 ID.AddInteger(Params->size());
65 for (TemplateParameterList::const_iterator P = Params->begin(),
66 PEnd = Params->end();
67 P != PEnd; ++P) {
68 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
69 ID.AddInteger(0);
70 ID.AddBoolean(TTP->isParameterPack());
71 continue;
72 }
73
74 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
75 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +000076 ID.AddBoolean(NTTP->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000077 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +000078 if (NTTP->isExpandedParameterPack()) {
79 ID.AddBoolean(true);
80 ID.AddInteger(NTTP->getNumExpansionTypes());
81 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
82 ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
83 } else
84 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +000085 continue;
86 }
87
88 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
89 ID.AddInteger(2);
90 Profile(ID, TTP);
91 }
92}
93
94TemplateTemplateParmDecl *
95ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +000096 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +000097 // Check if we already have a canonical template template parameter.
98 llvm::FoldingSetNodeID ID;
99 CanonicalTemplateTemplateParm::Profile(ID, TTP);
100 void *InsertPos = 0;
101 CanonicalTemplateTemplateParm *Canonical
102 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
103 if (Canonical)
104 return Canonical->getParam();
105
106 // Build a canonical template parameter list.
107 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000108 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000109 CanonParams.reserve(Params->size());
110 for (TemplateParameterList::const_iterator P = Params->begin(),
111 PEnd = Params->end();
112 P != PEnd; ++P) {
113 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
114 CanonParams.push_back(
115 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000116 SourceLocation(),
117 SourceLocation(),
118 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000119 TTP->getIndex(), 0, false,
120 TTP->isParameterPack()));
121 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000122 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
123 QualType T = getCanonicalType(NTTP->getType());
124 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
125 NonTypeTemplateParmDecl *Param;
126 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000127 SmallVector<QualType, 2> ExpandedTypes;
128 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000129 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
130 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
131 ExpandedTInfos.push_back(
132 getTrivialTypeSourceInfo(ExpandedTypes.back()));
133 }
134
135 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000136 SourceLocation(),
137 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000138 NTTP->getDepth(),
139 NTTP->getPosition(), 0,
140 T,
141 TInfo,
142 ExpandedTypes.data(),
143 ExpandedTypes.size(),
144 ExpandedTInfos.data());
145 } else {
146 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000147 SourceLocation(),
148 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000149 NTTP->getDepth(),
150 NTTP->getPosition(), 0,
151 T,
152 NTTP->isParameterPack(),
153 TInfo);
154 }
155 CanonParams.push_back(Param);
156
157 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000158 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
159 cast<TemplateTemplateParmDecl>(*P)));
160 }
161
162 TemplateTemplateParmDecl *CanonTTP
163 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
164 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000165 TTP->getPosition(),
166 TTP->isParameterPack(),
167 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000168 TemplateParameterList::Create(*this, SourceLocation(),
169 SourceLocation(),
170 CanonParams.data(),
171 CanonParams.size(),
172 SourceLocation()));
173
174 // Get the new insert position for the node we care about.
175 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
176 assert(Canonical == 0 && "Shouldn't be in the map!");
177 (void)Canonical;
178
179 // Create the canonical template template parameter entry.
180 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
181 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
182 return CanonTTP;
183}
184
Charles Davis071cc7d2010-08-16 03:33:14 +0000185CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000186 if (!LangOpts.CPlusPlus) return 0;
187
Charles Davis20cf7172010-08-19 02:18:14 +0000188 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000189 case CXXABI_ARM:
190 return CreateARMCXXABI(*this);
191 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000192 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000193 case CXXABI_Microsoft:
194 return CreateMicrosoftCXXABI(*this);
195 }
John McCallee79a4c2010-08-21 22:46:04 +0000196 return 0;
Charles Davis071cc7d2010-08-16 03:33:14 +0000197}
198
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000199static const LangAS::Map &getAddressSpaceMap(const TargetInfo &T,
200 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 };
209 return FakeAddrSpaceMap;
210 } else {
211 return T.getAddressSpaceMap();
212 }
213}
214
Chris Lattner61710852008-10-05 17:34:18 +0000215ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +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 Gregor63fe86b2010-07-25 17:53:33 +0000219 unsigned size_reserve) :
Sebastian Redl8026f6d2011-03-13 17:09:40 +0000220 FunctionProtoTypes(this_()),
John McCallef990012010-06-11 11:07:21 +0000221 TemplateSpecializationTypes(this_()),
222 DependentTemplateSpecializationTypes(this_()),
John McCall14606042011-06-30 08:33:18 +0000223 SubstTemplateTemplateParmPacks(this_()),
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +0000224 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
Douglas Gregor7a27ea52011-08-12 06:17:30 +0000225 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0),
Douglas Gregor79d67262011-08-12 05:59:41 +0000226 CFConstantStringTypeDecl(0),
Douglas Gregor0815b572011-08-09 17:23:49 +0000227 FILEDecl(0),
John McCallf85e1932011-06-15 23:02:42 +0000228 jmp_bufDecl(0), sigjmp_bufDecl(0), BlockDescriptorType(0),
229 BlockDescriptorExtendedType(0), cudaConfigureCallDecl(0),
John McCallbf1a0282010-06-04 23:28:52 +0000230 NullTypeSourceInfo(QualType()),
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000231 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)),
232 AddrSpaceMap(getAddressSpaceMap(t, LOpts)), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +0000233 Idents(idents), Selectors(sels),
Ted Kremenekac9590e2010-05-10 20:40:08 +0000234 BuiltinInfo(builtins),
235 DeclarationNames(*this),
Argyrios Kyrtzidis9a44b5f2010-10-28 09:29:35 +0000236 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenekf057bf72010-06-18 00:31:04 +0000237 LastSDM(0, 0),
John McCall8178df32011-02-22 22:38:33 +0000238 UniqueBlockByRefTypeID(0) {
Mike Stump1eb44332009-09-09 15:08:12 +0000239 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000240 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +0000241 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +0000242}
243
Reid Spencer5f016e22007-07-11 17:01:13 +0000244ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000245 // Release the DenseMaps associated with DeclContext objects.
246 // FIXME: Is this the ideal solution?
247 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000248
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000249 // Call all of the deallocation functions.
250 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
251 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000252
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000253 // Release all of the memory associated with overridden C++ methods.
254 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
255 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
256 OM != OMEnd; ++OM)
257 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +0000258
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000259 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000260 // because they can contain DenseMaps.
261 for (llvm::DenseMap<const ObjCContainerDecl*,
262 const ASTRecordLayout*>::iterator
263 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
264 // Increment in loop to prevent using deallocated memory.
265 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
266 R->Destroy(*this);
267
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000268 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
269 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
270 // Increment in loop to prevent using deallocated memory.
271 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
272 R->Destroy(*this);
273 }
Douglas Gregor63200642010-08-30 16:49:28 +0000274
275 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
276 AEnd = DeclAttrs.end();
277 A != AEnd; ++A)
278 A->second->~AttrVec();
279}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000280
Douglas Gregor00545312010-05-23 18:26:36 +0000281void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
282 Deallocations.push_back(std::make_pair(Callback, Data));
283}
284
Mike Stump1eb44332009-09-09 15:08:12 +0000285void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000286ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
287 ExternalSource.reset(Source.take());
288}
289
Reid Spencer5f016e22007-07-11 17:01:13 +0000290void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000291 llvm::errs() << "\n*** AST Context Stats:\n";
292 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000293
Douglas Gregordbe833d2009-05-26 14:40:08 +0000294 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000295#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000296#define ABSTRACT_TYPE(Name, Parent)
297#include "clang/AST/TypeNodes.def"
298 0 // Extra
299 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000300
Reid Spencer5f016e22007-07-11 17:01:13 +0000301 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
302 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000303 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000304 }
305
Douglas Gregordbe833d2009-05-26 14:40:08 +0000306 unsigned Idx = 0;
307 unsigned TotalBytes = 0;
308#define TYPE(Name, Parent) \
309 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000310 llvm::errs() << " " << counts[Idx] << " " << #Name \
311 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000312 TotalBytes += counts[Idx] * sizeof(Name##Type); \
313 ++Idx;
314#define ABSTRACT_TYPE(Name, Parent)
315#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000316
Chandler Carruthcd92a652011-07-04 05:32:14 +0000317 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
318
Douglas Gregor4923aa22010-07-02 20:37:36 +0000319 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000320 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
321 << NumImplicitDefaultConstructors
322 << " implicit default constructors created\n";
323 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
324 << NumImplicitCopyConstructors
325 << " implicit copy constructors created\n";
Sean Huntffe37fd2011-05-25 20:50:04 +0000326 if (getLangOptions().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000327 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
328 << NumImplicitMoveConstructors
329 << " implicit move constructors created\n";
330 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
331 << NumImplicitCopyAssignmentOperators
332 << " implicit copy assignment operators created\n";
Sean Huntffe37fd2011-05-25 20:50:04 +0000333 if (getLangOptions().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000334 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
335 << NumImplicitMoveAssignmentOperators
336 << " implicit move assignment operators created\n";
337 llvm::errs() << NumImplicitDestructorsDeclared << "/"
338 << NumImplicitDestructors
339 << " implicit destructors created\n";
340
Douglas Gregor2cf26342009-04-09 22:27:44 +0000341 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000342 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000343 ExternalSource->PrintStats();
344 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000345
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000346 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000347}
348
349
John McCalle27ec8a2009-10-23 23:03:21 +0000350void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000351 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000352 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000353 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000354}
355
Reid Spencer5f016e22007-07-11 17:01:13 +0000356void ASTContext::InitBuiltinTypes() {
357 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Reid Spencer5f016e22007-07-11 17:01:13 +0000359 // C99 6.2.5p19.
360 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 // C99 6.2.5p2.
363 InitBuiltinType(BoolTy, BuiltinType::Bool);
364 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000365 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000366 InitBuiltinType(CharTy, BuiltinType::Char_S);
367 else
368 InitBuiltinType(CharTy, BuiltinType::Char_U);
369 // C99 6.2.5p4.
370 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
371 InitBuiltinType(ShortTy, BuiltinType::Short);
372 InitBuiltinType(IntTy, BuiltinType::Int);
373 InitBuiltinType(LongTy, BuiltinType::Long);
374 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000375
Reid Spencer5f016e22007-07-11 17:01:13 +0000376 // C99 6.2.5p6.
377 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
378 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
379 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
380 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
381 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000382
Reid Spencer5f016e22007-07-11 17:01:13 +0000383 // C99 6.2.5p10.
384 InitBuiltinType(FloatTy, BuiltinType::Float);
385 InitBuiltinType(DoubleTy, BuiltinType::Double);
386 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000387
Chris Lattner2df9ced2009-04-30 02:43:43 +0000388 // GNU extension, 128-bit integers.
389 InitBuiltinType(Int128Ty, BuiltinType::Int128);
390 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
391
Chris Lattner3f59c972010-12-25 23:25:43 +0000392 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedmand3d77cd2011-04-30 19:24:24 +0000393 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattner3f59c972010-12-25 23:25:43 +0000394 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
395 else // -fshort-wchar makes wchar_t be unsigned.
396 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
397 } else // C99
Chris Lattner3a250322009-02-26 23:43:47 +0000398 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000399
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000400 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
401 InitBuiltinType(Char16Ty, BuiltinType::Char16);
402 else // C99
403 Char16Ty = getFromTargetType(Target.getChar16Type());
404
405 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
406 InitBuiltinType(Char32Ty, BuiltinType::Char32);
407 else // C99
408 Char32Ty = getFromTargetType(Target.getChar32Type());
409
Douglas Gregor898574e2008-12-05 23:32:09 +0000410 // Placeholder type for type-dependent expressions whose type is
411 // completely unknown. No code should ever check a type against
412 // DependentTy and users should never see it; however, it is here to
413 // help diagnose failures to properly check for type-dependent
414 // expressions.
415 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000416
John McCall2a984ca2010-10-12 00:20:44 +0000417 // Placeholder type for functions.
418 InitBuiltinType(OverloadTy, BuiltinType::Overload);
419
John McCall864c0412011-04-26 20:42:42 +0000420 // Placeholder type for bound members.
421 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
422
John McCall1de4d4e2011-04-07 08:22:57 +0000423 // "any" type; useful for debugger-like clients.
424 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
425
Reid Spencer5f016e22007-07-11 17:01:13 +0000426 // C99 6.2.5p11.
427 FloatComplexTy = getComplexType(FloatTy);
428 DoubleComplexTy = getComplexType(DoubleTy);
429 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000430
Steve Naroff7e219e42007-10-15 14:41:52 +0000431 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000433 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000434 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
435 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000436 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000437
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000438 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000440 // void * type
441 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000442
443 // nullptr type (C++0x 2.14.7)
444 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000445}
446
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000447Diagnostic &ASTContext::getDiagnostics() const {
448 return SourceMgr.getDiagnostics();
449}
450
Douglas Gregor63200642010-08-30 16:49:28 +0000451AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
452 AttrVec *&Result = DeclAttrs[D];
453 if (!Result) {
454 void *Mem = Allocate(sizeof(AttrVec));
455 Result = new (Mem) AttrVec;
456 }
457
458 return *Result;
459}
460
461/// \brief Erase the attributes corresponding to the given declaration.
462void ASTContext::eraseDeclAttrs(const Decl *D) {
463 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
464 if (Pos != DeclAttrs.end()) {
465 Pos->second->~AttrVec();
466 DeclAttrs.erase(Pos);
467 }
468}
469
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000470MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000471ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000472 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000473 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000474 = InstantiatedFromStaticDataMember.find(Var);
475 if (Pos == InstantiatedFromStaticDataMember.end())
476 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000477
Douglas Gregor7caa6822009-07-24 20:34:43 +0000478 return Pos->second;
479}
480
Mike Stump1eb44332009-09-09 15:08:12 +0000481void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000482ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000483 TemplateSpecializationKind TSK,
484 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000485 assert(Inst->isStaticDataMember() && "Not a static data member");
486 assert(Tmpl->isStaticDataMember() && "Not a static data member");
487 assert(!InstantiatedFromStaticDataMember[Inst] &&
488 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000489 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000490 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000491}
492
John McCall7ba107a2009-11-18 02:36:19 +0000493NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000494ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000495 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000496 = InstantiatedFromUsingDecl.find(UUD);
497 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000498 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000499
Anders Carlsson0d8df782009-08-29 19:37:28 +0000500 return Pos->second;
501}
502
503void
John McCalled976492009-12-04 22:46:56 +0000504ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
505 assert((isa<UsingDecl>(Pattern) ||
506 isa<UnresolvedUsingValueDecl>(Pattern) ||
507 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
508 "pattern decl is not a using decl");
509 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
510 InstantiatedFromUsingDecl[Inst] = Pattern;
511}
512
513UsingShadowDecl *
514ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
515 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
516 = InstantiatedFromUsingShadowDecl.find(Inst);
517 if (Pos == InstantiatedFromUsingShadowDecl.end())
518 return 0;
519
520 return Pos->second;
521}
522
523void
524ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
525 UsingShadowDecl *Pattern) {
526 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
527 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000528}
529
Anders Carlssond8b285f2009-09-01 04:26:58 +0000530FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
531 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
532 = InstantiatedFromUnnamedFieldDecl.find(Field);
533 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
534 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000535
Anders Carlssond8b285f2009-09-01 04:26:58 +0000536 return Pos->second;
537}
538
539void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
540 FieldDecl *Tmpl) {
541 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
542 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
543 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
544 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000545
Anders Carlssond8b285f2009-09-01 04:26:58 +0000546 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
547}
548
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000549bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
550 const FieldDecl *LastFD) const {
551 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Chad Rosier682b7f82011-08-04 21:50:29 +0000552 FD->getBitWidth()->EvaluateAsInt(*this).getZExtValue() == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000553}
554
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000555bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
556 const FieldDecl *LastFD) const {
557 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Chad Rosier682b7f82011-08-04 21:50:29 +0000558 FD->getBitWidth()->EvaluateAsInt(*this).getZExtValue() == 0 &&
559 LastFD->getBitWidth()->EvaluateAsInt(*this).getZExtValue() != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000560}
561
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000562bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
563 const FieldDecl *LastFD) const {
564 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Chad Rosier682b7f82011-08-04 21:50:29 +0000565 FD->getBitWidth()->EvaluateAsInt(*this).getZExtValue() &&
566 LastFD->getBitWidth()->EvaluateAsInt(*this).getZExtValue());
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000567}
568
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000569bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000570 const FieldDecl *LastFD) const {
571 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Chad Rosier682b7f82011-08-04 21:50:29 +0000572 LastFD->getBitWidth()->EvaluateAsInt(*this).getZExtValue());
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000573}
574
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000575bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000576 const FieldDecl *LastFD) const {
577 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Chad Rosier682b7f82011-08-04 21:50:29 +0000578 FD->getBitWidth()->EvaluateAsInt(*this).getZExtValue());
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000579}
580
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000581ASTContext::overridden_cxx_method_iterator
582ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
583 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
584 = OverriddenMethods.find(Method);
585 if (Pos == OverriddenMethods.end())
586 return 0;
587
588 return Pos->second.begin();
589}
590
591ASTContext::overridden_cxx_method_iterator
592ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
593 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
594 = OverriddenMethods.find(Method);
595 if (Pos == OverriddenMethods.end())
596 return 0;
597
598 return Pos->second.end();
599}
600
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000601unsigned
602ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
603 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
604 = OverriddenMethods.find(Method);
605 if (Pos == OverriddenMethods.end())
606 return 0;
607
608 return Pos->second.size();
609}
610
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000611void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
612 const CXXMethodDecl *Overridden) {
613 OverriddenMethods[Method].push_back(Overridden);
614}
615
Chris Lattner464175b2007-07-18 17:52:12 +0000616//===----------------------------------------------------------------------===//
617// Type Sizing and Analysis
618//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000619
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000620/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
621/// scalar floating point type.
622const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000623 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000624 assert(BT && "Not a floating point type!");
625 switch (BT->getKind()) {
626 default: assert(0 && "Not a floating point type!");
627 case BuiltinType::Float: return Target.getFloatFormat();
628 case BuiltinType::Double: return Target.getDoubleFormat();
629 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
630 }
631}
632
Ken Dyck8b752f12010-01-27 17:10:57 +0000633/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000634/// specified decl. Note that bitfields do not have a valid alignment, so
635/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000636/// If @p RefAsPointee, references are treated like their underlying type
637/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +0000638CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000639 unsigned Align = Target.getCharWidth();
640
John McCall4081a5c2010-10-08 18:24:19 +0000641 bool UseAlignAttrOnly = false;
642 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
643 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +0000644
John McCall4081a5c2010-10-08 18:24:19 +0000645 // __attribute__((aligned)) can increase or decrease alignment
646 // *except* on a struct or struct member, where it only increases
647 // alignment unless 'packed' is also specified.
648 //
649 // It is an error for [[align]] to decrease alignment, so we can
650 // ignore that possibility; Sema should diagnose it.
651 if (isa<FieldDecl>(D)) {
652 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
653 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
654 } else {
655 UseAlignAttrOnly = true;
656 }
657 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +0000658 else if (isa<FieldDecl>(D))
659 UseAlignAttrOnly =
660 D->hasAttr<PackedAttr>() ||
661 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +0000662
John McCallba4f5d52011-01-20 07:57:12 +0000663 // If we're using the align attribute only, just ignore everything
664 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +0000665 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +0000666 // do nothing
667
John McCall4081a5c2010-10-08 18:24:19 +0000668 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +0000669 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000670 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000671 if (RefAsPointee)
672 T = RT->getPointeeType();
673 else
674 T = getPointerType(RT->getPointeeType());
675 }
676 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +0000677 // Adjust alignments of declarations with array type by the
678 // large-array alignment on the target.
Rafael Espindola6deecb02010-06-04 23:15:27 +0000679 unsigned MinWidth = Target.getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +0000680 const ArrayType *arrayType;
681 if (MinWidth && (arrayType = getAsArrayType(T))) {
682 if (isa<VariableArrayType>(arrayType))
683 Align = std::max(Align, Target.getLargeArrayAlign());
684 else if (isa<ConstantArrayType>(arrayType) &&
685 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
686 Align = std::max(Align, Target.getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000687
John McCall3b657512011-01-19 10:06:00 +0000688 // Walk through any array types while we're at it.
689 T = getBaseElementType(arrayType);
690 }
Chad Rosier9f1210c2011-07-26 07:03:04 +0000691 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedmandcdafb62009-02-22 02:56:25 +0000692 }
John McCallba4f5d52011-01-20 07:57:12 +0000693
694 // Fields can be subject to extra alignment constraints, like if
695 // the field is packed, the struct is packed, or the struct has a
696 // a max-field-alignment constraint (#pragma pack). So calculate
697 // the actual alignment of the field within the struct, and then
698 // (as we're expected to) constrain that by the alignment of the type.
699 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
700 // So calculate the alignment of the field.
701 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
702
703 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +0000704 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +0000705
706 // Use the GCD of that and the offset within the record.
707 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
708 if (offset > 0) {
709 // Alignment is always a power of 2, so the GCD will be a power of 2,
710 // which means we get to do this crazy thing instead of Euclid's.
711 uint64_t lowBitOfOffset = offset & (~offset + 1);
712 if (lowBitOfOffset < fieldAlign)
713 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
714 }
715
716 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +0000717 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000718 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000719
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000720 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +0000721}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000722
John McCallea1471e2010-05-20 01:18:31 +0000723std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000724ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +0000725 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000726 return std::make_pair(toCharUnitsFromBits(Info.first),
727 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +0000728}
729
730std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000731ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +0000732 return getTypeInfoInChars(T.getTypePtr());
733}
734
Chris Lattnera7674d82007-07-13 22:13:22 +0000735/// getTypeSize - Return the size of the specified type, in bits. This method
736/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000737///
738/// FIXME: Pointers into different addr spaces could have different sizes and
739/// alignment requirements: getPointerInfo should take an AddrSpace, this
740/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000741std::pair<uint64_t, unsigned>
Jay Foad4ba2a172011-01-12 09:06:06 +0000742ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +0000743 uint64_t Width=0;
744 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000745 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000746#define TYPE(Class, Base)
747#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000748#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000749#define DEPENDENT_TYPE(Class, Base) case Type::Class:
750#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +0000751 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000752 break;
753
Chris Lattner692233e2007-07-13 22:27:08 +0000754 case Type::FunctionNoProto:
755 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000756 // GCC extension: alignof(function) = 32 bits
757 Width = 0;
758 Align = 32;
759 break;
760
Douglas Gregor72564e72009-02-26 23:50:07 +0000761 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000762 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000763 Width = 0;
764 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
765 break;
766
Steve Narofffb22d962007-08-30 01:06:46 +0000767 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000768 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000769
Chris Lattner98be4942008-03-05 18:54:05 +0000770 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000771 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000772 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +0000773 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000774 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000775 }
Nate Begeman213541a2008-04-18 23:10:10 +0000776 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000777 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000778 const VectorType *VT = cast<VectorType>(T);
779 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
780 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000781 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000782 // If the alignment is not a power of 2, round up to the next power of 2.
783 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000784 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000785 Align = llvm::NextPowerOf2(Align);
786 Width = llvm::RoundUpToAlignment(Width, Align);
787 }
Chris Lattner030d8842007-07-19 22:06:24 +0000788 break;
789 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000790
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000791 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000792 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000793 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000794 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000795 // GCC extension: alignof(void) = 8 bits.
796 Width = 0;
797 Align = 8;
798 break;
799
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000800 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000801 Width = Target.getBoolWidth();
802 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000803 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000804 case BuiltinType::Char_S:
805 case BuiltinType::Char_U:
806 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000807 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000808 Width = Target.getCharWidth();
809 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000810 break;
Chris Lattner3f59c972010-12-25 23:25:43 +0000811 case BuiltinType::WChar_S:
812 case BuiltinType::WChar_U:
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000813 Width = Target.getWCharWidth();
814 Align = Target.getWCharAlign();
815 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000816 case BuiltinType::Char16:
817 Width = Target.getChar16Width();
818 Align = Target.getChar16Align();
819 break;
820 case BuiltinType::Char32:
821 Width = Target.getChar32Width();
822 Align = Target.getChar32Align();
823 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000824 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000825 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000826 Width = Target.getShortWidth();
827 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000828 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000829 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000830 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000831 Width = Target.getIntWidth();
832 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000833 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000834 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000835 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000836 Width = Target.getLongWidth();
837 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000838 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000839 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000840 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000841 Width = Target.getLongLongWidth();
842 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000843 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000844 case BuiltinType::Int128:
845 case BuiltinType::UInt128:
846 Width = 128;
847 Align = 128; // int128_t is 128-bit aligned on all targets.
848 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000849 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000850 Width = Target.getFloatWidth();
851 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000852 break;
853 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000854 Width = Target.getDoubleWidth();
855 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000856 break;
857 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000858 Width = Target.getLongDoubleWidth();
859 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000860 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000861 case BuiltinType::NullPtr:
862 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
863 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000864 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000865 case BuiltinType::ObjCId:
866 case BuiltinType::ObjCClass:
867 case BuiltinType::ObjCSel:
868 Width = Target.getPointerWidth(0);
869 Align = Target.getPointerAlign(0);
870 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000871 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000872 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000873 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000874 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000875 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000876 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000877 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000878 unsigned AS = getTargetAddressSpace(
879 cast<BlockPointerType>(T)->getPointeeType());
Steve Naroff485eeff2008-09-24 15:05:44 +0000880 Width = Target.getPointerWidth(AS);
881 Align = Target.getPointerAlign(AS);
882 break;
883 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000884 case Type::LValueReference:
885 case Type::RValueReference: {
886 // alignof and sizeof should never enter this code path here, so we go
887 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000888 unsigned AS = getTargetAddressSpace(
889 cast<ReferenceType>(T)->getPointeeType());
Sebastian Redl5d484e82009-11-23 17:18:46 +0000890 Width = Target.getPointerWidth(AS);
891 Align = Target.getPointerAlign(AS);
892 break;
893 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000894 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000895 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Chris Lattner5426bf62008-04-07 07:01:58 +0000896 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000897 Align = Target.getPointerAlign(AS);
898 break;
899 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000900 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +0000901 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000902 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000903 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +0000904 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000905 Align = PtrDiffInfo.second;
906 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000907 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000908 case Type::Complex: {
909 // Complex types have the same alignment as their elements, but twice the
910 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000911 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000912 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000913 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000914 Align = EltInfo.second;
915 break;
916 }
John McCallc12c5bb2010-05-15 11:32:37 +0000917 case Type::ObjCObject:
918 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000919 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000920 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000921 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +0000922 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +0000923 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +0000924 break;
925 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000926 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000927 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000928 const TagType *TT = cast<TagType>(T);
929
930 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +0000931 Width = 8;
932 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +0000933 break;
934 }
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Daniel Dunbar1d751182008-11-08 05:48:37 +0000936 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000937 return getTypeInfo(ET->getDecl()->getIntegerType());
938
Daniel Dunbar1d751182008-11-08 05:48:37 +0000939 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000940 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +0000941 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +0000942 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000943 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000944 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000945
Chris Lattner9fcfe922009-10-22 05:17:15 +0000946 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000947 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
948 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000949
Richard Smith34b41d92011-02-20 03:19:35 +0000950 case Type::Auto: {
951 const AutoType *A = cast<AutoType>(T);
952 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +0000953 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +0000954 }
955
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000956 case Type::Paren:
957 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
958
Douglas Gregor18857642009-04-30 17:32:17 +0000959 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +0000960 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +0000961 std::pair<uint64_t, unsigned> Info
962 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +0000963 // If the typedef has an aligned attribute on it, it overrides any computed
964 // alignment we have. This violates the GCC documentation (which says that
965 // attribute(aligned) can only round up) but matches its implementation.
966 if (unsigned AttrAlign = Typedef->getMaxAlignment())
967 Align = AttrAlign;
968 else
969 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +0000970 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +0000971 break;
Chris Lattner71763312008-04-06 22:05:18 +0000972 }
Douglas Gregor18857642009-04-30 17:32:17 +0000973
974 case Type::TypeOfExpr:
975 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
976 .getTypePtr());
977
978 case Type::TypeOf:
979 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
980
Anders Carlsson395b4752009-06-24 19:06:50 +0000981 case Type::Decltype:
982 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
983 .getTypePtr());
984
Sean Huntca63c202011-05-24 22:41:36 +0000985 case Type::UnaryTransform:
986 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
987
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000988 case Type::Elaborated:
989 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000990
John McCall9d156a72011-01-06 01:58:22 +0000991 case Type::Attributed:
992 return getTypeInfo(
993 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
994
Richard Smith3e4c6c42011-05-05 21:57:07 +0000995 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +0000996 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000997 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +0000998 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
999 // A type alias template specialization may refer to a typedef with the
1000 // aligned attribute on it.
1001 if (TST->isTypeAlias())
1002 return getTypeInfo(TST->getAliasedType().getTypePtr());
1003 else
1004 return getTypeInfo(getCanonicalType(T));
1005 }
1006
Douglas Gregor18857642009-04-30 17:32:17 +00001007 }
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Chris Lattner464175b2007-07-18 17:52:12 +00001009 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001010 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001011}
1012
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001013/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1014CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1015 return CharUnits::fromQuantity(BitSize / getCharWidth());
1016}
1017
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001018/// toBits - Convert a size in characters to a size in characters.
1019int64_t ASTContext::toBits(CharUnits CharSize) const {
1020 return CharSize.getQuantity() * getCharWidth();
1021}
1022
Ken Dyckbdc601b2009-12-22 14:23:30 +00001023/// getTypeSizeInChars - Return the size of the specified type, in characters.
1024/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001025CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001026 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001027}
Jay Foad4ba2a172011-01-12 09:06:06 +00001028CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001029 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001030}
1031
Ken Dyck16e20cc2010-01-26 17:25:18 +00001032/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001033/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001034CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001035 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001036}
Jay Foad4ba2a172011-01-12 09:06:06 +00001037CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001038 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001039}
1040
Chris Lattner34ebde42009-01-27 18:08:34 +00001041/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1042/// type for the current target in bits. This can be different than the ABI
1043/// alignment in cases where it is beneficial for performance to overalign
1044/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001045unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001046 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001047
1048 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001049 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001050 T = CT->getElementType().getTypePtr();
1051 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1052 T->isSpecificBuiltinType(BuiltinType::LongLong))
1053 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1054
Chris Lattner34ebde42009-01-27 18:08:34 +00001055 return ABIAlign;
1056}
1057
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001058/// DeepCollectObjCIvars -
1059/// This routine first collects all declared, but not synthesized, ivars in
1060/// super class and then collects all ivars, including those synthesized for
1061/// current class. This routine is used for implementation of current class
1062/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001063///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001064void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1065 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001066 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001067 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1068 DeepCollectObjCIvars(SuperClass, false, Ivars);
1069 if (!leafClass) {
1070 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1071 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanian11062e12010-02-19 00:31:17 +00001072 Ivars.push_back(*I);
1073 }
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001074 else {
1075 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001076 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001077 Iv= Iv->getNextIvar())
1078 Ivars.push_back(Iv);
1079 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001080}
1081
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001082/// CollectInheritedProtocols - Collect all protocols in current class and
1083/// those inherited by it.
1084void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001085 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001086 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001087 // We can use protocol_iterator here instead of
1088 // all_referenced_protocol_iterator since we are walking all categories.
1089 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1090 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001091 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001092 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001093 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001094 PE = Proto->protocol_end(); P != PE; ++P) {
1095 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001096 CollectInheritedProtocols(*P, Protocols);
1097 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001098 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001099
1100 // Categories of this Interface.
1101 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1102 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1103 CollectInheritedProtocols(CDeclChain, Protocols);
1104 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1105 while (SD) {
1106 CollectInheritedProtocols(SD, Protocols);
1107 SD = SD->getSuperClass();
1108 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001109 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001110 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001111 PE = OC->protocol_end(); P != PE; ++P) {
1112 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001113 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001114 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1115 PE = Proto->protocol_end(); P != PE; ++P)
1116 CollectInheritedProtocols(*P, Protocols);
1117 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001118 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001119 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1120 PE = OP->protocol_end(); P != PE; ++P) {
1121 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001122 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001123 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1124 PE = Proto->protocol_end(); P != PE; ++P)
1125 CollectInheritedProtocols(*P, Protocols);
1126 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001127 }
1128}
1129
Jay Foad4ba2a172011-01-12 09:06:06 +00001130unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001131 unsigned count = 0;
1132 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001133 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1134 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001135 count += CDecl->ivar_size();
1136
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001137 // Count ivar defined in this class's implementation. This
1138 // includes synthesized ivars.
1139 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001140 count += ImplDecl->ivar_size();
1141
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001142 return count;
1143}
1144
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001145/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1146ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1147 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1148 I = ObjCImpls.find(D);
1149 if (I != ObjCImpls.end())
1150 return cast<ObjCImplementationDecl>(I->second);
1151 return 0;
1152}
1153/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1154ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1155 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1156 I = ObjCImpls.find(D);
1157 if (I != ObjCImpls.end())
1158 return cast<ObjCCategoryImplDecl>(I->second);
1159 return 0;
1160}
1161
1162/// \brief Set the implementation of ObjCInterfaceDecl.
1163void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1164 ObjCImplementationDecl *ImplD) {
1165 assert(IFaceD && ImplD && "Passed null params");
1166 ObjCImpls[IFaceD] = ImplD;
1167}
1168/// \brief Set the implementation of ObjCCategoryDecl.
1169void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1170 ObjCCategoryImplDecl *ImplD) {
1171 assert(CatD && ImplD && "Passed null params");
1172 ObjCImpls[CatD] = ImplD;
1173}
1174
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001175/// \brief Get the copy initialization expression of VarDecl,or NULL if
1176/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001177Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001178 assert(VD && "Passed null params");
1179 assert(VD->hasAttr<BlocksAttr>() &&
1180 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001181 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001182 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001183 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1184}
1185
1186/// \brief Set the copy inialization expression of a block var decl.
1187void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1188 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001189 assert(VD->hasAttr<BlocksAttr>() &&
1190 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001191 BlockVarCopyInits[VD] = Init;
1192}
1193
John McCalla93c9342009-12-07 02:54:59 +00001194/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001195///
John McCalla93c9342009-12-07 02:54:59 +00001196/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001197/// the TypeLoc wrappers.
1198///
1199/// \param T the type that will be the basis for type source info. This type
1200/// should refer to how the declarator was written in source code, not to
1201/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001202TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001203 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001204 if (!DataSize)
1205 DataSize = TypeLoc::getFullDataSizeForType(T);
1206 else
1207 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001208 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001209
John McCalla93c9342009-12-07 02:54:59 +00001210 TypeSourceInfo *TInfo =
1211 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1212 new (TInfo) TypeSourceInfo(T);
1213 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001214}
1215
John McCalla93c9342009-12-07 02:54:59 +00001216TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001217 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001218 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001219 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001220 return DI;
1221}
1222
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001223const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001224ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001225 return getObjCLayout(D, 0);
1226}
1227
1228const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001229ASTContext::getASTObjCImplementationLayout(
1230 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001231 return getObjCLayout(D->getClassInterface(), D);
1232}
1233
Chris Lattnera7674d82007-07-13 22:13:22 +00001234//===----------------------------------------------------------------------===//
1235// Type creation/memoization methods
1236//===----------------------------------------------------------------------===//
1237
Jay Foad4ba2a172011-01-12 09:06:06 +00001238QualType
John McCall3b657512011-01-19 10:06:00 +00001239ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1240 unsigned fastQuals = quals.getFastQualifiers();
1241 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001242
1243 // Check if we've already instantiated this type.
1244 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001245 ExtQuals::Profile(ID, baseType, quals);
1246 void *insertPos = 0;
1247 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1248 assert(eq->getQualifiers() == quals);
1249 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001250 }
1251
John McCall3b657512011-01-19 10:06:00 +00001252 // If the base type is not canonical, make the appropriate canonical type.
1253 QualType canon;
1254 if (!baseType->isCanonicalUnqualified()) {
1255 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1256 canonSplit.second.addConsistentQualifiers(quals);
1257 canon = getExtQualType(canonSplit.first, canonSplit.second);
1258
1259 // Re-find the insert position.
1260 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1261 }
1262
1263 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1264 ExtQualNodes.InsertNode(eq, insertPos);
1265 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001266}
1267
Jay Foad4ba2a172011-01-12 09:06:06 +00001268QualType
1269ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001270 QualType CanT = getCanonicalType(T);
1271 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001272 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001273
John McCall0953e762009-09-24 19:53:00 +00001274 // If we are composing extended qualifiers together, merge together
1275 // into one ExtQuals node.
1276 QualifierCollector Quals;
1277 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001278
John McCall0953e762009-09-24 19:53:00 +00001279 // If this type already has an address space specified, it cannot get
1280 // another one.
1281 assert(!Quals.hasAddressSpace() &&
1282 "Type cannot be in multiple addr spaces!");
1283 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001284
John McCall0953e762009-09-24 19:53:00 +00001285 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001286}
1287
Chris Lattnerb7d25532009-02-18 22:53:11 +00001288QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001289 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001290 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001291 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001292 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001293
John McCall7f040a92010-12-24 02:08:15 +00001294 if (const PointerType *ptr = T->getAs<PointerType>()) {
1295 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001296 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001297 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1298 return getPointerType(ResultType);
1299 }
1300 }
Mike Stump1eb44332009-09-09 15:08:12 +00001301
John McCall0953e762009-09-24 19:53:00 +00001302 // If we are composing extended qualifiers together, merge together
1303 // into one ExtQuals node.
1304 QualifierCollector Quals;
1305 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001306
John McCall0953e762009-09-24 19:53:00 +00001307 // If this type already has an ObjCGC specified, it cannot get
1308 // another one.
1309 assert(!Quals.hasObjCGCAttr() &&
1310 "Type cannot have multiple ObjCGCs!");
1311 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001312
John McCall0953e762009-09-24 19:53:00 +00001313 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001314}
Chris Lattnera7674d82007-07-13 22:13:22 +00001315
John McCalle6a365d2010-12-19 02:44:49 +00001316const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1317 FunctionType::ExtInfo Info) {
1318 if (T->getExtInfo() == Info)
1319 return T;
1320
1321 QualType Result;
1322 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1323 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1324 } else {
1325 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1326 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1327 EPI.ExtInfo = Info;
1328 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1329 FPT->getNumArgs(), EPI);
1330 }
1331
1332 return cast<FunctionType>(Result.getTypePtr());
1333}
1334
Reid Spencer5f016e22007-07-11 17:01:13 +00001335/// getComplexType - Return the uniqued reference to the type for a complex
1336/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001337QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001338 // Unique pointers, to guarantee there is only one pointer of a particular
1339 // structure.
1340 llvm::FoldingSetNodeID ID;
1341 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001342
Reid Spencer5f016e22007-07-11 17:01:13 +00001343 void *InsertPos = 0;
1344 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1345 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001346
Reid Spencer5f016e22007-07-11 17:01:13 +00001347 // If the pointee type isn't canonical, this won't be a canonical type either,
1348 // so fill in the canonical type field.
1349 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001350 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001351 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001352
Reid Spencer5f016e22007-07-11 17:01:13 +00001353 // Get the new insert position for the node we care about.
1354 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001355 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001356 }
John McCall6b304a02009-09-24 23:30:46 +00001357 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001358 Types.push_back(New);
1359 ComplexTypes.InsertNode(New, InsertPos);
1360 return QualType(New, 0);
1361}
1362
Reid Spencer5f016e22007-07-11 17:01:13 +00001363/// getPointerType - Return the uniqued reference to the type for a pointer to
1364/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001365QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001366 // Unique pointers, to guarantee there is only one pointer of a particular
1367 // structure.
1368 llvm::FoldingSetNodeID ID;
1369 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001370
Reid Spencer5f016e22007-07-11 17:01:13 +00001371 void *InsertPos = 0;
1372 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1373 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001374
Reid Spencer5f016e22007-07-11 17:01:13 +00001375 // If the pointee type isn't canonical, this won't be a canonical type either,
1376 // so fill in the canonical type field.
1377 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001378 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001379 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001380
Reid Spencer5f016e22007-07-11 17:01:13 +00001381 // Get the new insert position for the node we care about.
1382 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001383 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001384 }
John McCall6b304a02009-09-24 23:30:46 +00001385 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001386 Types.push_back(New);
1387 PointerTypes.InsertNode(New, InsertPos);
1388 return QualType(New, 0);
1389}
1390
Mike Stump1eb44332009-09-09 15:08:12 +00001391/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001392/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001393QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001394 assert(T->isFunctionType() && "block of function types only");
1395 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001396 // structure.
1397 llvm::FoldingSetNodeID ID;
1398 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001399
Steve Naroff5618bd42008-08-27 16:04:49 +00001400 void *InsertPos = 0;
1401 if (BlockPointerType *PT =
1402 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1403 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001404
1405 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001406 // type either so fill in the canonical type field.
1407 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001408 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001409 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001410
Steve Naroff5618bd42008-08-27 16:04:49 +00001411 // Get the new insert position for the node we care about.
1412 BlockPointerType *NewIP =
1413 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001414 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001415 }
John McCall6b304a02009-09-24 23:30:46 +00001416 BlockPointerType *New
1417 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001418 Types.push_back(New);
1419 BlockPointerTypes.InsertNode(New, InsertPos);
1420 return QualType(New, 0);
1421}
1422
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001423/// getLValueReferenceType - Return the uniqued reference to the type for an
1424/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001425QualType
1426ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00001427 assert(getCanonicalType(T) != OverloadTy &&
1428 "Unresolved overloaded function type");
1429
Reid Spencer5f016e22007-07-11 17:01:13 +00001430 // Unique pointers, to guarantee there is only one pointer of a particular
1431 // structure.
1432 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001433 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001434
1435 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001436 if (LValueReferenceType *RT =
1437 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001438 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001439
John McCall54e14c42009-10-22 22:37:11 +00001440 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1441
Reid Spencer5f016e22007-07-11 17:01:13 +00001442 // If the referencee type isn't canonical, this won't be a canonical type
1443 // either, so fill in the canonical type field.
1444 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001445 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1446 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1447 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001448
Reid Spencer5f016e22007-07-11 17:01:13 +00001449 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001450 LValueReferenceType *NewIP =
1451 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001452 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001453 }
1454
John McCall6b304a02009-09-24 23:30:46 +00001455 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001456 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1457 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001458 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001459 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001460
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001461 return QualType(New, 0);
1462}
1463
1464/// getRValueReferenceType - Return the uniqued reference to the type for an
1465/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001466QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001467 // Unique pointers, to guarantee there is only one pointer of a particular
1468 // structure.
1469 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001470 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001471
1472 void *InsertPos = 0;
1473 if (RValueReferenceType *RT =
1474 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1475 return QualType(RT, 0);
1476
John McCall54e14c42009-10-22 22:37:11 +00001477 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1478
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001479 // If the referencee type isn't canonical, this won't be a canonical type
1480 // either, so fill in the canonical type field.
1481 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001482 if (InnerRef || !T.isCanonical()) {
1483 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1484 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001485
1486 // Get the new insert position for the node we care about.
1487 RValueReferenceType *NewIP =
1488 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001489 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001490 }
1491
John McCall6b304a02009-09-24 23:30:46 +00001492 RValueReferenceType *New
1493 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001494 Types.push_back(New);
1495 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001496 return QualType(New, 0);
1497}
1498
Sebastian Redlf30208a2009-01-24 21:16:55 +00001499/// getMemberPointerType - Return the uniqued reference to the type for a
1500/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00001501QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001502 // Unique pointers, to guarantee there is only one pointer of a particular
1503 // structure.
1504 llvm::FoldingSetNodeID ID;
1505 MemberPointerType::Profile(ID, T, Cls);
1506
1507 void *InsertPos = 0;
1508 if (MemberPointerType *PT =
1509 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1510 return QualType(PT, 0);
1511
1512 // If the pointee or class type isn't canonical, this won't be a canonical
1513 // type either, so fill in the canonical type field.
1514 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001515 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001516 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1517
1518 // Get the new insert position for the node we care about.
1519 MemberPointerType *NewIP =
1520 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001521 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001522 }
John McCall6b304a02009-09-24 23:30:46 +00001523 MemberPointerType *New
1524 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001525 Types.push_back(New);
1526 MemberPointerTypes.InsertNode(New, InsertPos);
1527 return QualType(New, 0);
1528}
1529
Mike Stump1eb44332009-09-09 15:08:12 +00001530/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001531/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001532QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001533 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001534 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001535 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001536 assert((EltTy->isDependentType() ||
1537 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001538 "Constant array of VLAs is illegal!");
1539
Chris Lattner38aeec72009-05-13 04:12:56 +00001540 // Convert the array size into a canonical width matching the pointer size for
1541 // the target.
1542 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001543 ArySize =
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001544 ArySize.zextOrTrunc(Target.getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00001545
Reid Spencer5f016e22007-07-11 17:01:13 +00001546 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001547 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001548
Reid Spencer5f016e22007-07-11 17:01:13 +00001549 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001550 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001551 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001552 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001553
John McCall3b657512011-01-19 10:06:00 +00001554 // If the element type isn't canonical or has qualifiers, this won't
1555 // be a canonical type either, so fill in the canonical type field.
1556 QualType Canon;
1557 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1558 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1559 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001560 ASM, IndexTypeQuals);
John McCall3b657512011-01-19 10:06:00 +00001561 Canon = getQualifiedType(Canon, canonSplit.second);
1562
Reid Spencer5f016e22007-07-11 17:01:13 +00001563 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001564 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001565 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001566 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001567 }
Mike Stump1eb44332009-09-09 15:08:12 +00001568
John McCall6b304a02009-09-24 23:30:46 +00001569 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001570 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001571 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 Types.push_back(New);
1573 return QualType(New, 0);
1574}
1575
John McCallce889032011-01-18 08:40:38 +00001576/// getVariableArrayDecayedType - Turns the given type, which may be
1577/// variably-modified, into the corresponding type with all the known
1578/// sizes replaced with [*].
1579QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1580 // Vastly most common case.
1581 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001582
John McCallce889032011-01-18 08:40:38 +00001583 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001584
John McCallce889032011-01-18 08:40:38 +00001585 SplitQualType split = type.getSplitDesugaredType();
1586 const Type *ty = split.first;
1587 switch (ty->getTypeClass()) {
1588#define TYPE(Class, Base)
1589#define ABSTRACT_TYPE(Class, Base)
1590#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1591#include "clang/AST/TypeNodes.def"
1592 llvm_unreachable("didn't desugar past all non-canonical types?");
1593
1594 // These types should never be variably-modified.
1595 case Type::Builtin:
1596 case Type::Complex:
1597 case Type::Vector:
1598 case Type::ExtVector:
1599 case Type::DependentSizedExtVector:
1600 case Type::ObjCObject:
1601 case Type::ObjCInterface:
1602 case Type::ObjCObjectPointer:
1603 case Type::Record:
1604 case Type::Enum:
1605 case Type::UnresolvedUsing:
1606 case Type::TypeOfExpr:
1607 case Type::TypeOf:
1608 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00001609 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00001610 case Type::DependentName:
1611 case Type::InjectedClassName:
1612 case Type::TemplateSpecialization:
1613 case Type::DependentTemplateSpecialization:
1614 case Type::TemplateTypeParm:
1615 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00001616 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00001617 case Type::PackExpansion:
1618 llvm_unreachable("type should never be variably-modified");
1619
1620 // These types can be variably-modified but should never need to
1621 // further decay.
1622 case Type::FunctionNoProto:
1623 case Type::FunctionProto:
1624 case Type::BlockPointer:
1625 case Type::MemberPointer:
1626 return type;
1627
1628 // These types can be variably-modified. All these modifications
1629 // preserve structure except as noted by comments.
1630 // TODO: if we ever care about optimizing VLAs, there are no-op
1631 // optimizations available here.
1632 case Type::Pointer:
1633 result = getPointerType(getVariableArrayDecayedType(
1634 cast<PointerType>(ty)->getPointeeType()));
1635 break;
1636
1637 case Type::LValueReference: {
1638 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1639 result = getLValueReferenceType(
1640 getVariableArrayDecayedType(lv->getPointeeType()),
1641 lv->isSpelledAsLValue());
1642 break;
1643 }
1644
1645 case Type::RValueReference: {
1646 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1647 result = getRValueReferenceType(
1648 getVariableArrayDecayedType(lv->getPointeeType()));
1649 break;
1650 }
1651
1652 case Type::ConstantArray: {
1653 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1654 result = getConstantArrayType(
1655 getVariableArrayDecayedType(cat->getElementType()),
1656 cat->getSize(),
1657 cat->getSizeModifier(),
1658 cat->getIndexTypeCVRQualifiers());
1659 break;
1660 }
1661
1662 case Type::DependentSizedArray: {
1663 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1664 result = getDependentSizedArrayType(
1665 getVariableArrayDecayedType(dat->getElementType()),
1666 dat->getSizeExpr(),
1667 dat->getSizeModifier(),
1668 dat->getIndexTypeCVRQualifiers(),
1669 dat->getBracketsRange());
1670 break;
1671 }
1672
1673 // Turn incomplete types into [*] types.
1674 case Type::IncompleteArray: {
1675 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1676 result = getVariableArrayType(
1677 getVariableArrayDecayedType(iat->getElementType()),
1678 /*size*/ 0,
1679 ArrayType::Normal,
1680 iat->getIndexTypeCVRQualifiers(),
1681 SourceRange());
1682 break;
1683 }
1684
1685 // Turn VLA types into [*] types.
1686 case Type::VariableArray: {
1687 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1688 result = getVariableArrayType(
1689 getVariableArrayDecayedType(vat->getElementType()),
1690 /*size*/ 0,
1691 ArrayType::Star,
1692 vat->getIndexTypeCVRQualifiers(),
1693 vat->getBracketsRange());
1694 break;
1695 }
1696 }
1697
1698 // Apply the top-level qualifiers from the original.
1699 return getQualifiedType(result, split.second);
1700}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001701
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001702/// getVariableArrayType - Returns a non-unique reference to the type for a
1703/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001704QualType ASTContext::getVariableArrayType(QualType EltTy,
1705 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001706 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001707 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00001708 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001709 // Since we don't unique expressions, it isn't possible to unique VLA's
1710 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00001711 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00001712
John McCall3b657512011-01-19 10:06:00 +00001713 // Be sure to pull qualifiers off the element type.
1714 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1715 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1716 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001717 IndexTypeQuals, Brackets);
John McCall3b657512011-01-19 10:06:00 +00001718 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor715e9c82010-05-23 16:10:32 +00001719 }
1720
John McCall6b304a02009-09-24 23:30:46 +00001721 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001722 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001723
1724 VariableArrayTypes.push_back(New);
1725 Types.push_back(New);
1726 return QualType(New, 0);
1727}
1728
Douglas Gregor898574e2008-12-05 23:32:09 +00001729/// getDependentSizedArrayType - Returns a non-unique reference to
1730/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001731/// type.
John McCall3b657512011-01-19 10:06:00 +00001732QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1733 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00001734 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001735 unsigned elementTypeQuals,
1736 SourceRange brackets) const {
1737 assert((!numElements || numElements->isTypeDependent() ||
1738 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001739 "Size must be type- or value-dependent!");
1740
John McCall3b657512011-01-19 10:06:00 +00001741 // Dependently-sized array types that do not have a specified number
1742 // of elements will have their sizes deduced from a dependent
1743 // initializer. We do no canonicalization here at all, which is okay
1744 // because they can't be used in most locations.
1745 if (!numElements) {
1746 DependentSizedArrayType *newType
1747 = new (*this, TypeAlignment)
1748 DependentSizedArrayType(*this, elementType, QualType(),
1749 numElements, ASM, elementTypeQuals,
1750 brackets);
1751 Types.push_back(newType);
1752 return QualType(newType, 0);
1753 }
1754
1755 // Otherwise, we actually build a new type every time, but we
1756 // also build a canonical type.
1757
1758 SplitQualType canonElementType = getCanonicalType(elementType).split();
1759
1760 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001761 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001762 DependentSizedArrayType::Profile(ID, *this,
1763 QualType(canonElementType.first, 0),
1764 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001765
John McCall3b657512011-01-19 10:06:00 +00001766 // Look for an existing type with these properties.
1767 DependentSizedArrayType *canonTy =
1768 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001769
John McCall3b657512011-01-19 10:06:00 +00001770 // If we don't have one, build one.
1771 if (!canonTy) {
1772 canonTy = new (*this, TypeAlignment)
1773 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1774 QualType(), numElements, ASM, elementTypeQuals,
1775 brackets);
1776 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1777 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001778 }
1779
John McCall3b657512011-01-19 10:06:00 +00001780 // Apply qualifiers from the element type to the array.
1781 QualType canon = getQualifiedType(QualType(canonTy,0),
1782 canonElementType.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001783
John McCall3b657512011-01-19 10:06:00 +00001784 // If we didn't need extra canonicalization for the element type,
1785 // then just use that as our result.
1786 if (QualType(canonElementType.first, 0) == elementType)
1787 return canon;
1788
1789 // Otherwise, we need to build a type which follows the spelling
1790 // of the element type.
1791 DependentSizedArrayType *sugaredType
1792 = new (*this, TypeAlignment)
1793 DependentSizedArrayType(*this, elementType, canon, numElements,
1794 ASM, elementTypeQuals, brackets);
1795 Types.push_back(sugaredType);
1796 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00001797}
1798
John McCall3b657512011-01-19 10:06:00 +00001799QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00001800 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001801 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001802 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001803 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001804
John McCall3b657512011-01-19 10:06:00 +00001805 void *insertPos = 0;
1806 if (IncompleteArrayType *iat =
1807 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1808 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001809
1810 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00001811 // either, so fill in the canonical type field. We also have to pull
1812 // qualifiers off the element type.
1813 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00001814
John McCall3b657512011-01-19 10:06:00 +00001815 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1816 SplitQualType canonSplit = getCanonicalType(elementType).split();
1817 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1818 ASM, elementTypeQuals);
1819 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001820
1821 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00001822 IncompleteArrayType *existing =
1823 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1824 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001825 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001826
John McCall3b657512011-01-19 10:06:00 +00001827 IncompleteArrayType *newType = new (*this, TypeAlignment)
1828 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001829
John McCall3b657512011-01-19 10:06:00 +00001830 IncompleteArrayTypes.InsertNode(newType, insertPos);
1831 Types.push_back(newType);
1832 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001833}
1834
Steve Naroff73322922007-07-18 18:00:27 +00001835/// getVectorType - Return the unique reference to a vector type of
1836/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001837QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00001838 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00001839 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001840
Reid Spencer5f016e22007-07-11 17:01:13 +00001841 // Check if we've already instantiated a vector of this type.
1842 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00001843 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00001844
Reid Spencer5f016e22007-07-11 17:01:13 +00001845 void *InsertPos = 0;
1846 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1847 return QualType(VTP, 0);
1848
1849 // If the element type isn't canonical, this won't be a canonical type either,
1850 // so fill in the canonical type field.
1851 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00001852 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00001853 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00001854
Reid Spencer5f016e22007-07-11 17:01:13 +00001855 // Get the new insert position for the node we care about.
1856 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001857 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001858 }
John McCall6b304a02009-09-24 23:30:46 +00001859 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00001860 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001861 VectorTypes.InsertNode(New, InsertPos);
1862 Types.push_back(New);
1863 return QualType(New, 0);
1864}
1865
Nate Begeman213541a2008-04-18 23:10:10 +00001866/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001867/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001868QualType
1869ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00001870 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00001871
Steve Naroff73322922007-07-18 18:00:27 +00001872 // Check if we've already instantiated a vector of this type.
1873 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001874 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001875 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00001876 void *InsertPos = 0;
1877 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1878 return QualType(VTP, 0);
1879
1880 // If the element type isn't canonical, this won't be a canonical type either,
1881 // so fill in the canonical type field.
1882 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001883 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001884 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001885
Steve Naroff73322922007-07-18 18:00:27 +00001886 // Get the new insert position for the node we care about.
1887 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001888 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001889 }
John McCall6b304a02009-09-24 23:30:46 +00001890 ExtVectorType *New = new (*this, TypeAlignment)
1891 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001892 VectorTypes.InsertNode(New, InsertPos);
1893 Types.push_back(New);
1894 return QualType(New, 0);
1895}
1896
Jay Foad4ba2a172011-01-12 09:06:06 +00001897QualType
1898ASTContext::getDependentSizedExtVectorType(QualType vecType,
1899 Expr *SizeExpr,
1900 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001901 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001902 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001903 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001904
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001905 void *InsertPos = 0;
1906 DependentSizedExtVectorType *Canon
1907 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1908 DependentSizedExtVectorType *New;
1909 if (Canon) {
1910 // We already have a canonical version of this array type; use it as
1911 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001912 New = new (*this, TypeAlignment)
1913 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1914 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001915 } else {
1916 QualType CanonVecTy = getCanonicalType(vecType);
1917 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001918 New = new (*this, TypeAlignment)
1919 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1920 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001921
1922 DependentSizedExtVectorType *CanonCheck
1923 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1924 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1925 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001926 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1927 } else {
1928 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1929 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001930 New = new (*this, TypeAlignment)
1931 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001932 }
1933 }
Mike Stump1eb44332009-09-09 15:08:12 +00001934
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001935 Types.push_back(New);
1936 return QualType(New, 0);
1937}
1938
Douglas Gregor72564e72009-02-26 23:50:07 +00001939/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001940///
Jay Foad4ba2a172011-01-12 09:06:06 +00001941QualType
1942ASTContext::getFunctionNoProtoType(QualType ResultTy,
1943 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00001944 const CallingConv DefaultCC = Info.getCC();
1945 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1946 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00001947 // Unique functions, to guarantee there is only one function of a particular
1948 // structure.
1949 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00001950 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001951
Reid Spencer5f016e22007-07-11 17:01:13 +00001952 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001953 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001954 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001955 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001956
Reid Spencer5f016e22007-07-11 17:01:13 +00001957 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001958 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001959 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001960 Canonical =
1961 getFunctionNoProtoType(getCanonicalType(ResultTy),
1962 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00001963
Reid Spencer5f016e22007-07-11 17:01:13 +00001964 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001965 FunctionNoProtoType *NewIP =
1966 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001967 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001968 }
Mike Stump1eb44332009-09-09 15:08:12 +00001969
Roman Divackycfe9af22011-03-01 17:40:53 +00001970 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00001971 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00001972 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00001973 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001974 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001975 return QualType(New, 0);
1976}
1977
1978/// getFunctionType - Return a normal function type with a typed argument
1979/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00001980QualType
1981ASTContext::getFunctionType(QualType ResultTy,
1982 const QualType *ArgArray, unsigned NumArgs,
1983 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001984 // Unique functions, to guarantee there is only one function of a particular
1985 // structure.
1986 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001987 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00001988
1989 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001990 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001991 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001992 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001993
1994 // Determine whether the type being created is already canonical or not.
Sebastian Redl8b5b4092011-03-06 10:52:04 +00001995 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001996 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001997 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001998 isCanonical = false;
1999
Roman Divackycfe9af22011-03-01 17:40:53 +00002000 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2001 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2002 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002003
Reid Spencer5f016e22007-07-11 17:01:13 +00002004 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002005 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002006 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002007 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002008 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002009 CanonicalArgs.reserve(NumArgs);
2010 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002011 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002012
John McCalle23cf432010-12-14 08:05:40 +00002013 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002014 CanonicalEPI.ExceptionSpecType = EST_None;
2015 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002016 CanonicalEPI.ExtInfo
2017 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2018
Chris Lattnerf52ab252008-04-06 22:59:24 +00002019 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00002020 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002021 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002022
Reid Spencer5f016e22007-07-11 17:01:13 +00002023 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002024 FunctionProtoType *NewIP =
2025 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002026 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002027 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002028
John McCallf85e1932011-06-15 23:02:42 +00002029 // FunctionProtoType objects are allocated with extra bytes after
2030 // them for three variable size arrays at the end:
2031 // - parameter types
2032 // - exception types
2033 // - consumed-arguments flags
2034 // Instead of the exception types, there could be a noexcept
2035 // expression.
John McCalle23cf432010-12-14 08:05:40 +00002036 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002037 NumArgs * sizeof(QualType);
2038 if (EPI.ExceptionSpecType == EST_Dynamic)
2039 Size += EPI.NumExceptions * sizeof(QualType);
2040 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002041 Size += sizeof(Expr*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002042 }
John McCallf85e1932011-06-15 23:02:42 +00002043 if (EPI.ConsumedArguments)
2044 Size += NumArgs * sizeof(bool);
2045
John McCalle23cf432010-12-14 08:05:40 +00002046 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002047 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2048 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002049 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002050 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002051 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002052 return QualType(FTP, 0);
2053}
2054
John McCall3cb0ebd2010-03-10 03:28:59 +00002055#ifndef NDEBUG
2056static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2057 if (!isa<CXXRecordDecl>(D)) return false;
2058 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2059 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2060 return true;
2061 if (RD->getDescribedClassTemplate() &&
2062 !isa<ClassTemplateSpecializationDecl>(RD))
2063 return true;
2064 return false;
2065}
2066#endif
2067
2068/// getInjectedClassNameType - Return the unique reference to the
2069/// injected class name type for the specified templated declaration.
2070QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002071 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002072 assert(NeedsInjectedClassNameType(Decl));
2073 if (Decl->TypeForDecl) {
2074 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00002075 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002076 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2077 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2078 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2079 } else {
John McCallf4c73712011-01-19 06:33:43 +00002080 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002081 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002082 Decl->TypeForDecl = newType;
2083 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002084 }
2085 return QualType(Decl->TypeForDecl, 0);
2086}
2087
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002088/// getTypeDeclType - Return the unique reference to the type for the
2089/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002090QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002091 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002092 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002093
Richard Smith162e1c12011-04-15 14:24:37 +00002094 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002095 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002096
John McCallbecb8d52010-03-10 06:48:02 +00002097 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2098 "Template type parameter types are always available.");
2099
John McCall19c85762010-02-16 03:57:14 +00002100 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002101 assert(!Record->getPreviousDeclaration() &&
2102 "struct/union has previous declaration");
2103 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002104 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002105 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002106 assert(!Enum->getPreviousDeclaration() &&
2107 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002108 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002109 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002110 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002111 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2112 Decl->TypeForDecl = newType;
2113 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002114 } else
John McCallbecb8d52010-03-10 06:48:02 +00002115 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002116
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002117 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002118}
2119
Reid Spencer5f016e22007-07-11 17:01:13 +00002120/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002121/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002122QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002123ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2124 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002125 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002126
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002127 if (Canonical.isNull())
2128 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002129 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002130 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002131 Decl->TypeForDecl = newType;
2132 Types.push_back(newType);
2133 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002134}
2135
Jay Foad4ba2a172011-01-12 09:06:06 +00002136QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002137 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2138
2139 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2140 if (PrevDecl->TypeForDecl)
2141 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2142
John McCallf4c73712011-01-19 06:33:43 +00002143 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2144 Decl->TypeForDecl = newType;
2145 Types.push_back(newType);
2146 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002147}
2148
Jay Foad4ba2a172011-01-12 09:06:06 +00002149QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002150 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2151
2152 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2153 if (PrevDecl->TypeForDecl)
2154 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2155
John McCallf4c73712011-01-19 06:33:43 +00002156 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2157 Decl->TypeForDecl = newType;
2158 Types.push_back(newType);
2159 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002160}
2161
John McCall9d156a72011-01-06 01:58:22 +00002162QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2163 QualType modifiedType,
2164 QualType equivalentType) {
2165 llvm::FoldingSetNodeID id;
2166 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2167
2168 void *insertPos = 0;
2169 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2170 if (type) return QualType(type, 0);
2171
2172 QualType canon = getCanonicalType(equivalentType);
2173 type = new (*this, TypeAlignment)
2174 AttributedType(canon, attrKind, modifiedType, equivalentType);
2175
2176 Types.push_back(type);
2177 AttributedTypes.InsertNode(type, insertPos);
2178
2179 return QualType(type, 0);
2180}
2181
2182
John McCall49a832b2009-10-18 09:09:24 +00002183/// \brief Retrieve a substitution-result type.
2184QualType
2185ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002186 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002187 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002188 && "replacement types must always be canonical");
2189
2190 llvm::FoldingSetNodeID ID;
2191 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2192 void *InsertPos = 0;
2193 SubstTemplateTypeParmType *SubstParm
2194 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2195
2196 if (!SubstParm) {
2197 SubstParm = new (*this, TypeAlignment)
2198 SubstTemplateTypeParmType(Parm, Replacement);
2199 Types.push_back(SubstParm);
2200 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2201 }
2202
2203 return QualType(SubstParm, 0);
2204}
2205
Douglas Gregorc3069d62011-01-14 02:55:32 +00002206/// \brief Retrieve a
2207QualType ASTContext::getSubstTemplateTypeParmPackType(
2208 const TemplateTypeParmType *Parm,
2209 const TemplateArgument &ArgPack) {
2210#ifndef NDEBUG
2211 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2212 PEnd = ArgPack.pack_end();
2213 P != PEnd; ++P) {
2214 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2215 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2216 }
2217#endif
2218
2219 llvm::FoldingSetNodeID ID;
2220 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2221 void *InsertPos = 0;
2222 if (SubstTemplateTypeParmPackType *SubstParm
2223 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2224 return QualType(SubstParm, 0);
2225
2226 QualType Canon;
2227 if (!Parm->isCanonicalUnqualified()) {
2228 Canon = getCanonicalType(QualType(Parm, 0));
2229 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2230 ArgPack);
2231 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2232 }
2233
2234 SubstTemplateTypeParmPackType *SubstParm
2235 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2236 ArgPack);
2237 Types.push_back(SubstParm);
2238 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2239 return QualType(SubstParm, 0);
2240}
2241
Douglas Gregorfab9d672009-02-05 23:33:38 +00002242/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002243/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002244/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002245QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002246 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002247 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002248 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002249 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002250 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002251 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002252 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2253
2254 if (TypeParm)
2255 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002256
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002257 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002258 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002259 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002260
2261 TemplateTypeParmType *TypeCheck
2262 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2263 assert(!TypeCheck && "Template type parameter canonical type broken");
2264 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002265 } else
John McCall6b304a02009-09-24 23:30:46 +00002266 TypeParm = new (*this, TypeAlignment)
2267 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002268
2269 Types.push_back(TypeParm);
2270 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2271
2272 return QualType(TypeParm, 0);
2273}
2274
John McCall3cb0ebd2010-03-10 03:28:59 +00002275TypeSourceInfo *
2276ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2277 SourceLocation NameLoc,
2278 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002279 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002280 assert(!Name.getAsDependentTemplateName() &&
2281 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002282 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002283
2284 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2285 TemplateSpecializationTypeLoc TL
2286 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2287 TL.setTemplateNameLoc(NameLoc);
2288 TL.setLAngleLoc(Args.getLAngleLoc());
2289 TL.setRAngleLoc(Args.getRAngleLoc());
2290 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2291 TL.setArgLocInfo(i, Args[i].getLocInfo());
2292 return DI;
2293}
2294
Mike Stump1eb44332009-09-09 15:08:12 +00002295QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002296ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002297 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002298 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002299 assert(!Template.getAsDependentTemplateName() &&
2300 "No dependent template names here!");
2301
John McCalld5532b62009-11-23 01:53:49 +00002302 unsigned NumArgs = Args.size();
2303
Chris Lattner5f9e2722011-07-23 10:55:15 +00002304 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002305 ArgVec.reserve(NumArgs);
2306 for (unsigned i = 0; i != NumArgs; ++i)
2307 ArgVec.push_back(Args[i].getArgument());
2308
John McCall31f17ec2010-04-27 00:57:59 +00002309 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002310 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002311}
2312
2313QualType
2314ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002315 const TemplateArgument *Args,
2316 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002317 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002318 assert(!Template.getAsDependentTemplateName() &&
2319 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002320 // Look through qualified template names.
2321 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2322 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002323
Richard Smith3e4c6c42011-05-05 21:57:07 +00002324 bool isTypeAlias =
2325 Template.getAsTemplateDecl() &&
2326 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2327
2328 QualType CanonType;
2329 if (!Underlying.isNull())
2330 CanonType = getCanonicalType(Underlying);
2331 else {
2332 assert(!isTypeAlias &&
2333 "Underlying type for template alias must be computed by caller");
2334 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2335 NumArgs);
2336 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002337
Douglas Gregor1275ae02009-07-28 23:00:59 +00002338 // Allocate the (non-canonical) template specialization type, but don't
2339 // try to unique it: these types typically have location information that
2340 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002341 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2342 sizeof(TemplateArgument) * NumArgs +
2343 (isTypeAlias ? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00002344 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002345 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00002346 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00002347 Args, NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002348 CanonType,
2349 isTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00002350
Douglas Gregor55f6b142009-02-09 18:46:07 +00002351 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002352 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002353}
2354
Mike Stump1eb44332009-09-09 15:08:12 +00002355QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002356ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2357 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002358 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002359 assert(!Template.getAsDependentTemplateName() &&
2360 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002361 assert((!Template.getAsTemplateDecl() ||
2362 !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2363 "Underlying type for template alias must be computed by caller");
2364
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002365 // Look through qualified template names.
2366 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2367 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002368
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002369 // Build the canonical template specialization type.
2370 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002371 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002372 CanonArgs.reserve(NumArgs);
2373 for (unsigned I = 0; I != NumArgs; ++I)
2374 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2375
2376 // Determine whether this canonical template specialization type already
2377 // exists.
2378 llvm::FoldingSetNodeID ID;
2379 TemplateSpecializationType::Profile(ID, CanonTemplate,
2380 CanonArgs.data(), NumArgs, *this);
2381
2382 void *InsertPos = 0;
2383 TemplateSpecializationType *Spec
2384 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2385
2386 if (!Spec) {
2387 // Allocate a new canonical template specialization type.
2388 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2389 sizeof(TemplateArgument) * NumArgs),
2390 TypeAlignment);
2391 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2392 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002393 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002394 Types.push_back(Spec);
2395 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2396 }
2397
2398 assert(Spec->isDependentType() &&
2399 "Non-dependent template-id type must have a canonical type");
2400 return QualType(Spec, 0);
2401}
2402
2403QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002404ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2405 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002406 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002407 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002408 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002409
2410 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002411 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002412 if (T)
2413 return QualType(T, 0);
2414
Douglas Gregor789b1f62010-02-04 18:10:26 +00002415 QualType Canon = NamedType;
2416 if (!Canon.isCanonical()) {
2417 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002418 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2419 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002420 (void)CheckT;
2421 }
2422
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002423 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002424 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002425 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002426 return QualType(T, 0);
2427}
2428
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002429QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002430ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002431 llvm::FoldingSetNodeID ID;
2432 ParenType::Profile(ID, InnerType);
2433
2434 void *InsertPos = 0;
2435 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2436 if (T)
2437 return QualType(T, 0);
2438
2439 QualType Canon = InnerType;
2440 if (!Canon.isCanonical()) {
2441 Canon = getCanonicalType(InnerType);
2442 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2443 assert(!CheckT && "Paren canonical type broken");
2444 (void)CheckT;
2445 }
2446
2447 T = new (*this) ParenType(InnerType, Canon);
2448 Types.push_back(T);
2449 ParenTypes.InsertNode(T, InsertPos);
2450 return QualType(T, 0);
2451}
2452
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002453QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2454 NestedNameSpecifier *NNS,
2455 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002456 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002457 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2458
2459 if (Canon.isNull()) {
2460 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002461 ElaboratedTypeKeyword CanonKeyword = Keyword;
2462 if (Keyword == ETK_None)
2463 CanonKeyword = ETK_Typename;
2464
2465 if (CanonNNS != NNS || CanonKeyword != Keyword)
2466 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002467 }
2468
2469 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002470 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002471
2472 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002473 DependentNameType *T
2474 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002475 if (T)
2476 return QualType(T, 0);
2477
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002478 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002479 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002480 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002481 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002482}
2483
Mike Stump1eb44332009-09-09 15:08:12 +00002484QualType
John McCall33500952010-06-11 00:33:02 +00002485ASTContext::getDependentTemplateSpecializationType(
2486 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002487 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002488 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002489 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00002490 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00002491 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00002492 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2493 ArgCopy.push_back(Args[I].getArgument());
2494 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2495 ArgCopy.size(),
2496 ArgCopy.data());
2497}
2498
2499QualType
2500ASTContext::getDependentTemplateSpecializationType(
2501 ElaboratedTypeKeyword Keyword,
2502 NestedNameSpecifier *NNS,
2503 const IdentifierInfo *Name,
2504 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002505 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00002506 assert((!NNS || NNS->isDependent()) &&
2507 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00002508
Douglas Gregor789b1f62010-02-04 18:10:26 +00002509 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002510 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2511 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002512
2513 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002514 DependentTemplateSpecializationType *T
2515 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002516 if (T)
2517 return QualType(T, 0);
2518
John McCall33500952010-06-11 00:33:02 +00002519 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002520
John McCall33500952010-06-11 00:33:02 +00002521 ElaboratedTypeKeyword CanonKeyword = Keyword;
2522 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2523
2524 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002525 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00002526 for (unsigned I = 0; I != NumArgs; ++I) {
2527 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2528 if (!CanonArgs[I].structurallyEquals(Args[I]))
2529 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002530 }
2531
John McCall33500952010-06-11 00:33:02 +00002532 QualType Canon;
2533 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2534 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2535 Name, NumArgs,
2536 CanonArgs.data());
2537
2538 // Find the insert position again.
2539 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2540 }
2541
2542 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2543 sizeof(TemplateArgument) * NumArgs),
2544 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002545 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002546 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002547 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002548 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002549 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002550}
2551
Douglas Gregorcded4f62011-01-14 17:04:44 +00002552QualType ASTContext::getPackExpansionType(QualType Pattern,
2553 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00002554 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002555 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002556
2557 assert(Pattern->containsUnexpandedParameterPack() &&
2558 "Pack expansions must expand one or more parameter packs");
2559 void *InsertPos = 0;
2560 PackExpansionType *T
2561 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2562 if (T)
2563 return QualType(T, 0);
2564
2565 QualType Canon;
2566 if (!Pattern.isCanonical()) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002567 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002568
2569 // Find the insert position again.
2570 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2571 }
2572
Douglas Gregorcded4f62011-01-14 17:04:44 +00002573 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002574 Types.push_back(T);
2575 PackExpansionTypes.InsertNode(T, InsertPos);
2576 return QualType(T, 0);
2577}
2578
Chris Lattner88cb27a2008-04-07 04:56:42 +00002579/// CmpProtocolNames - Comparison predicate for sorting protocols
2580/// alphabetically.
2581static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2582 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002583 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002584}
2585
John McCallc12c5bb2010-05-15 11:32:37 +00002586static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002587 unsigned NumProtocols) {
2588 if (NumProtocols == 0) return true;
2589
2590 for (unsigned i = 1; i != NumProtocols; ++i)
2591 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2592 return false;
2593 return true;
2594}
2595
2596static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002597 unsigned &NumProtocols) {
2598 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002599
Chris Lattner88cb27a2008-04-07 04:56:42 +00002600 // Sort protocols, keyed by name.
2601 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2602
2603 // Remove duplicates.
2604 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2605 NumProtocols = ProtocolsEnd-Protocols;
2606}
2607
John McCallc12c5bb2010-05-15 11:32:37 +00002608QualType ASTContext::getObjCObjectType(QualType BaseType,
2609 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00002610 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002611 // If the base type is an interface and there aren't any protocols
2612 // to add, then the interface type will do just fine.
2613 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2614 return BaseType;
2615
2616 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002617 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002618 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002619 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002620 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2621 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002622
John McCallc12c5bb2010-05-15 11:32:37 +00002623 // Build the canonical type, which has the canonical base type and
2624 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002625 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002626 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2627 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2628 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002629 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00002630 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002631 unsigned UniqueCount = NumProtocols;
2632
John McCall54e14c42009-10-22 22:37:11 +00002633 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002634 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2635 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002636 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002637 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2638 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002639 }
2640
2641 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002642 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2643 }
2644
2645 unsigned Size = sizeof(ObjCObjectTypeImpl);
2646 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2647 void *Mem = Allocate(Size, TypeAlignment);
2648 ObjCObjectTypeImpl *T =
2649 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2650
2651 Types.push_back(T);
2652 ObjCObjectTypes.InsertNode(T, InsertPos);
2653 return QualType(T, 0);
2654}
2655
2656/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2657/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002658QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002659 llvm::FoldingSetNodeID ID;
2660 ObjCObjectPointerType::Profile(ID, ObjectT);
2661
2662 void *InsertPos = 0;
2663 if (ObjCObjectPointerType *QT =
2664 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2665 return QualType(QT, 0);
2666
2667 // Find the canonical object type.
2668 QualType Canonical;
2669 if (!ObjectT.isCanonical()) {
2670 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2671
2672 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002673 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2674 }
2675
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002676 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002677 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2678 ObjCObjectPointerType *QType =
2679 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002680
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002681 Types.push_back(QType);
2682 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002683 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002684}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002685
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002686/// getObjCInterfaceType - Return the unique reference to the type for the
2687/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad4ba2a172011-01-12 09:06:06 +00002688QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002689 if (Decl->TypeForDecl)
2690 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002691
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002692 // FIXME: redeclarations?
2693 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2694 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2695 Decl->TypeForDecl = T;
2696 Types.push_back(T);
2697 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002698}
2699
Douglas Gregor72564e72009-02-26 23:50:07 +00002700/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2701/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002702/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002703/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002704/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002705QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002706 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002707 if (tofExpr->isTypeDependent()) {
2708 llvm::FoldingSetNodeID ID;
2709 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002710
Douglas Gregorb1975722009-07-30 23:18:24 +00002711 void *InsertPos = 0;
2712 DependentTypeOfExprType *Canon
2713 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2714 if (Canon) {
2715 // We already have a "canonical" version of an identical, dependent
2716 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002717 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002718 QualType((TypeOfExprType*)Canon, 0));
2719 }
2720 else {
2721 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002722 Canon
2723 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002724 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2725 toe = Canon;
2726 }
2727 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002728 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002729 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002730 }
Steve Naroff9752f252007-08-01 18:02:17 +00002731 Types.push_back(toe);
2732 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002733}
2734
Steve Naroff9752f252007-08-01 18:02:17 +00002735/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2736/// TypeOfType AST's. The only motivation to unique these nodes would be
2737/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002738/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002739/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002740QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002741 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002742 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002743 Types.push_back(tot);
2744 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002745}
2746
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002747/// getDecltypeForExpr - Given an expr, will return the decltype for that
2748/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad4ba2a172011-01-12 09:06:06 +00002749static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002750 if (e->isTypeDependent())
2751 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002752
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002753 // If e is an id expression or a class member access, decltype(e) is defined
2754 // as the type of the entity named by e.
2755 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2756 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2757 return VD->getType();
2758 }
2759 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2760 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2761 return FD->getType();
2762 }
2763 // If e is a function call or an invocation of an overloaded operator,
2764 // (parentheses around e are ignored), decltype(e) is defined as the
2765 // return type of that function.
2766 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2767 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002768
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002769 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002770
2771 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002772 // defined as T&, otherwise decltype(e) is defined as T.
John McCall7eb0a9e2010-11-24 05:12:34 +00002773 if (e->isLValue())
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002774 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002775
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002776 return T;
2777}
2778
Anders Carlsson395b4752009-06-24 19:06:50 +00002779/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2780/// DecltypeType AST's. The only motivation to unique these nodes would be
2781/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002782/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002783/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002784QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002785 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00002786
2787 // C++0x [temp.type]p2:
2788 // If an expression e involves a template parameter, decltype(e) denotes a
2789 // unique dependent type. Two such decltype-specifiers refer to the same
2790 // type only if their expressions are equivalent (14.5.6.1).
2791 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002792 llvm::FoldingSetNodeID ID;
2793 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002794
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002795 void *InsertPos = 0;
2796 DependentDecltypeType *Canon
2797 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2798 if (Canon) {
2799 // We already have a "canonical" version of an equivalent, dependent
2800 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002801 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002802 QualType((DecltypeType*)Canon, 0));
2803 }
2804 else {
2805 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002806 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002807 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2808 dt = Canon;
2809 }
2810 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002811 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002812 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002813 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002814 Types.push_back(dt);
2815 return QualType(dt, 0);
2816}
2817
Sean Huntca63c202011-05-24 22:41:36 +00002818/// getUnaryTransformationType - We don't unique these, since the memory
2819/// savings are minimal and these are rare.
2820QualType ASTContext::getUnaryTransformType(QualType BaseType,
2821 QualType UnderlyingType,
2822 UnaryTransformType::UTTKind Kind)
2823 const {
2824 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00002825 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2826 Kind,
2827 UnderlyingType->isDependentType() ?
2828 QualType() : UnderlyingType);
Sean Huntca63c202011-05-24 22:41:36 +00002829 Types.push_back(Ty);
2830 return QualType(Ty, 0);
2831}
2832
Richard Smith483b9f32011-02-21 20:05:19 +00002833/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00002834QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00002835 void *InsertPos = 0;
2836 if (!DeducedType.isNull()) {
2837 // Look in the folding set for an existing type.
2838 llvm::FoldingSetNodeID ID;
2839 AutoType::Profile(ID, DeducedType);
2840 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2841 return QualType(AT, 0);
2842 }
2843
2844 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2845 Types.push_back(AT);
2846 if (InsertPos)
2847 AutoTypes.InsertNode(AT, InsertPos);
2848 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00002849}
2850
Richard Smithad762fc2011-04-14 22:09:26 +00002851/// getAutoDeductType - Get type pattern for deducing against 'auto'.
2852QualType ASTContext::getAutoDeductType() const {
2853 if (AutoDeductTy.isNull())
2854 AutoDeductTy = getAutoType(QualType());
2855 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
2856 return AutoDeductTy;
2857}
2858
2859/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
2860QualType ASTContext::getAutoRRefDeductType() const {
2861 if (AutoRRefDeductTy.isNull())
2862 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
2863 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
2864 return AutoRRefDeductTy;
2865}
2866
Reid Spencer5f016e22007-07-11 17:01:13 +00002867/// getTagDeclType - Return the unique reference to the type for the
2868/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00002869QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00002870 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002871 // FIXME: What is the design on getTagDeclType when it requires casting
2872 // away const? mutable?
2873 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002874}
2875
Mike Stump1eb44332009-09-09 15:08:12 +00002876/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2877/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2878/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002879CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002880 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002881}
2882
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002883/// getSignedWCharType - Return the type of "signed wchar_t".
2884/// Used when in C++, as a GCC extension.
2885QualType ASTContext::getSignedWCharType() const {
2886 // FIXME: derive from "Target" ?
2887 return WCharTy;
2888}
2889
2890/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2891/// Used when in C++, as a GCC extension.
2892QualType ASTContext::getUnsignedWCharType() const {
2893 // FIXME: derive from "Target" ?
2894 return UnsignedIntTy;
2895}
2896
Chris Lattner8b9023b2007-07-13 03:05:23 +00002897/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2898/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2899QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002900 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002901}
2902
Chris Lattnere6327742008-04-02 05:18:44 +00002903//===----------------------------------------------------------------------===//
2904// Type Operators
2905//===----------------------------------------------------------------------===//
2906
Jay Foad4ba2a172011-01-12 09:06:06 +00002907CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00002908 // Push qualifiers into arrays, and then discard any remaining
2909 // qualifiers.
2910 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002911 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00002912 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00002913 QualType Result;
2914 if (isa<ArrayType>(Ty)) {
2915 Result = getArrayDecayedType(QualType(Ty,0));
2916 } else if (isa<FunctionType>(Ty)) {
2917 Result = getPointerType(QualType(Ty, 0));
2918 } else {
2919 Result = QualType(Ty, 0);
2920 }
2921
2922 return CanQualType::CreateUnsafe(Result);
2923}
2924
John McCall62c28c82011-01-18 07:41:22 +00002925QualType ASTContext::getUnqualifiedArrayType(QualType type,
2926 Qualifiers &quals) {
2927 SplitQualType splitType = type.getSplitUnqualifiedType();
2928
2929 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2930 // the unqualified desugared type and then drops it on the floor.
2931 // We then have to strip that sugar back off with
2932 // getUnqualifiedDesugaredType(), which is silly.
2933 const ArrayType *AT =
2934 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2935
2936 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00002937 if (!AT) {
John McCall62c28c82011-01-18 07:41:22 +00002938 quals = splitType.second;
2939 return QualType(splitType.first, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002940 }
2941
John McCall62c28c82011-01-18 07:41:22 +00002942 // Otherwise, recurse on the array's element type.
2943 QualType elementType = AT->getElementType();
2944 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2945
2946 // If that didn't change the element type, AT has no qualifiers, so we
2947 // can just use the results in splitType.
2948 if (elementType == unqualElementType) {
2949 assert(quals.empty()); // from the recursive call
2950 quals = splitType.second;
2951 return QualType(splitType.first, 0);
2952 }
2953
2954 // Otherwise, add in the qualifiers from the outermost type, then
2955 // build the type back up.
2956 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002957
Douglas Gregor9dadd942010-05-17 18:45:21 +00002958 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002959 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00002960 CAT->getSizeModifier(), 0);
2961 }
2962
Douglas Gregor9dadd942010-05-17 18:45:21 +00002963 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002964 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002965 }
2966
Douglas Gregor9dadd942010-05-17 18:45:21 +00002967 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002968 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00002969 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00002970 VAT->getSizeModifier(),
2971 VAT->getIndexTypeCVRQualifiers(),
2972 VAT->getBracketsRange());
2973 }
2974
2975 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00002976 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00002977 DSAT->getSizeModifier(), 0,
2978 SourceRange());
2979}
2980
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002981/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2982/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2983/// they point to and return true. If T1 and T2 aren't pointer types
2984/// or pointer-to-member types, or if they are not similar at this
2985/// level, returns false and leaves T1 and T2 unchanged. Top-level
2986/// qualifiers on T1 and T2 are ignored. This function will typically
2987/// be called in a loop that successively "unwraps" pointer and
2988/// pointer-to-member types to compare them at each level.
2989bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2990 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2991 *T2PtrType = T2->getAs<PointerType>();
2992 if (T1PtrType && T2PtrType) {
2993 T1 = T1PtrType->getPointeeType();
2994 T2 = T2PtrType->getPointeeType();
2995 return true;
2996 }
2997
2998 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2999 *T2MPType = T2->getAs<MemberPointerType>();
3000 if (T1MPType && T2MPType &&
3001 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3002 QualType(T2MPType->getClass(), 0))) {
3003 T1 = T1MPType->getPointeeType();
3004 T2 = T2MPType->getPointeeType();
3005 return true;
3006 }
3007
3008 if (getLangOptions().ObjC1) {
3009 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3010 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3011 if (T1OPType && T2OPType) {
3012 T1 = T1OPType->getPointeeType();
3013 T2 = T2OPType->getPointeeType();
3014 return true;
3015 }
3016 }
3017
3018 // FIXME: Block pointers, too?
3019
3020 return false;
3021}
3022
Jay Foad4ba2a172011-01-12 09:06:06 +00003023DeclarationNameInfo
3024ASTContext::getNameForTemplate(TemplateName Name,
3025 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003026 switch (Name.getKind()) {
3027 case TemplateName::QualifiedTemplate:
3028 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003029 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003030 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3031 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003032
John McCall14606042011-06-30 08:33:18 +00003033 case TemplateName::OverloadedTemplate: {
3034 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3035 // DNInfo work in progress: CHECKME: what about DNLoc?
3036 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3037 }
3038
3039 case TemplateName::DependentTemplate: {
3040 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003041 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003042 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003043 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3044 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003045 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003046 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3047 // DNInfo work in progress: FIXME: source locations?
3048 DeclarationNameLoc DNLoc;
3049 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3050 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3051 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003052 }
3053 }
3054
John McCall14606042011-06-30 08:33:18 +00003055 case TemplateName::SubstTemplateTemplateParm: {
3056 SubstTemplateTemplateParmStorage *subst
3057 = Name.getAsSubstTemplateTemplateParm();
3058 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3059 NameLoc);
3060 }
3061
3062 case TemplateName::SubstTemplateTemplateParmPack: {
3063 SubstTemplateTemplateParmPackStorage *subst
3064 = Name.getAsSubstTemplateTemplateParmPack();
3065 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3066 NameLoc);
3067 }
3068 }
3069
3070 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003071}
3072
Jay Foad4ba2a172011-01-12 09:06:06 +00003073TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003074 switch (Name.getKind()) {
3075 case TemplateName::QualifiedTemplate:
3076 case TemplateName::Template: {
3077 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003078 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003079 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003080 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3081
3082 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003083 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003084 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003085
John McCall14606042011-06-30 08:33:18 +00003086 case TemplateName::OverloadedTemplate:
3087 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003088
John McCall14606042011-06-30 08:33:18 +00003089 case TemplateName::DependentTemplate: {
3090 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3091 assert(DTN && "Non-dependent template names must refer to template decls.");
3092 return DTN->CanonicalTemplateName;
3093 }
3094
3095 case TemplateName::SubstTemplateTemplateParm: {
3096 SubstTemplateTemplateParmStorage *subst
3097 = Name.getAsSubstTemplateTemplateParm();
3098 return getCanonicalTemplateName(subst->getReplacement());
3099 }
3100
3101 case TemplateName::SubstTemplateTemplateParmPack: {
3102 SubstTemplateTemplateParmPackStorage *subst
3103 = Name.getAsSubstTemplateTemplateParmPack();
3104 TemplateTemplateParmDecl *canonParameter
3105 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3106 TemplateArgument canonArgPack
3107 = getCanonicalTemplateArgument(subst->getArgumentPack());
3108 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3109 }
3110 }
3111
3112 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003113}
3114
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003115bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3116 X = getCanonicalTemplateName(X);
3117 Y = getCanonicalTemplateName(Y);
3118 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3119}
3120
Mike Stump1eb44332009-09-09 15:08:12 +00003121TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003122ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003123 switch (Arg.getKind()) {
3124 case TemplateArgument::Null:
3125 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003126
Douglas Gregor1275ae02009-07-28 23:00:59 +00003127 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003128 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003129
Douglas Gregor1275ae02009-07-28 23:00:59 +00003130 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00003131 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003132
Douglas Gregor788cd062009-11-11 01:00:40 +00003133 case TemplateArgument::Template:
3134 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003135
3136 case TemplateArgument::TemplateExpansion:
3137 return TemplateArgument(getCanonicalTemplateName(
3138 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003139 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003140
Douglas Gregor1275ae02009-07-28 23:00:59 +00003141 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00003142 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003143 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003144
Douglas Gregor1275ae02009-07-28 23:00:59 +00003145 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003146 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003147
Douglas Gregor1275ae02009-07-28 23:00:59 +00003148 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003149 if (Arg.pack_size() == 0)
3150 return Arg;
3151
Douglas Gregor910f8002010-11-07 23:05:16 +00003152 TemplateArgument *CanonArgs
3153 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003154 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003155 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003156 AEnd = Arg.pack_end();
3157 A != AEnd; (void)++A, ++Idx)
3158 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003159
Douglas Gregor910f8002010-11-07 23:05:16 +00003160 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003161 }
3162 }
3163
3164 // Silence GCC warning
3165 assert(false && "Unhandled template argument kind");
3166 return TemplateArgument();
3167}
3168
Douglas Gregord57959a2009-03-27 23:10:48 +00003169NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003170ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003171 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003172 return 0;
3173
3174 switch (NNS->getKind()) {
3175 case NestedNameSpecifier::Identifier:
3176 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003177 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003178 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3179 NNS->getAsIdentifier());
3180
3181 case NestedNameSpecifier::Namespace:
3182 // A namespace is canonical; build a nested-name-specifier with
3183 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003184 return NestedNameSpecifier::Create(*this, 0,
3185 NNS->getAsNamespace()->getOriginalNamespace());
3186
3187 case NestedNameSpecifier::NamespaceAlias:
3188 // A namespace is canonical; build a nested-name-specifier with
3189 // this namespace and no prefix.
3190 return NestedNameSpecifier::Create(*this, 0,
3191 NNS->getAsNamespaceAlias()->getNamespace()
3192 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003193
3194 case NestedNameSpecifier::TypeSpec:
3195 case NestedNameSpecifier::TypeSpecWithTemplate: {
3196 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003197
3198 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3199 // break it apart into its prefix and identifier, then reconsititute those
3200 // as the canonical nested-name-specifier. This is required to canonicalize
3201 // a dependent nested-name-specifier involving typedefs of dependent-name
3202 // types, e.g.,
3203 // typedef typename T::type T1;
3204 // typedef typename T1::type T2;
3205 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3206 NestedNameSpecifier *Prefix
3207 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3208 return NestedNameSpecifier::Create(*this, Prefix,
3209 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3210 }
3211
Douglas Gregor643f8432010-11-04 00:14:23 +00003212 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor264bf662010-11-04 00:09:33 +00003213 if (const DependentTemplateSpecializationType *DTST
3214 = T->getAs<DependentTemplateSpecializationType>()) {
3215 NestedNameSpecifier *Prefix
3216 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003217
3218 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3219 Prefix, DTST->getIdentifier(),
3220 DTST->getNumArgs(),
3221 DTST->getArgs());
Douglas Gregor264bf662010-11-04 00:09:33 +00003222 T = getCanonicalType(T);
3223 }
3224
John McCall3b657512011-01-19 10:06:00 +00003225 return NestedNameSpecifier::Create(*this, 0, false,
3226 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003227 }
3228
3229 case NestedNameSpecifier::Global:
3230 // The global specifier is canonical and unique.
3231 return NNS;
3232 }
3233
3234 // Required to silence a GCC warning
3235 return 0;
3236}
3237
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003238
Jay Foad4ba2a172011-01-12 09:06:06 +00003239const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003240 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003241 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003242 // Handle the common positive case fast.
3243 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3244 return AT;
3245 }
Mike Stump1eb44332009-09-09 15:08:12 +00003246
John McCall0953e762009-09-24 19:53:00 +00003247 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003248 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003249 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003250
John McCall0953e762009-09-24 19:53:00 +00003251 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003252 // implements C99 6.7.3p8: "If the specification of an array type includes
3253 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003254
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003255 // If we get here, we either have type qualifiers on the type, or we have
3256 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003257 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003258
John McCall3b657512011-01-19 10:06:00 +00003259 SplitQualType split = T.getSplitDesugaredType();
3260 Qualifiers qs = split.second;
Mike Stump1eb44332009-09-09 15:08:12 +00003261
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003262 // If we have a simple case, just return now.
John McCall3b657512011-01-19 10:06:00 +00003263 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3264 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003265 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003266
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003267 // Otherwise, we have an array and we have qualifiers on it. Push the
3268 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003269 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003270
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003271 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3272 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3273 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003274 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003275 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3276 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3277 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003278 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003279
Mike Stump1eb44332009-09-09 15:08:12 +00003280 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003281 = dyn_cast<DependentSizedArrayType>(ATy))
3282 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003283 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003284 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003285 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003286 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003287 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003288
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003289 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003290 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003291 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003292 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003293 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003294 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003295}
3296
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003297QualType ASTContext::getAdjustedParameterType(QualType T) {
3298 // C99 6.7.5.3p7:
3299 // A declaration of a parameter as "array of type" shall be
3300 // adjusted to "qualified pointer to type", where the type
3301 // qualifiers (if any) are those specified within the [ and ] of
3302 // the array type derivation.
3303 if (T->isArrayType())
3304 return getArrayDecayedType(T);
3305
3306 // C99 6.7.5.3p8:
3307 // A declaration of a parameter as "function returning type"
3308 // shall be adjusted to "pointer to function returning type", as
3309 // in 6.3.2.1.
3310 if (T->isFunctionType())
3311 return getPointerType(T);
3312
3313 return T;
3314}
3315
3316QualType ASTContext::getSignatureParameterType(QualType T) {
3317 T = getVariableArrayDecayedType(T);
3318 T = getAdjustedParameterType(T);
3319 return T.getUnqualifiedType();
3320}
3321
Chris Lattnere6327742008-04-02 05:18:44 +00003322/// getArrayDecayedType - Return the properly qualified result of decaying the
3323/// specified array type to a pointer. This operation is non-trivial when
3324/// handling typedefs etc. The canonical type of "T" must be an array type,
3325/// this returns a pointer to a properly qualified element of the array.
3326///
3327/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003328QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003329 // Get the element type with 'getAsArrayType' so that we don't lose any
3330 // typedefs in the element type of the array. This also handles propagation
3331 // of type qualifiers from the array type into the element type if present
3332 // (C99 6.7.3p8).
3333 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3334 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003335
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003336 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003337
3338 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003339 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003340}
3341
John McCall3b657512011-01-19 10:06:00 +00003342QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3343 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003344}
3345
John McCall3b657512011-01-19 10:06:00 +00003346QualType ASTContext::getBaseElementType(QualType type) const {
3347 Qualifiers qs;
3348 while (true) {
3349 SplitQualType split = type.getSplitDesugaredType();
3350 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3351 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003352
John McCall3b657512011-01-19 10:06:00 +00003353 type = array->getElementType();
3354 qs.addConsistentQualifiers(split.second);
3355 }
Mike Stump1eb44332009-09-09 15:08:12 +00003356
John McCall3b657512011-01-19 10:06:00 +00003357 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003358}
3359
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003360/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003361uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003362ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3363 uint64_t ElementCount = 1;
3364 do {
3365 ElementCount *= CA->getSize().getZExtValue();
3366 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3367 } while (CA);
3368 return ElementCount;
3369}
3370
Reid Spencer5f016e22007-07-11 17:01:13 +00003371/// getFloatingRank - Return a relative rank for floating point types.
3372/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003373static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003374 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003375 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003376
John McCall183700f2009-09-21 23:43:11 +00003377 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3378 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00003379 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00003380 case BuiltinType::Float: return FloatRank;
3381 case BuiltinType::Double: return DoubleRank;
3382 case BuiltinType::LongDouble: return LongDoubleRank;
3383 }
3384}
3385
Mike Stump1eb44332009-09-09 15:08:12 +00003386/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3387/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003388/// 'typeDomain' is a real floating point or complex type.
3389/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003390QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3391 QualType Domain) const {
3392 FloatingRank EltRank = getFloatingRank(Size);
3393 if (Domain->isComplexType()) {
3394 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00003395 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00003396 case FloatRank: return FloatComplexTy;
3397 case DoubleRank: return DoubleComplexTy;
3398 case LongDoubleRank: return LongDoubleComplexTy;
3399 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003400 }
Chris Lattner1361b112008-04-06 23:58:54 +00003401
3402 assert(Domain->isRealFloatingType() && "Unknown domain!");
3403 switch (EltRank) {
3404 default: assert(0 && "getFloatingRank(): illegal value for rank");
3405 case FloatRank: return FloatTy;
3406 case DoubleRank: return DoubleTy;
3407 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003408 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003409}
3410
Chris Lattner7cfeb082008-04-06 23:55:33 +00003411/// getFloatingTypeOrder - Compare the rank of the two specified floating
3412/// point types, ignoring the domain of the type (i.e. 'double' ==
3413/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003414/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003415int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003416 FloatingRank LHSR = getFloatingRank(LHS);
3417 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003418
Chris Lattnera75cea32008-04-06 23:38:49 +00003419 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003420 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003421 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003422 return 1;
3423 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003424}
3425
Chris Lattnerf52ab252008-04-06 22:59:24 +00003426/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3427/// routine will assert if passed a built-in type that isn't an integer or enum,
3428/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003429unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003430 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCallf4c73712011-01-19 06:33:43 +00003431 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00003432 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00003433
Chris Lattner3f59c972010-12-25 23:25:43 +00003434 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3435 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmana3426752009-07-05 23:44:27 +00003436 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3437
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003438 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3439 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3440
3441 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3442 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3443
Chris Lattnerf52ab252008-04-06 22:59:24 +00003444 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00003445 default: assert(0 && "getIntegerRank(): not a built-in integer");
3446 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003447 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003448 case BuiltinType::Char_S:
3449 case BuiltinType::Char_U:
3450 case BuiltinType::SChar:
3451 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003452 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003453 case BuiltinType::Short:
3454 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003455 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003456 case BuiltinType::Int:
3457 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003458 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003459 case BuiltinType::Long:
3460 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003461 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003462 case BuiltinType::LongLong:
3463 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003464 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003465 case BuiltinType::Int128:
3466 case BuiltinType::UInt128:
3467 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003468 }
3469}
3470
Eli Friedman04e83572009-08-20 04:21:42 +00003471/// \brief Whether this is a promotable bitfield reference according
3472/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3473///
3474/// \returns the type this bit-field will promote to, or NULL if no
3475/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00003476QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003477 if (E->isTypeDependent() || E->isValueDependent())
3478 return QualType();
3479
Eli Friedman04e83572009-08-20 04:21:42 +00003480 FieldDecl *Field = E->getBitField();
3481 if (!Field)
3482 return QualType();
3483
3484 QualType FT = Field->getType();
3485
3486 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3487 uint64_t BitWidth = BitWidthAP.getZExtValue();
3488 uint64_t IntSize = getTypeSize(IntTy);
3489 // GCC extension compatibility: if the bit-field size is less than or equal
3490 // to the size of int, it gets promoted no matter what its type is.
3491 // For instance, unsigned long bf : 4 gets promoted to signed int.
3492 if (BitWidth < IntSize)
3493 return IntTy;
3494
3495 if (BitWidth == IntSize)
3496 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3497
3498 // Types bigger than int are not subject to promotions, and therefore act
3499 // like the base type.
3500 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3501 // is ridiculous.
3502 return QualType();
3503}
3504
Eli Friedmana95d7572009-08-19 07:44:53 +00003505/// getPromotedIntegerType - Returns the type that Promotable will
3506/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3507/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003508QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003509 assert(!Promotable.isNull());
3510 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003511 if (const EnumType *ET = Promotable->getAs<EnumType>())
3512 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00003513 if (Promotable->isSignedIntegerType())
3514 return IntTy;
3515 uint64_t PromotableSize = getTypeSize(Promotable);
3516 uint64_t IntSize = getTypeSize(IntTy);
3517 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3518 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3519}
3520
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003521/// \brief Recurses in pointer/array types until it finds an objc retainable
3522/// type and returns its ownership.
3523Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3524 while (!T.isNull()) {
3525 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3526 return T.getObjCLifetime();
3527 if (T->isArrayType())
3528 T = getBaseElementType(T);
3529 else if (const PointerType *PT = T->getAs<PointerType>())
3530 T = PT->getPointeeType();
3531 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00003532 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003533 else
3534 break;
3535 }
3536
3537 return Qualifiers::OCL_None;
3538}
3539
Mike Stump1eb44332009-09-09 15:08:12 +00003540/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003541/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003542/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003543int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00003544 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3545 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003546 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003547
Chris Lattnerf52ab252008-04-06 22:59:24 +00003548 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3549 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003550
Chris Lattner7cfeb082008-04-06 23:55:33 +00003551 unsigned LHSRank = getIntegerRank(LHSC);
3552 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003553
Chris Lattner7cfeb082008-04-06 23:55:33 +00003554 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3555 if (LHSRank == RHSRank) return 0;
3556 return LHSRank > RHSRank ? 1 : -1;
3557 }
Mike Stump1eb44332009-09-09 15:08:12 +00003558
Chris Lattner7cfeb082008-04-06 23:55:33 +00003559 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3560 if (LHSUnsigned) {
3561 // If the unsigned [LHS] type is larger, return it.
3562 if (LHSRank >= RHSRank)
3563 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003564
Chris Lattner7cfeb082008-04-06 23:55:33 +00003565 // If the signed type can represent all values of the unsigned type, it
3566 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003567 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003568 return -1;
3569 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003570
Chris Lattner7cfeb082008-04-06 23:55:33 +00003571 // If the unsigned [RHS] type is larger, return it.
3572 if (RHSRank >= LHSRank)
3573 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003574
Chris Lattner7cfeb082008-04-06 23:55:33 +00003575 // If the signed type can represent all values of the unsigned type, it
3576 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003577 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003578 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003579}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003580
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003581static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003582CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3583 DeclContext *DC, IdentifierInfo *Id) {
3584 SourceLocation Loc;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003585 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003586 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003587 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003588 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003589}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003590
Mike Stump1eb44332009-09-09 15:08:12 +00003591// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003592QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003593 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003594 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003595 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003596 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003597 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003598
Anders Carlssonf06273f2007-11-19 00:25:30 +00003599 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003600
Anders Carlsson71993dd2007-08-17 05:31:46 +00003601 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003602 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003603 // int flags;
3604 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003605 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003606 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003607 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003608 FieldTypes[3] = LongTy;
3609
Anders Carlsson71993dd2007-08-17 05:31:46 +00003610 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003611 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003612 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003613 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00003614 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003615 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003616 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003617 /*Mutable=*/false,
3618 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003619 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003620 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003621 }
3622
Douglas Gregor838db382010-02-11 01:19:42 +00003623 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003624 }
Mike Stump1eb44332009-09-09 15:08:12 +00003625
Anders Carlsson71993dd2007-08-17 05:31:46 +00003626 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003627}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003628
Douglas Gregor319ac892009-04-23 22:29:11 +00003629void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003630 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003631 assert(Rec && "Invalid CFConstantStringType");
3632 CFConstantStringTypeDecl = Rec->getDecl();
3633}
3634
Jay Foad4ba2a172011-01-12 09:06:06 +00003635QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00003636 if (BlockDescriptorType)
3637 return getTagDeclType(BlockDescriptorType);
3638
3639 RecordDecl *T;
3640 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003641 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003642 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003643 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003644
3645 QualType FieldTypes[] = {
3646 UnsignedLongTy,
3647 UnsignedLongTy,
3648 };
3649
3650 const char *FieldNames[] = {
3651 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003652 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003653 };
3654
3655 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003656 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003657 SourceLocation(),
3658 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003659 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003660 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003661 /*Mutable=*/false,
3662 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003663 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003664 T->addDecl(Field);
3665 }
3666
Douglas Gregor838db382010-02-11 01:19:42 +00003667 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003668
3669 BlockDescriptorType = T;
3670
3671 return getTagDeclType(BlockDescriptorType);
3672}
3673
Jay Foad4ba2a172011-01-12 09:06:06 +00003674QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00003675 if (BlockDescriptorExtendedType)
3676 return getTagDeclType(BlockDescriptorExtendedType);
3677
3678 RecordDecl *T;
3679 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003680 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003681 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003682 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003683
3684 QualType FieldTypes[] = {
3685 UnsignedLongTy,
3686 UnsignedLongTy,
3687 getPointerType(VoidPtrTy),
3688 getPointerType(VoidPtrTy)
3689 };
3690
3691 const char *FieldNames[] = {
3692 "reserved",
3693 "Size",
3694 "CopyFuncPtr",
3695 "DestroyFuncPtr"
3696 };
3697
3698 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003699 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00003700 SourceLocation(),
3701 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003702 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003703 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003704 /*Mutable=*/false,
3705 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003706 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003707 T->addDecl(Field);
3708 }
3709
Douglas Gregor838db382010-02-11 01:19:42 +00003710 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003711
3712 BlockDescriptorExtendedType = T;
3713
3714 return getTagDeclType(BlockDescriptorExtendedType);
3715}
3716
Jay Foad4ba2a172011-01-12 09:06:06 +00003717bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCallf85e1932011-06-15 23:02:42 +00003718 if (Ty->isObjCRetainableType())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003719 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003720 if (getLangOptions().CPlusPlus) {
3721 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3722 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Huntffe37fd2011-05-25 20:50:04 +00003723 return RD->hasConstCopyConstructor();
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003724
3725 }
3726 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003727 return false;
3728}
3729
Jay Foad4ba2a172011-01-12 09:06:06 +00003730QualType
Chris Lattner5f9e2722011-07-23 10:55:15 +00003731ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003732 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003733 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003734 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003735 // unsigned int __flags;
3736 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003737 // void *__copy_helper; // as needed
3738 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003739 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003740 // } *
3741
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003742 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3743
3744 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003745 llvm::SmallString<36> Name;
3746 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3747 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003748 RecordDecl *T;
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003749 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003750 T->startDefinition();
3751 QualType Int32Ty = IntTy;
3752 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3753 QualType FieldTypes[] = {
3754 getPointerType(VoidPtrTy),
3755 getPointerType(getTagDeclType(T)),
3756 Int32Ty,
3757 Int32Ty,
3758 getPointerType(VoidPtrTy),
3759 getPointerType(VoidPtrTy),
3760 Ty
3761 };
3762
Chris Lattner5f9e2722011-07-23 10:55:15 +00003763 StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003764 "__isa",
3765 "__forwarding",
3766 "__flags",
3767 "__size",
3768 "__copy_helper",
3769 "__destroy_helper",
3770 DeclName,
3771 };
3772
3773 for (size_t i = 0; i < 7; ++i) {
3774 if (!HasCopyAndDispose && i >=4 && i <= 5)
3775 continue;
3776 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003777 SourceLocation(),
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003778 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003779 FieldTypes[i], /*TInfo=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003780 /*BitWidth=*/0, /*Mutable=*/false,
3781 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003782 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003783 T->addDecl(Field);
3784 }
3785
Douglas Gregor838db382010-02-11 01:19:42 +00003786 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003787
3788 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003789}
3790
Anders Carlssone8c49532007-10-29 06:33:42 +00003791// This returns true if a type has been typedefed to BOOL:
3792// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003793static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003794 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003795 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3796 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003797
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003798 return false;
3799}
3800
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003801/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003802/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00003803CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00003804 if (!type->isIncompleteArrayType() && type->isIncompleteType())
3805 return CharUnits::Zero();
3806
Ken Dyck199c3d62010-01-11 17:06:35 +00003807 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003808
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003809 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003810 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003811 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003812 // Treat arrays as pointers, since that's how they're passed in.
3813 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003814 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003815 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003816}
3817
3818static inline
3819std::string charUnitsToString(const CharUnits &CU) {
3820 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003821}
3822
John McCall6b5a61b2011-02-07 10:33:21 +00003823/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003824/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00003825std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3826 std::string S;
3827
David Chisnall5e530af2009-11-17 19:33:30 +00003828 const BlockDecl *Decl = Expr->getBlockDecl();
3829 QualType BlockTy =
3830 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3831 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003832 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003833 // Compute size of all parameters.
3834 // Start with computing size of a pointer in number of bytes.
3835 // FIXME: There might(should) be a better way of doing this computation!
3836 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003837 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3838 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003839 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003840 E = Decl->param_end(); PI != E; ++PI) {
3841 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003842 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003843 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003844 ParmOffset += sz;
3845 }
3846 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003847 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003848 // Block pointer and offset.
3849 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00003850
3851 // Argument types.
3852 ParmOffset = PtrSize;
3853 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3854 Decl->param_end(); PI != E; ++PI) {
3855 ParmVarDecl *PVDecl = *PI;
3856 QualType PType = PVDecl->getOriginalType();
3857 if (const ArrayType *AT =
3858 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3859 // Use array's original type only if it has known number of
3860 // elements.
3861 if (!isa<ConstantArrayType>(AT))
3862 PType = PVDecl->getType();
3863 } else if (PType->isFunctionType())
3864 PType = PVDecl->getType();
3865 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003866 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003867 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003868 }
John McCall6b5a61b2011-02-07 10:33:21 +00003869
3870 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00003871}
3872
Douglas Gregorf968d832011-05-27 01:19:52 +00003873bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00003874 std::string& S) {
3875 // Encode result type.
3876 getObjCEncodingForType(Decl->getResultType(), S);
3877 CharUnits ParmOffset;
3878 // Compute size of all parameters.
3879 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3880 E = Decl->param_end(); PI != E; ++PI) {
3881 QualType PType = (*PI)->getType();
3882 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00003883 if (sz.isZero())
3884 return true;
3885
David Chisnall5389f482010-12-30 14:05:53 +00003886 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00003887 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00003888 ParmOffset += sz;
3889 }
3890 S += charUnitsToString(ParmOffset);
3891 ParmOffset = CharUnits::Zero();
3892
3893 // Argument types.
3894 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3895 E = Decl->param_end(); PI != E; ++PI) {
3896 ParmVarDecl *PVDecl = *PI;
3897 QualType PType = PVDecl->getOriginalType();
3898 if (const ArrayType *AT =
3899 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3900 // Use array's original type only if it has known number of
3901 // elements.
3902 if (!isa<ConstantArrayType>(AT))
3903 PType = PVDecl->getType();
3904 } else if (PType->isFunctionType())
3905 PType = PVDecl->getType();
3906 getObjCEncodingForType(PType, S);
3907 S += charUnitsToString(ParmOffset);
3908 ParmOffset += getObjCEncodingTypeSize(PType);
3909 }
Douglas Gregorf968d832011-05-27 01:19:52 +00003910
3911 return false;
David Chisnall5389f482010-12-30 14:05:53 +00003912}
3913
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003914/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003915/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00003916bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00003917 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003918 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003919 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003920 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003921 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003922 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003923 // Compute size of all parameters.
3924 // Start with computing size of a pointer in number of bytes.
3925 // FIXME: There might(should) be a better way of doing this computation!
3926 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003927 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003928 // The first two arguments (self and _cmd) are pointers; account for
3929 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003930 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003931 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003932 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003933 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003934 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00003935 if (sz.isZero())
3936 return true;
3937
Ken Dyck199c3d62010-01-11 17:06:35 +00003938 assert (sz.isPositive() &&
3939 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003940 ParmOffset += sz;
3941 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003942 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003943 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003944 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003945
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003946 // Argument types.
3947 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003948 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003949 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003950 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003951 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003952 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003953 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3954 // Use array's original type only if it has known number of
3955 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003956 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003957 PType = PVDecl->getType();
3958 } else if (PType->isFunctionType())
3959 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003960 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003961 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003962 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003963 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003964 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003965 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003966 }
Douglas Gregorf968d832011-05-27 01:19:52 +00003967
3968 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003969}
3970
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003971/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003972/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003973/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3974/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003975/// Property attributes are stored as a comma-delimited C string. The simple
3976/// attributes readonly and bycopy are encoded as single characters. The
3977/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3978/// encoded as single characters, followed by an identifier. Property types
3979/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003980/// these attributes are defined by the following enumeration:
3981/// @code
3982/// enum PropertyAttributes {
3983/// kPropertyReadOnly = 'R', // property is read-only.
3984/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3985/// kPropertyByref = '&', // property is a reference to the value last assigned
3986/// kPropertyDynamic = 'D', // property is dynamic
3987/// kPropertyGetter = 'G', // followed by getter selector name
3988/// kPropertySetter = 'S', // followed by setter selector name
3989/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3990/// kPropertyType = 't' // followed by old-style type encoding.
3991/// kPropertyWeak = 'W' // 'weak' property
3992/// kPropertyStrong = 'P' // property GC'able
3993/// kPropertyNonAtomic = 'N' // property non-atomic
3994/// };
3995/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003996void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003997 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00003998 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003999 // Collect information from the property implementation decl(s).
4000 bool Dynamic = false;
4001 ObjCPropertyImplDecl *SynthesizePID = 0;
4002
4003 // FIXME: Duplicated code due to poor abstraction.
4004 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004005 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004006 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4007 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004008 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004009 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004010 ObjCPropertyImplDecl *PID = *i;
4011 if (PID->getPropertyDecl() == PD) {
4012 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4013 Dynamic = true;
4014 } else {
4015 SynthesizePID = PID;
4016 }
4017 }
4018 }
4019 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004020 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004021 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004022 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004023 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004024 ObjCPropertyImplDecl *PID = *i;
4025 if (PID->getPropertyDecl() == PD) {
4026 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4027 Dynamic = true;
4028 } else {
4029 SynthesizePID = PID;
4030 }
4031 }
Mike Stump1eb44332009-09-09 15:08:12 +00004032 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004033 }
4034 }
4035
4036 // FIXME: This is not very efficient.
4037 S = "T";
4038
4039 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004040 // GCC has some special rules regarding encoding of properties which
4041 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004042 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004043 true /* outermost type */,
4044 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004045
4046 if (PD->isReadOnly()) {
4047 S += ",R";
4048 } else {
4049 switch (PD->getSetterKind()) {
4050 case ObjCPropertyDecl::Assign: break;
4051 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004052 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004053 }
4054 }
4055
4056 // It really isn't clear at all what this means, since properties
4057 // are "dynamic by default".
4058 if (Dynamic)
4059 S += ",D";
4060
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004061 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4062 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004063
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004064 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4065 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004066 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004067 }
4068
4069 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4070 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004071 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004072 }
4073
4074 if (SynthesizePID) {
4075 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4076 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004077 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004078 }
4079
4080 // FIXME: OBJCGC: weak & strong
4081}
4082
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004083/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004084/// Another legacy compatibility encoding: 32-bit longs are encoded as
4085/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004086/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4087///
4088void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004089 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004090 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004091 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004092 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004093 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004094 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004095 PointeeTy = IntTy;
4096 }
4097 }
4098}
4099
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004100void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004101 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004102 // We follow the behavior of gcc, expanding structures which are
4103 // directly pointed to, and expanding embedded structures. Note that
4104 // these rules are sufficient to prevent recursive encoding of the
4105 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004106 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004107 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004108}
4109
David Chisnall64fd7e82010-06-04 01:10:52 +00004110static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4111 switch (T->getAs<BuiltinType>()->getKind()) {
4112 default: assert(0 && "Unhandled builtin type kind");
4113 case BuiltinType::Void: return 'v';
4114 case BuiltinType::Bool: return 'B';
4115 case BuiltinType::Char_U:
4116 case BuiltinType::UChar: return 'C';
4117 case BuiltinType::UShort: return 'S';
4118 case BuiltinType::UInt: return 'I';
4119 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00004120 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004121 case BuiltinType::UInt128: return 'T';
4122 case BuiltinType::ULongLong: return 'Q';
4123 case BuiltinType::Char_S:
4124 case BuiltinType::SChar: return 'c';
4125 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004126 case BuiltinType::WChar_S:
4127 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004128 case BuiltinType::Int: return 'i';
4129 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00004130 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004131 case BuiltinType::LongLong: return 'q';
4132 case BuiltinType::Int128: return 't';
4133 case BuiltinType::Float: return 'f';
4134 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004135 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004136 }
4137}
4138
Jay Foad4ba2a172011-01-12 09:06:06 +00004139static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004140 QualType T, const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004141 const Expr *E = FD->getBitWidth();
4142 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004143 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004144 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4145 // The GNU runtime requires more information; bitfields are encoded as b,
4146 // then the offset (in bits) of the first element, then the type of the
4147 // bitfield, then the size in bits. For example, in this structure:
4148 //
4149 // struct
4150 // {
4151 // int integer;
4152 // int flags:2;
4153 // };
4154 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4155 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4156 // information is not especially sensible, but we're stuck with it for
4157 // compatibility with GCC, although providing it breaks anything that
4158 // actually uses runtime introspection and wants to work on both runtimes...
4159 if (!Ctx->getLangOptions().NeXTRuntime) {
4160 const RecordDecl *RD = FD->getParent();
4161 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004162 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
David Chisnallc7ff82c2010-12-26 20:12:30 +00004163 if (T->isEnumeralType())
4164 S += 'i';
4165 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004166 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004167 }
4168 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004169 S += llvm::utostr(N);
4170}
4171
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004172// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004173void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4174 bool ExpandPointedToStructures,
4175 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004176 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004177 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004178 bool EncodingProperty,
4179 bool StructField) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004180 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004181 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004182 return EncodeBitField(this, S, T, FD);
4183 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004184 return;
4185 }
Mike Stump1eb44332009-09-09 15:08:12 +00004186
John McCall183700f2009-09-21 23:43:11 +00004187 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004188 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004189 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004190 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004191 return;
4192 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004193
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004194 // encoding for pointer or r3eference types.
4195 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004196 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004197 if (PT->isObjCSelType()) {
4198 S += ':';
4199 return;
4200 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004201 PointeeTy = PT->getPointeeType();
4202 }
4203 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4204 PointeeTy = RT->getPointeeType();
4205 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004206 bool isReadOnly = false;
4207 // For historical/compatibility reasons, the read-only qualifier of the
4208 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4209 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004210 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004211 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004212 if (OutermostType && T.isConstQualified()) {
4213 isReadOnly = true;
4214 S += 'r';
4215 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004216 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004217 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004218 while (P->getAs<PointerType>())
4219 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004220 if (P.isConstQualified()) {
4221 isReadOnly = true;
4222 S += 'r';
4223 }
4224 }
4225 if (isReadOnly) {
4226 // Another legacy compatibility encoding. Some ObjC qualifier and type
4227 // combinations need to be rearranged.
4228 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00004229 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00004230 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004231 }
Mike Stump1eb44332009-09-09 15:08:12 +00004232
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004233 if (PointeeTy->isCharType()) {
4234 // char pointer types should be encoded as '*' unless it is a
4235 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004236 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004237 S += '*';
4238 return;
4239 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004240 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004241 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4242 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4243 S += '#';
4244 return;
4245 }
4246 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4247 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4248 S += '@';
4249 return;
4250 }
4251 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004252 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004253 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004254 getLegacyIntegralTypeEncoding(PointeeTy);
4255
Mike Stump1eb44332009-09-09 15:08:12 +00004256 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004257 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004258 return;
4259 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004260
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004261 if (const ArrayType *AT =
4262 // Ignore type qualifiers etc.
4263 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004264 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004265 // Incomplete arrays are encoded as a pointer to the array element.
4266 S += '^';
4267
Mike Stump1eb44332009-09-09 15:08:12 +00004268 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004269 false, ExpandStructures, FD);
4270 } else {
4271 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004272
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004273 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4274 if (getTypeSize(CAT->getElementType()) == 0)
4275 S += '0';
4276 else
4277 S += llvm::utostr(CAT->getSize().getZExtValue());
4278 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00004279 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004280 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4281 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00004282 S += '0';
4283 }
Mike Stump1eb44332009-09-09 15:08:12 +00004284
4285 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004286 false, ExpandStructures, FD);
4287 S += ']';
4288 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004289 return;
4290 }
Mike Stump1eb44332009-09-09 15:08:12 +00004291
John McCall183700f2009-09-21 23:43:11 +00004292 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004293 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004294 return;
4295 }
Mike Stump1eb44332009-09-09 15:08:12 +00004296
Ted Kremenek6217b802009-07-29 21:53:49 +00004297 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004298 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004299 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004300 // Anonymous structures print as '?'
4301 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4302 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004303 if (ClassTemplateSpecializationDecl *Spec
4304 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4305 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4306 std::string TemplateArgsStr
4307 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004308 TemplateArgs.data(),
4309 TemplateArgs.size(),
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004310 (*this).PrintingPolicy);
4311
4312 S += TemplateArgsStr;
4313 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004314 } else {
4315 S += '?';
4316 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004317 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004318 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004319 if (!RDecl->isUnion()) {
4320 getObjCEncodingForStructureImpl(RDecl, S, FD);
4321 } else {
4322 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4323 FieldEnd = RDecl->field_end();
4324 Field != FieldEnd; ++Field) {
4325 if (FD) {
4326 S += '"';
4327 S += Field->getNameAsString();
4328 S += '"';
4329 }
Mike Stump1eb44332009-09-09 15:08:12 +00004330
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004331 // Special case bit-fields.
4332 if (Field->isBitField()) {
4333 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4334 (*Field));
4335 } else {
4336 QualType qt = Field->getType();
4337 getLegacyIntegralTypeEncoding(qt);
4338 getObjCEncodingForTypeImpl(qt, S, false, true,
4339 FD, /*OutermostType*/false,
4340 /*EncodingProperty*/false,
4341 /*StructField*/true);
4342 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004343 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004344 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004345 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004346 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004347 return;
4348 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004349
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004350 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004351 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004352 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004353 else
4354 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004355 return;
4356 }
Mike Stump1eb44332009-09-09 15:08:12 +00004357
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004358 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004359 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004360 return;
4361 }
Mike Stump1eb44332009-09-09 15:08:12 +00004362
John McCallc12c5bb2010-05-15 11:32:37 +00004363 // Ignore protocol qualifiers when mangling at this level.
4364 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4365 T = OT->getBaseType();
4366
John McCall0953e762009-09-24 19:53:00 +00004367 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004368 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004369 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004370 S += '{';
4371 const IdentifierInfo *II = OI->getIdentifier();
4372 S += II->getName();
4373 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00004374 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004375 DeepCollectObjCIvars(OI, true, Ivars);
4376 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00004377 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004378 if (Field->isBitField())
4379 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004380 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004381 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004382 }
4383 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004384 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004385 }
Mike Stump1eb44332009-09-09 15:08:12 +00004386
John McCall183700f2009-09-21 23:43:11 +00004387 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004388 if (OPT->isObjCIdType()) {
4389 S += '@';
4390 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004391 }
Mike Stump1eb44332009-09-09 15:08:12 +00004392
Steve Naroff27d20a22009-10-28 22:03:49 +00004393 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4394 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4395 // Since this is a binary compatibility issue, need to consult with runtime
4396 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004397 S += '#';
4398 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004399 }
Mike Stump1eb44332009-09-09 15:08:12 +00004400
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004401 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004402 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004403 ExpandPointedToStructures,
4404 ExpandStructures, FD);
4405 if (FD || EncodingProperty) {
4406 // Note that we do extended encoding of protocol qualifer list
4407 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004408 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004409 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4410 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004411 S += '<';
4412 S += (*I)->getNameAsString();
4413 S += '>';
4414 }
4415 S += '"';
4416 }
4417 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004418 }
Mike Stump1eb44332009-09-09 15:08:12 +00004419
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004420 QualType PointeeTy = OPT->getPointeeType();
4421 if (!EncodingProperty &&
4422 isa<TypedefType>(PointeeTy.getTypePtr())) {
4423 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004424 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004425 // {...};
4426 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004427 getObjCEncodingForTypeImpl(PointeeTy, S,
4428 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004429 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004430 return;
4431 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004432
4433 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00004434 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004435 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004436 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004437 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4438 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004439 S += '<';
4440 S += (*I)->getNameAsString();
4441 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004442 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004443 S += '"';
4444 }
4445 return;
4446 }
Mike Stump1eb44332009-09-09 15:08:12 +00004447
John McCall532ec7b2010-05-17 23:56:34 +00004448 // gcc just blithely ignores member pointers.
4449 // TODO: maybe there should be a mangling for these
4450 if (T->getAs<MemberPointerType>())
4451 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004452
4453 if (T->isVectorType()) {
4454 // This matches gcc's encoding, even though technically it is
4455 // insufficient.
4456 // FIXME. We should do a better job than gcc.
4457 return;
4458 }
4459
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004460 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004461}
4462
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004463void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4464 std::string &S,
4465 const FieldDecl *FD,
4466 bool includeVBases) const {
4467 assert(RDecl && "Expected non-null RecordDecl");
4468 assert(!RDecl->isUnion() && "Should not be called for unions");
4469 if (!RDecl->getDefinition())
4470 return;
4471
4472 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4473 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4474 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4475
4476 if (CXXRec) {
4477 for (CXXRecordDecl::base_class_iterator
4478 BI = CXXRec->bases_begin(),
4479 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4480 if (!BI->isVirtual()) {
4481 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004482 if (base->isEmpty())
4483 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004484 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4485 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4486 std::make_pair(offs, base));
4487 }
4488 }
4489 }
4490
4491 unsigned i = 0;
4492 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4493 FieldEnd = RDecl->field_end();
4494 Field != FieldEnd; ++Field, ++i) {
4495 uint64_t offs = layout.getFieldOffset(i);
4496 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4497 std::make_pair(offs, *Field));
4498 }
4499
4500 if (CXXRec && includeVBases) {
4501 for (CXXRecordDecl::base_class_iterator
4502 BI = CXXRec->vbases_begin(),
4503 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4504 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004505 if (base->isEmpty())
4506 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004507 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
4508 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4509 std::make_pair(offs, base));
4510 }
4511 }
4512
4513 CharUnits size;
4514 if (CXXRec) {
4515 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4516 } else {
4517 size = layout.getSize();
4518 }
4519
4520 uint64_t CurOffs = 0;
4521 std::multimap<uint64_t, NamedDecl *>::iterator
4522 CurLayObj = FieldOrBaseOffsets.begin();
4523
4524 if (CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) {
4525 assert(CXXRec && CXXRec->isDynamicClass() &&
4526 "Offset 0 was empty but no VTable ?");
4527 if (FD) {
4528 S += "\"_vptr$";
4529 std::string recname = CXXRec->getNameAsString();
4530 if (recname.empty()) recname = "?";
4531 S += recname;
4532 S += '"';
4533 }
4534 S += "^^?";
4535 CurOffs += getTypeSize(VoidPtrTy);
4536 }
4537
4538 if (!RDecl->hasFlexibleArrayMember()) {
4539 // Mark the end of the structure.
4540 uint64_t offs = toBits(size);
4541 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4542 std::make_pair(offs, (NamedDecl*)0));
4543 }
4544
4545 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4546 assert(CurOffs <= CurLayObj->first);
4547
4548 if (CurOffs < CurLayObj->first) {
4549 uint64_t padding = CurLayObj->first - CurOffs;
4550 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4551 // packing/alignment of members is different that normal, in which case
4552 // the encoding will be out-of-sync with the real layout.
4553 // If the runtime switches to just consider the size of types without
4554 // taking into account alignment, we could make padding explicit in the
4555 // encoding (e.g. using arrays of chars). The encoding strings would be
4556 // longer then though.
4557 CurOffs += padding;
4558 }
4559
4560 NamedDecl *dcl = CurLayObj->second;
4561 if (dcl == 0)
4562 break; // reached end of structure.
4563
4564 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4565 // We expand the bases without their virtual bases since those are going
4566 // in the initial structure. Note that this differs from gcc which
4567 // expands virtual bases each time one is encountered in the hierarchy,
4568 // making the encoding type bigger than it really is.
4569 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004570 assert(!base->isEmpty());
4571 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004572 } else {
4573 FieldDecl *field = cast<FieldDecl>(dcl);
4574 if (FD) {
4575 S += '"';
4576 S += field->getNameAsString();
4577 S += '"';
4578 }
4579
4580 if (field->isBitField()) {
4581 EncodeBitField(this, S, field->getType(), field);
4582 CurOffs += field->getBitWidth()->EvaluateAsInt(*this).getZExtValue();
4583 } else {
4584 QualType qt = field->getType();
4585 getLegacyIntegralTypeEncoding(qt);
4586 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4587 /*OutermostType*/false,
4588 /*EncodingProperty*/false,
4589 /*StructField*/true);
4590 CurOffs += getTypeSize(field->getType());
4591 }
4592 }
4593 }
4594}
4595
Mike Stump1eb44332009-09-09 15:08:12 +00004596void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004597 std::string& S) const {
4598 if (QT & Decl::OBJC_TQ_In)
4599 S += 'n';
4600 if (QT & Decl::OBJC_TQ_Inout)
4601 S += 'N';
4602 if (QT & Decl::OBJC_TQ_Out)
4603 S += 'o';
4604 if (QT & Decl::OBJC_TQ_Bycopy)
4605 S += 'O';
4606 if (QT & Decl::OBJC_TQ_Byref)
4607 S += 'R';
4608 if (QT & Decl::OBJC_TQ_Oneway)
4609 S += 'V';
4610}
4611
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004612void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004613 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004614
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004615 BuiltinVaListType = T;
4616}
4617
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00004618TypedefDecl *ASTContext::getObjCIdDecl() const {
4619 if (!ObjCIdDecl) {
4620 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4621 T = getObjCObjectPointerType(T);
4622 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4623 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4624 getTranslationUnitDecl(),
4625 SourceLocation(), SourceLocation(),
4626 &Idents.get("id"), IdInfo);
4627 }
4628
4629 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00004630}
4631
Douglas Gregor7a27ea52011-08-12 06:17:30 +00004632TypedefDecl *ASTContext::getObjCSelDecl() const {
4633 if (!ObjCSelDecl) {
4634 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4635 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4636 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4637 getTranslationUnitDecl(),
4638 SourceLocation(), SourceLocation(),
4639 &Idents.get("SEL"), SelInfo);
4640 }
4641 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004642}
4643
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004644void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004645 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00004646}
4647
Douglas Gregor79d67262011-08-12 05:59:41 +00004648TypedefDecl *ASTContext::getObjCClassDecl() const {
4649 if (!ObjCClassDecl) {
4650 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4651 T = getObjCObjectPointerType(T);
4652 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4653 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4654 getTranslationUnitDecl(),
4655 SourceLocation(), SourceLocation(),
4656 &Idents.get("Class"), ClassInfo);
4657 }
4658
4659 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004660}
4661
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004662void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004663 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004664 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004665
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004666 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004667}
4668
John McCall0bd6feb2009-12-02 08:04:21 +00004669/// \brief Retrieve the template name that corresponds to a non-empty
4670/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00004671TemplateName
4672ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4673 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00004674 unsigned size = End - Begin;
4675 assert(size > 1 && "set is not overloaded!");
4676
4677 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4678 size * sizeof(FunctionTemplateDecl*));
4679 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4680
4681 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004682 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004683 NamedDecl *D = *I;
4684 assert(isa<FunctionTemplateDecl>(D) ||
4685 (isa<UsingShadowDecl>(D) &&
4686 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4687 *Storage++ = D;
4688 }
4689
4690 return TemplateName(OT);
4691}
4692
Douglas Gregor7532dc62009-03-30 22:58:21 +00004693/// \brief Retrieve the template name that represents a qualified
4694/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00004695TemplateName
4696ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4697 bool TemplateKeyword,
4698 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00004699 assert(NNS && "Missing nested-name-specifier in qualified template name");
4700
Douglas Gregor789b1f62010-02-04 18:10:26 +00004701 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004702 llvm::FoldingSetNodeID ID;
4703 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4704
4705 void *InsertPos = 0;
4706 QualifiedTemplateName *QTN =
4707 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4708 if (!QTN) {
4709 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4710 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4711 }
4712
4713 return TemplateName(QTN);
4714}
4715
4716/// \brief Retrieve the template name that represents a dependent
4717/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00004718TemplateName
4719ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4720 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004721 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004722 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004723
4724 llvm::FoldingSetNodeID ID;
4725 DependentTemplateName::Profile(ID, NNS, Name);
4726
4727 void *InsertPos = 0;
4728 DependentTemplateName *QTN =
4729 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4730
4731 if (QTN)
4732 return TemplateName(QTN);
4733
4734 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4735 if (CanonNNS == NNS) {
4736 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4737 } else {
4738 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4739 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004740 DependentTemplateName *CheckQTN =
4741 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4742 assert(!CheckQTN && "Dependent type name canonicalization broken");
4743 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004744 }
4745
4746 DependentTemplateNames.InsertNode(QTN, InsertPos);
4747 return TemplateName(QTN);
4748}
4749
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004750/// \brief Retrieve the template name that represents a dependent
4751/// template name such as \c MetaFun::template operator+.
4752TemplateName
4753ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00004754 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004755 assert((!NNS || NNS->isDependent()) &&
4756 "Nested name specifier must be dependent");
4757
4758 llvm::FoldingSetNodeID ID;
4759 DependentTemplateName::Profile(ID, NNS, Operator);
4760
4761 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004762 DependentTemplateName *QTN
4763 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004764
4765 if (QTN)
4766 return TemplateName(QTN);
4767
4768 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4769 if (CanonNNS == NNS) {
4770 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4771 } else {
4772 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4773 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004774
4775 DependentTemplateName *CheckQTN
4776 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4777 assert(!CheckQTN && "Dependent template name canonicalization broken");
4778 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004779 }
4780
4781 DependentTemplateNames.InsertNode(QTN, InsertPos);
4782 return TemplateName(QTN);
4783}
4784
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004785TemplateName
John McCall14606042011-06-30 08:33:18 +00004786ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
4787 TemplateName replacement) const {
4788 llvm::FoldingSetNodeID ID;
4789 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
4790
4791 void *insertPos = 0;
4792 SubstTemplateTemplateParmStorage *subst
4793 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
4794
4795 if (!subst) {
4796 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
4797 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
4798 }
4799
4800 return TemplateName(subst);
4801}
4802
4803TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004804ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4805 const TemplateArgument &ArgPack) const {
4806 ASTContext &Self = const_cast<ASTContext &>(*this);
4807 llvm::FoldingSetNodeID ID;
4808 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4809
4810 void *InsertPos = 0;
4811 SubstTemplateTemplateParmPackStorage *Subst
4812 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4813
4814 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00004815 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004816 ArgPack.pack_size(),
4817 ArgPack.pack_begin());
4818 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4819 }
4820
4821 return TemplateName(Subst);
4822}
4823
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004824/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004825/// TargetInfo, produce the corresponding type. The unsigned @p Type
4826/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004827CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004828 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004829 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004830 case TargetInfo::SignedShort: return ShortTy;
4831 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4832 case TargetInfo::SignedInt: return IntTy;
4833 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4834 case TargetInfo::SignedLong: return LongTy;
4835 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4836 case TargetInfo::SignedLongLong: return LongLongTy;
4837 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4838 }
4839
4840 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004841 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004842}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004843
4844//===----------------------------------------------------------------------===//
4845// Type Predicates.
4846//===----------------------------------------------------------------------===//
4847
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004848/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4849/// garbage collection attribute.
4850///
John McCallae278a32011-01-12 00:34:59 +00004851Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4852 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4853 return Qualifiers::GCNone;
4854
4855 assert(getLangOptions().ObjC1);
4856 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4857
4858 // Default behaviour under objective-C's gc is for ObjC pointers
4859 // (or pointers to them) be treated as though they were declared
4860 // as __strong.
4861 if (GCAttrs == Qualifiers::GCNone) {
4862 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4863 return Qualifiers::Strong;
4864 else if (Ty->isPointerType())
4865 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4866 } else {
4867 // It's not valid to set GC attributes on anything that isn't a
4868 // pointer.
4869#ifndef NDEBUG
4870 QualType CT = Ty->getCanonicalTypeInternal();
4871 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4872 CT = AT->getElementType();
4873 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4874#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004875 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004876 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004877}
4878
Chris Lattner6ac46a42008-04-07 06:51:04 +00004879//===----------------------------------------------------------------------===//
4880// Type Compatibility Testing
4881//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004882
Mike Stump1eb44332009-09-09 15:08:12 +00004883/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004884/// compatible.
4885static bool areCompatVectorTypes(const VectorType *LHS,
4886 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004887 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004888 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004889 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004890}
4891
Douglas Gregor255210e2010-08-06 10:14:59 +00004892bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4893 QualType SecondVec) {
4894 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4895 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4896
4897 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4898 return true;
4899
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004900 // Treat Neon vector types and most AltiVec vector types as if they are the
4901 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00004902 const VectorType *First = FirstVec->getAs<VectorType>();
4903 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004904 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00004905 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004906 First->getVectorKind() != VectorType::AltiVecPixel &&
4907 First->getVectorKind() != VectorType::AltiVecBool &&
4908 Second->getVectorKind() != VectorType::AltiVecPixel &&
4909 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00004910 return true;
4911
4912 return false;
4913}
4914
Steve Naroff4084c302009-07-23 01:01:38 +00004915//===----------------------------------------------------------------------===//
4916// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4917//===----------------------------------------------------------------------===//
4918
4919/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4920/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00004921bool
4922ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4923 ObjCProtocolDecl *rProto) const {
Steve Naroff4084c302009-07-23 01:01:38 +00004924 if (lProto == rProto)
4925 return true;
4926 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4927 E = rProto->protocol_end(); PI != E; ++PI)
4928 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4929 return true;
4930 return false;
4931}
4932
Steve Naroff4084c302009-07-23 01:01:38 +00004933/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4934/// return true if lhs's protocols conform to rhs's protocol; false
4935/// otherwise.
4936bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4937 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4938 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4939 return false;
4940}
4941
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004942/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4943/// Class<p1, ...>.
4944bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4945 QualType rhs) {
4946 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4947 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4948 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4949
4950 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4951 E = lhsQID->qual_end(); I != E; ++I) {
4952 bool match = false;
4953 ObjCProtocolDecl *lhsProto = *I;
4954 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4955 E = rhsOPT->qual_end(); J != E; ++J) {
4956 ObjCProtocolDecl *rhsProto = *J;
4957 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4958 match = true;
4959 break;
4960 }
4961 }
4962 if (!match)
4963 return false;
4964 }
4965 return true;
4966}
4967
Steve Naroff4084c302009-07-23 01:01:38 +00004968/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4969/// ObjCQualifiedIDType.
4970bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4971 bool compare) {
4972 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004973 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004974 lhs->isObjCIdType() || lhs->isObjCClassType())
4975 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004976 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004977 rhs->isObjCIdType() || rhs->isObjCClassType())
4978 return true;
4979
4980 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004981 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004982
Steve Naroff4084c302009-07-23 01:01:38 +00004983 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004984
Steve Naroff4084c302009-07-23 01:01:38 +00004985 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004986 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004987 // make sure we check the class hierarchy.
4988 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4989 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4990 E = lhsQID->qual_end(); I != E; ++I) {
4991 // when comparing an id<P> on lhs with a static type on rhs,
4992 // see if static class implements all of id's protocols, directly or
4993 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004994 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004995 return false;
4996 }
4997 }
4998 // If there are no qualifiers and no interface, we have an 'id'.
4999 return true;
5000 }
Mike Stump1eb44332009-09-09 15:08:12 +00005001 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005002 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5003 E = lhsQID->qual_end(); I != E; ++I) {
5004 ObjCProtocolDecl *lhsProto = *I;
5005 bool match = false;
5006
5007 // when comparing an id<P> on lhs with a static type on rhs,
5008 // see if static class implements all of id's protocols, directly or
5009 // through its super class and categories.
5010 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5011 E = rhsOPT->qual_end(); J != E; ++J) {
5012 ObjCProtocolDecl *rhsProto = *J;
5013 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5014 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5015 match = true;
5016 break;
5017 }
5018 }
Mike Stump1eb44332009-09-09 15:08:12 +00005019 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00005020 // make sure we check the class hierarchy.
5021 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5022 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5023 E = lhsQID->qual_end(); I != E; ++I) {
5024 // when comparing an id<P> on lhs with a static type on rhs,
5025 // see if static class implements all of id's protocols, directly or
5026 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005027 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00005028 match = true;
5029 break;
5030 }
5031 }
5032 }
5033 if (!match)
5034 return false;
5035 }
Mike Stump1eb44332009-09-09 15:08:12 +00005036
Steve Naroff4084c302009-07-23 01:01:38 +00005037 return true;
5038 }
Mike Stump1eb44332009-09-09 15:08:12 +00005039
Steve Naroff4084c302009-07-23 01:01:38 +00005040 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5041 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5042
Mike Stump1eb44332009-09-09 15:08:12 +00005043 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00005044 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005045 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005046 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5047 E = lhsOPT->qual_end(); I != E; ++I) {
5048 ObjCProtocolDecl *lhsProto = *I;
5049 bool match = false;
5050
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005051 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00005052 // see if static class implements all of id's protocols, directly or
5053 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005054 // First, lhs protocols in the qualifier list must be found, direct
5055 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00005056 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5057 E = rhsQID->qual_end(); J != E; ++J) {
5058 ObjCProtocolDecl *rhsProto = *J;
5059 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5060 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5061 match = true;
5062 break;
5063 }
5064 }
5065 if (!match)
5066 return false;
5067 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005068
5069 // Static class's protocols, or its super class or category protocols
5070 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5071 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5072 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5073 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5074 // This is rather dubious but matches gcc's behavior. If lhs has
5075 // no type qualifier and its class has no static protocol(s)
5076 // assume that it is mismatch.
5077 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5078 return false;
5079 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5080 LHSInheritedProtocols.begin(),
5081 E = LHSInheritedProtocols.end(); I != E; ++I) {
5082 bool match = false;
5083 ObjCProtocolDecl *lhsProto = (*I);
5084 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5085 E = rhsQID->qual_end(); J != E; ++J) {
5086 ObjCProtocolDecl *rhsProto = *J;
5087 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5088 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5089 match = true;
5090 break;
5091 }
5092 }
5093 if (!match)
5094 return false;
5095 }
5096 }
Steve Naroff4084c302009-07-23 01:01:38 +00005097 return true;
5098 }
5099 return false;
5100}
5101
Eli Friedman3d815e72008-08-22 00:56:42 +00005102/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005103/// compatible for assignment from RHS to LHS. This handles validation of any
5104/// protocol qualifiers on the LHS or RHS.
5105///
Steve Naroff14108da2009-07-10 23:34:53 +00005106bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5107 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00005108 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5109 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5110
Steve Naroffde2e22d2009-07-15 18:40:39 +00005111 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00005112 if (LHS->isObjCUnqualifiedIdOrClass() ||
5113 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00005114 return true;
5115
John McCallc12c5bb2010-05-15 11:32:37 +00005116 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00005117 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5118 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00005119 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005120
5121 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5122 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5123 QualType(RHSOPT,0));
5124
John McCallc12c5bb2010-05-15 11:32:37 +00005125 // If we have 2 user-defined types, fall into that path.
5126 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00005127 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00005128
Steve Naroff4084c302009-07-23 01:01:38 +00005129 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005130}
5131
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005132/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00005133/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005134/// arguments in block literals. When passed as arguments, passing 'A*' where
5135/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5136/// not OK. For the return type, the opposite is not OK.
5137bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5138 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005139 const ObjCObjectPointerType *RHSOPT,
5140 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005141 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005142 return true;
5143
5144 if (LHSOPT->isObjCBuiltinType()) {
5145 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5146 }
5147
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005148 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005149 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5150 QualType(RHSOPT,0),
5151 false);
5152
5153 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5154 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5155 if (LHS && RHS) { // We have 2 user-defined types.
5156 if (LHS != RHS) {
5157 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005158 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005159 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005160 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005161 }
5162 else
5163 return true;
5164 }
5165 return false;
5166}
5167
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005168/// getIntersectionOfProtocols - This routine finds the intersection of set
5169/// of protocols inherited from two distinct objective-c pointer objects.
5170/// It is used to build composite qualifier list of the composite type of
5171/// the conditional expression involving two objective-c pointer objects.
5172static
5173void getIntersectionOfProtocols(ASTContext &Context,
5174 const ObjCObjectPointerType *LHSOPT,
5175 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005176 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005177
John McCallc12c5bb2010-05-15 11:32:37 +00005178 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5179 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5180 assert(LHS->getInterface() && "LHS must have an interface base");
5181 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005182
5183 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5184 unsigned LHSNumProtocols = LHS->getNumProtocols();
5185 if (LHSNumProtocols > 0)
5186 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5187 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005188 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005189 Context.CollectInheritedProtocols(LHS->getInterface(),
5190 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005191 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5192 LHSInheritedProtocols.end());
5193 }
5194
5195 unsigned RHSNumProtocols = RHS->getNumProtocols();
5196 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00005197 ObjCProtocolDecl **RHSProtocols =
5198 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005199 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5200 if (InheritedProtocolSet.count(RHSProtocols[i]))
5201 IntersectionOfProtocols.push_back(RHSProtocols[i]);
5202 }
5203 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005204 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005205 Context.CollectInheritedProtocols(RHS->getInterface(),
5206 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005207 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5208 RHSInheritedProtocols.begin(),
5209 E = RHSInheritedProtocols.end(); I != E; ++I)
5210 if (InheritedProtocolSet.count((*I)))
5211 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005212 }
5213}
5214
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005215/// areCommonBaseCompatible - Returns common base class of the two classes if
5216/// one found. Note that this is O'2 algorithm. But it will be called as the
5217/// last type comparison in a ?-exp of ObjC pointer types before a
5218/// warning is issued. So, its invokation is extremely rare.
5219QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00005220 const ObjCObjectPointerType *Lptr,
5221 const ObjCObjectPointerType *Rptr) {
5222 const ObjCObjectType *LHS = Lptr->getObjectType();
5223 const ObjCObjectType *RHS = Rptr->getObjectType();
5224 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5225 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005226 if (!LDecl || !RDecl || (LDecl == RDecl))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005227 return QualType();
5228
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005229 do {
John McCallc12c5bb2010-05-15 11:32:37 +00005230 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005231 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005232 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005233 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5234
5235 QualType Result = QualType(LHS, 0);
5236 if (!Protocols.empty())
5237 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5238 Result = getObjCObjectPointerType(Result);
5239 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005240 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005241 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005242
5243 return QualType();
5244}
5245
John McCallc12c5bb2010-05-15 11:32:37 +00005246bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5247 const ObjCObjectType *RHS) {
5248 assert(LHS->getInterface() && "LHS is not an interface type");
5249 assert(RHS->getInterface() && "RHS is not an interface type");
5250
Chris Lattner6ac46a42008-04-07 06:51:04 +00005251 // Verify that the base decls are compatible: the RHS must be a subclass of
5252 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00005253 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00005254 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005255
Chris Lattner6ac46a42008-04-07 06:51:04 +00005256 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5257 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00005258 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00005259 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005260
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005261 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5262 // more detailed analysis is required.
5263 if (RHS->getNumProtocols() == 0) {
5264 // OK, if LHS is a superclass of RHS *and*
5265 // this superclass is assignment compatible with LHS.
5266 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005267 bool IsSuperClass =
5268 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5269 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005270 // OK if conversion of LHS to SuperClass results in narrowing of types
5271 // ; i.e., SuperClass may implement at least one of the protocols
5272 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5273 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5274 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005275 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005276 // If super class has no protocols, it is not a match.
5277 if (SuperClassInheritedProtocols.empty())
5278 return false;
5279
5280 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5281 LHSPE = LHS->qual_end();
5282 LHSPI != LHSPE; LHSPI++) {
5283 bool SuperImplementsProtocol = false;
5284 ObjCProtocolDecl *LHSProto = (*LHSPI);
5285
5286 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5287 SuperClassInheritedProtocols.begin(),
5288 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5289 ObjCProtocolDecl *SuperClassProto = (*I);
5290 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5291 SuperImplementsProtocol = true;
5292 break;
5293 }
5294 }
5295 if (!SuperImplementsProtocol)
5296 return false;
5297 }
5298 return true;
5299 }
5300 return false;
5301 }
Mike Stump1eb44332009-09-09 15:08:12 +00005302
John McCallc12c5bb2010-05-15 11:32:37 +00005303 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5304 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005305 LHSPI != LHSPE; LHSPI++) {
5306 bool RHSImplementsProtocol = false;
5307
5308 // If the RHS doesn't implement the protocol on the left, the types
5309 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00005310 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5311 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00005312 RHSPI != RHSPE; RHSPI++) {
5313 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005314 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00005315 break;
5316 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005317 }
5318 // FIXME: For better diagnostics, consider passing back the protocol name.
5319 if (!RHSImplementsProtocol)
5320 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005321 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005322 // The RHS implements all protocols listed on the LHS.
5323 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005324}
5325
Steve Naroff389bf462009-02-12 17:52:19 +00005326bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5327 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00005328 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5329 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005330
Steve Naroff14108da2009-07-10 23:34:53 +00005331 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00005332 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005333
5334 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5335 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00005336}
5337
Douglas Gregor569c3162010-08-07 11:51:51 +00005338bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5339 return canAssignObjCInterfaces(
5340 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5341 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5342}
5343
Mike Stump1eb44332009-09-09 15:08:12 +00005344/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00005345/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00005346/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00005347/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00005348bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5349 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005350 if (getLangOptions().CPlusPlus)
5351 return hasSameType(LHS, RHS);
5352
Douglas Gregor447234d2010-07-29 15:18:02 +00005353 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00005354}
5355
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005356bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00005357 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005358}
5359
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005360bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5361 return !mergeTypes(LHS, RHS, true).isNull();
5362}
5363
Peter Collingbourne48466752010-10-24 18:30:18 +00005364/// mergeTransparentUnionType - if T is a transparent union type and a member
5365/// of T is compatible with SubType, return the merged type, else return
5366/// QualType()
5367QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5368 bool OfBlockPointer,
5369 bool Unqualified) {
5370 if (const RecordType *UT = T->getAsUnionType()) {
5371 RecordDecl *UD = UT->getDecl();
5372 if (UD->hasAttr<TransparentUnionAttr>()) {
5373 for (RecordDecl::field_iterator it = UD->field_begin(),
5374 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00005375 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005376 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5377 if (!MT.isNull())
5378 return MT;
5379 }
5380 }
5381 }
5382
5383 return QualType();
5384}
5385
5386/// mergeFunctionArgumentTypes - merge two types which appear as function
5387/// argument types
5388QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5389 bool OfBlockPointer,
5390 bool Unqualified) {
5391 // GNU extension: two types are compatible if they appear as a function
5392 // argument, one of the types is a transparent union type and the other
5393 // type is compatible with a union member
5394 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5395 Unqualified);
5396 if (!lmerge.isNull())
5397 return lmerge;
5398
5399 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5400 Unqualified);
5401 if (!rmerge.isNull())
5402 return rmerge;
5403
5404 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5405}
5406
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005407QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00005408 bool OfBlockPointer,
5409 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00005410 const FunctionType *lbase = lhs->getAs<FunctionType>();
5411 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00005412 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5413 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00005414 bool allLTypes = true;
5415 bool allRTypes = true;
5416
5417 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005418 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005419 if (OfBlockPointer) {
5420 QualType RHS = rbase->getResultType();
5421 QualType LHS = lbase->getResultType();
5422 bool UnqualifiedResult = Unqualified;
5423 if (!UnqualifiedResult)
5424 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005425 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005426 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005427 else
John McCall8cc246c2010-12-15 01:06:38 +00005428 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5429 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005430 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005431
5432 if (Unqualified)
5433 retType = retType.getUnqualifiedType();
5434
5435 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5436 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5437 if (Unqualified) {
5438 LRetType = LRetType.getUnqualifiedType();
5439 RRetType = RRetType.getUnqualifiedType();
5440 }
5441
5442 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005443 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00005444 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005445 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005446
Daniel Dunbar6a15c852010-04-28 16:20:58 +00005447 // FIXME: double check this
5448 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5449 // rbase->getRegParmAttr() != 0 &&
5450 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00005451 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5452 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00005453
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005454 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00005455 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005456 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005457
John McCall8cc246c2010-12-15 01:06:38 +00005458 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00005459 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5460 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00005461 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5462 return QualType();
5463
John McCallf85e1932011-06-15 23:02:42 +00005464 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5465 return QualType();
5466
John McCall8cc246c2010-12-15 01:06:38 +00005467 // It's noreturn if either type is.
5468 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5469 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5470 if (NoReturn != lbaseInfo.getNoReturn())
5471 allLTypes = false;
5472 if (NoReturn != rbaseInfo.getNoReturn())
5473 allRTypes = false;
5474
John McCallf85e1932011-06-15 23:02:42 +00005475 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00005476
Eli Friedman3d815e72008-08-22 00:56:42 +00005477 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00005478 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5479 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005480 unsigned lproto_nargs = lproto->getNumArgs();
5481 unsigned rproto_nargs = rproto->getNumArgs();
5482
5483 // Compatible functions must have the same number of arguments
5484 if (lproto_nargs != rproto_nargs)
5485 return QualType();
5486
5487 // Variadic and non-variadic functions aren't compatible
5488 if (lproto->isVariadic() != rproto->isVariadic())
5489 return QualType();
5490
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00005491 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5492 return QualType();
5493
Eli Friedman3d815e72008-08-22 00:56:42 +00005494 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00005495 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00005496 for (unsigned i = 0; i < lproto_nargs; i++) {
5497 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5498 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005499 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5500 OfBlockPointer,
5501 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005502 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005503
5504 if (Unqualified)
5505 argtype = argtype.getUnqualifiedType();
5506
Eli Friedman3d815e72008-08-22 00:56:42 +00005507 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00005508 if (Unqualified) {
5509 largtype = largtype.getUnqualifiedType();
5510 rargtype = rargtype.getUnqualifiedType();
5511 }
5512
Chris Lattner61710852008-10-05 17:34:18 +00005513 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5514 allLTypes = false;
5515 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5516 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00005517 }
5518 if (allLTypes) return lhs;
5519 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005520
5521 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5522 EPI.ExtInfo = einfo;
5523 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005524 }
5525
5526 if (lproto) allRTypes = false;
5527 if (rproto) allLTypes = false;
5528
Douglas Gregor72564e72009-02-26 23:50:07 +00005529 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00005530 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00005531 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005532 if (proto->isVariadic()) return QualType();
5533 // Check that the types are compatible with the types that
5534 // would result from default argument promotions (C99 6.7.5.3p15).
5535 // The only types actually affected are promotable integer
5536 // types and floats, which would be passed as a different
5537 // type depending on whether the prototype is visible.
5538 unsigned proto_nargs = proto->getNumArgs();
5539 for (unsigned i = 0; i < proto_nargs; ++i) {
5540 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00005541
5542 // Look at the promotion type of enum types, since that is the type used
5543 // to pass enum values.
5544 if (const EnumType *Enum = argTy->getAs<EnumType>())
5545 argTy = Enum->getDecl()->getPromotionType();
5546
Eli Friedman3d815e72008-08-22 00:56:42 +00005547 if (argTy->isPromotableIntegerType() ||
5548 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5549 return QualType();
5550 }
5551
5552 if (allLTypes) return lhs;
5553 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005554
5555 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5556 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00005557 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005558 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005559 }
5560
5561 if (allLTypes) return lhs;
5562 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00005563 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00005564}
5565
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005566QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00005567 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005568 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00005569 // C++ [expr]: If an expression initially has the type "reference to T", the
5570 // type is adjusted to "T" prior to any further analysis, the expression
5571 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005572 // expression is an lvalue unless the reference is an rvalue reference and
5573 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005574 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5575 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00005576
5577 if (Unqualified) {
5578 LHS = LHS.getUnqualifiedType();
5579 RHS = RHS.getUnqualifiedType();
5580 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005581
Eli Friedman3d815e72008-08-22 00:56:42 +00005582 QualType LHSCan = getCanonicalType(LHS),
5583 RHSCan = getCanonicalType(RHS);
5584
5585 // If two types are identical, they are compatible.
5586 if (LHSCan == RHSCan)
5587 return LHS;
5588
John McCall0953e762009-09-24 19:53:00 +00005589 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005590 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5591 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00005592 if (LQuals != RQuals) {
5593 // If any of these qualifiers are different, we have a type
5594 // mismatch.
5595 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00005596 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5597 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00005598 return QualType();
5599
5600 // Exactly one GC qualifier difference is allowed: __strong is
5601 // okay if the other type has no GC qualifier but is an Objective
5602 // C object pointer (i.e. implicitly strong by default). We fix
5603 // this by pretending that the unqualified type was actually
5604 // qualified __strong.
5605 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5606 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5607 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5608
5609 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5610 return QualType();
5611
5612 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5613 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5614 }
5615 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5616 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5617 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005618 return QualType();
John McCall0953e762009-09-24 19:53:00 +00005619 }
5620
5621 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00005622
Eli Friedman852d63b2009-06-01 01:22:52 +00005623 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5624 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00005625
Chris Lattner1adb8832008-01-14 05:45:46 +00005626 // We want to consider the two function types to be the same for these
5627 // comparisons, just force one to the other.
5628 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5629 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00005630
5631 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00005632 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5633 LHSClass = Type::ConstantArray;
5634 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5635 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00005636
John McCallc12c5bb2010-05-15 11:32:37 +00005637 // ObjCInterfaces are just specialized ObjCObjects.
5638 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5639 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5640
Nate Begeman213541a2008-04-18 23:10:10 +00005641 // Canonicalize ExtVector -> Vector.
5642 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5643 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00005644
Chris Lattnera36a61f2008-04-07 05:43:21 +00005645 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005646 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00005647 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00005648 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00005649 // Compatibility is based on the underlying type, not the promotion
5650 // type.
John McCall183700f2009-09-21 23:43:11 +00005651 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005652 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5653 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005654 }
John McCall183700f2009-09-21 23:43:11 +00005655 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005656 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5657 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005658 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005659
Eli Friedman3d815e72008-08-22 00:56:42 +00005660 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005661 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005662
Steve Naroff4a746782008-01-09 22:43:08 +00005663 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005664 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00005665#define TYPE(Class, Base)
5666#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00005667#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00005668#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5669#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5670#include "clang/AST/TypeNodes.def"
5671 assert(false && "Non-canonical and dependent types shouldn't get here");
5672 return QualType();
5673
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005674 case Type::LValueReference:
5675 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00005676 case Type::MemberPointer:
5677 assert(false && "C++ should never be in mergeTypes");
5678 return QualType();
5679
John McCallc12c5bb2010-05-15 11:32:37 +00005680 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00005681 case Type::IncompleteArray:
5682 case Type::VariableArray:
5683 case Type::FunctionProto:
5684 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00005685 assert(false && "Types are eliminated above");
5686 return QualType();
5687
Chris Lattner1adb8832008-01-14 05:45:46 +00005688 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00005689 {
5690 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005691 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5692 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005693 if (Unqualified) {
5694 LHSPointee = LHSPointee.getUnqualifiedType();
5695 RHSPointee = RHSPointee.getUnqualifiedType();
5696 }
5697 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5698 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005699 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00005700 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005701 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00005702 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005703 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005704 return getPointerType(ResultType);
5705 }
Steve Naroffc0febd52008-12-10 17:49:55 +00005706 case Type::BlockPointer:
5707 {
5708 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005709 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5710 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005711 if (Unqualified) {
5712 LHSPointee = LHSPointee.getUnqualifiedType();
5713 RHSPointee = RHSPointee.getUnqualifiedType();
5714 }
5715 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5716 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00005717 if (ResultType.isNull()) return QualType();
5718 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5719 return LHS;
5720 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5721 return RHS;
5722 return getBlockPointerType(ResultType);
5723 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005724 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00005725 {
5726 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5727 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5728 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5729 return QualType();
5730
5731 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5732 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005733 if (Unqualified) {
5734 LHSElem = LHSElem.getUnqualifiedType();
5735 RHSElem = RHSElem.getUnqualifiedType();
5736 }
5737
5738 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005739 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00005740 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5741 return LHS;
5742 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5743 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00005744 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5745 ArrayType::ArraySizeModifier(), 0);
5746 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5747 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005748 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5749 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00005750 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5751 return LHS;
5752 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5753 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005754 if (LVAT) {
5755 // FIXME: This isn't correct! But tricky to implement because
5756 // the array's size has to be the size of LHS, but the type
5757 // has to be different.
5758 return LHS;
5759 }
5760 if (RVAT) {
5761 // FIXME: This isn't correct! But tricky to implement because
5762 // the array's size has to be the size of RHS, but the type
5763 // has to be different.
5764 return RHS;
5765 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00005766 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5767 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00005768 return getIncompleteArrayType(ResultType,
5769 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005770 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005771 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00005772 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00005773 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00005774 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00005775 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00005776 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005777 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00005778 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00005779 case Type::Complex:
5780 // Distinct complex types are incompatible.
5781 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005782 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005783 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00005784 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5785 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005786 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00005787 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00005788 case Type::ObjCObject: {
5789 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005790 // FIXME: This should be type compatibility, e.g. whether
5791 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00005792 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5793 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5794 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00005795 return LHS;
5796
Eli Friedman3d815e72008-08-22 00:56:42 +00005797 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00005798 }
Steve Naroff14108da2009-07-10 23:34:53 +00005799 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005800 if (OfBlockPointer) {
5801 if (canAssignObjCInterfacesInBlockPointer(
5802 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005803 RHS->getAs<ObjCObjectPointerType>(),
5804 BlockReturnType))
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005805 return LHS;
5806 return QualType();
5807 }
John McCall183700f2009-09-21 23:43:11 +00005808 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5809 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00005810 return LHS;
5811
Steve Naroffbc76dd02008-12-10 22:14:21 +00005812 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005813 }
Steve Naroffec0550f2007-10-15 20:41:53 +00005814 }
Douglas Gregor72564e72009-02-26 23:50:07 +00005815
5816 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005817}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00005818
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005819/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5820/// 'RHS' attributes and returns the merged version; including for function
5821/// return types.
5822QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5823 QualType LHSCan = getCanonicalType(LHS),
5824 RHSCan = getCanonicalType(RHS);
5825 // If two types are identical, they are compatible.
5826 if (LHSCan == RHSCan)
5827 return LHS;
5828 if (RHSCan->isFunctionType()) {
5829 if (!LHSCan->isFunctionType())
5830 return QualType();
5831 QualType OldReturnType =
5832 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5833 QualType NewReturnType =
5834 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5835 QualType ResReturnType =
5836 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5837 if (ResReturnType.isNull())
5838 return QualType();
5839 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5840 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5841 // In either case, use OldReturnType to build the new function type.
5842 const FunctionType *F = LHS->getAs<FunctionType>();
5843 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00005844 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5845 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005846 QualType ResultType
5847 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005848 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005849 return ResultType;
5850 }
5851 }
5852 return QualType();
5853 }
5854
5855 // If the qualifiers are different, the types can still be merged.
5856 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5857 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5858 if (LQuals != RQuals) {
5859 // If any of these qualifiers are different, we have a type mismatch.
5860 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5861 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5862 return QualType();
5863
5864 // Exactly one GC qualifier difference is allowed: __strong is
5865 // okay if the other type has no GC qualifier but is an Objective
5866 // C object pointer (i.e. implicitly strong by default). We fix
5867 // this by pretending that the unqualified type was actually
5868 // qualified __strong.
5869 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5870 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5871 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5872
5873 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5874 return QualType();
5875
5876 if (GC_L == Qualifiers::Strong)
5877 return LHS;
5878 if (GC_R == Qualifiers::Strong)
5879 return RHS;
5880 return QualType();
5881 }
5882
5883 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5884 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5885 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5886 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5887 if (ResQT == LHSBaseQT)
5888 return LHS;
5889 if (ResQT == RHSBaseQT)
5890 return RHS;
5891 }
5892 return QualType();
5893}
5894
Chris Lattner5426bf62008-04-07 07:01:58 +00005895//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00005896// Integer Predicates
5897//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00005898
Jay Foad4ba2a172011-01-12 09:06:06 +00005899unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00005900 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00005901 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005902 if (T->isBooleanType())
5903 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00005904 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00005905 return (unsigned)getTypeSize(T);
5906}
5907
5908QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00005909 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00005910
5911 // Turn <4 x signed int> -> <4 x unsigned int>
5912 if (const VectorType *VTy = T->getAs<VectorType>())
5913 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00005914 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00005915
5916 // For enums, we return the unsigned version of the base type.
5917 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00005918 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00005919
5920 const BuiltinType *BTy = T->getAs<BuiltinType>();
5921 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00005922 switch (BTy->getKind()) {
5923 case BuiltinType::Char_S:
5924 case BuiltinType::SChar:
5925 return UnsignedCharTy;
5926 case BuiltinType::Short:
5927 return UnsignedShortTy;
5928 case BuiltinType::Int:
5929 return UnsignedIntTy;
5930 case BuiltinType::Long:
5931 return UnsignedLongTy;
5932 case BuiltinType::LongLong:
5933 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00005934 case BuiltinType::Int128:
5935 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00005936 default:
5937 assert(0 && "Unexpected signed integer type");
5938 return QualType();
5939 }
5940}
5941
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00005942ASTMutationListener::~ASTMutationListener() { }
5943
Chris Lattner86df27b2009-06-14 00:45:47 +00005944
5945//===----------------------------------------------------------------------===//
5946// Builtin Type Computation
5947//===----------------------------------------------------------------------===//
5948
5949/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00005950/// pointer over the consumed characters. This returns the resultant type. If
5951/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5952/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5953/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00005954///
5955/// RequiresICE is filled in on return to indicate whether the value is required
5956/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00005957static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00005958 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00005959 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00005960 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00005961 // Modifiers.
5962 int HowLong = 0;
5963 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00005964 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005965
Chris Lattner33daae62010-10-01 22:42:38 +00005966 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00005967 bool Done = false;
5968 while (!Done) {
5969 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00005970 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005971 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00005972 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005973 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005974 case 'S':
5975 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5976 assert(!Signed && "Can't use 'S' modifier multiple times!");
5977 Signed = true;
5978 break;
5979 case 'U':
5980 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5981 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5982 Unsigned = true;
5983 break;
5984 case 'L':
5985 assert(HowLong <= 2 && "Can't have LLLL modifier");
5986 ++HowLong;
5987 break;
5988 }
5989 }
5990
5991 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005992
Chris Lattner86df27b2009-06-14 00:45:47 +00005993 // Read the base type.
5994 switch (*Str++) {
5995 default: assert(0 && "Unknown builtin type letter!");
5996 case 'v':
5997 assert(HowLong == 0 && !Signed && !Unsigned &&
5998 "Bad modifiers used with 'v'!");
5999 Type = Context.VoidTy;
6000 break;
6001 case 'f':
6002 assert(HowLong == 0 && !Signed && !Unsigned &&
6003 "Bad modifiers used with 'f'!");
6004 Type = Context.FloatTy;
6005 break;
6006 case 'd':
6007 assert(HowLong < 2 && !Signed && !Unsigned &&
6008 "Bad modifiers used with 'd'!");
6009 if (HowLong)
6010 Type = Context.LongDoubleTy;
6011 else
6012 Type = Context.DoubleTy;
6013 break;
6014 case 's':
6015 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6016 if (Unsigned)
6017 Type = Context.UnsignedShortTy;
6018 else
6019 Type = Context.ShortTy;
6020 break;
6021 case 'i':
6022 if (HowLong == 3)
6023 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6024 else if (HowLong == 2)
6025 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6026 else if (HowLong == 1)
6027 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6028 else
6029 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6030 break;
6031 case 'c':
6032 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6033 if (Signed)
6034 Type = Context.SignedCharTy;
6035 else if (Unsigned)
6036 Type = Context.UnsignedCharTy;
6037 else
6038 Type = Context.CharTy;
6039 break;
6040 case 'b': // boolean
6041 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6042 Type = Context.BoolTy;
6043 break;
6044 case 'z': // size_t.
6045 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6046 Type = Context.getSizeType();
6047 break;
6048 case 'F':
6049 Type = Context.getCFConstantStringType();
6050 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00006051 case 'G':
6052 Type = Context.getObjCIdType();
6053 break;
6054 case 'H':
6055 Type = Context.getObjCSelType();
6056 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006057 case 'a':
6058 Type = Context.getBuiltinVaListType();
6059 assert(!Type.isNull() && "builtin va list type not initialized!");
6060 break;
6061 case 'A':
6062 // This is a "reference" to a va_list; however, what exactly
6063 // this means depends on how va_list is defined. There are two
6064 // different kinds of va_list: ones passed by value, and ones
6065 // passed by reference. An example of a by-value va_list is
6066 // x86, where va_list is a char*. An example of by-ref va_list
6067 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6068 // we want this argument to be a char*&; for x86-64, we want
6069 // it to be a __va_list_tag*.
6070 Type = Context.getBuiltinVaListType();
6071 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00006072 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00006073 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00006074 else
Chris Lattner86df27b2009-06-14 00:45:47 +00006075 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00006076 break;
6077 case 'V': {
6078 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00006079 unsigned NumElements = strtoul(Str, &End, 10);
6080 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00006081 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00006082
Chris Lattner14e0e742010-10-01 22:53:11 +00006083 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6084 RequiresICE, false);
6085 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00006086
6087 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00006088 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00006089 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00006090 break;
6091 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00006092 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00006093 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6094 false);
6095 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00006096 Type = Context.getComplexType(ElementType);
6097 break;
6098 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006099 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00006100 Type = Context.getFILEType();
6101 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006102 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00006103 return QualType();
6104 }
Mike Stumpfd612db2009-07-28 23:47:15 +00006105 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006106 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00006107 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00006108 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00006109 else
6110 Type = Context.getjmp_bufType();
6111
Mike Stumpfd612db2009-07-28 23:47:15 +00006112 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006113 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00006114 return QualType();
6115 }
6116 break;
Mike Stump782fa302009-07-28 02:25:19 +00006117 }
Mike Stump1eb44332009-09-09 15:08:12 +00006118
Chris Lattner33daae62010-10-01 22:42:38 +00006119 // If there are modifiers and if we're allowed to parse them, go for it.
6120 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00006121 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00006122 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00006123 default: Done = true; --Str; break;
6124 case '*':
6125 case '&': {
6126 // Both pointers and references can have their pointee types
6127 // qualified with an address space.
6128 char *End;
6129 unsigned AddrSpace = strtoul(Str, &End, 10);
6130 if (End != Str && AddrSpace != 0) {
6131 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6132 Str = End;
6133 }
6134 if (c == '*')
6135 Type = Context.getPointerType(Type);
6136 else
6137 Type = Context.getLValueReferenceType(Type);
6138 break;
6139 }
6140 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6141 case 'C':
6142 Type = Type.withConst();
6143 break;
6144 case 'D':
6145 Type = Context.getVolatileType(Type);
6146 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006147 }
6148 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00006149
Chris Lattner14e0e742010-10-01 22:53:11 +00006150 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00006151 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00006152
Chris Lattner86df27b2009-06-14 00:45:47 +00006153 return Type;
6154}
6155
6156/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00006157QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00006158 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00006159 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00006160 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00006161
Chris Lattner5f9e2722011-07-23 10:55:15 +00006162 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00006163
Chris Lattner14e0e742010-10-01 22:53:11 +00006164 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00006165 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00006166 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6167 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006168 if (Error != GE_None)
6169 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00006170
6171 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6172
Chris Lattner86df27b2009-06-14 00:45:47 +00006173 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00006174 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006175 if (Error != GE_None)
6176 return QualType();
6177
Chris Lattner14e0e742010-10-01 22:53:11 +00006178 // If this argument is required to be an IntegerConstantExpression and the
6179 // caller cares, fill in the bitmask we return.
6180 if (RequiresICE && IntegerConstantArgs)
6181 *IntegerConstantArgs |= 1 << ArgTypes.size();
6182
Chris Lattner86df27b2009-06-14 00:45:47 +00006183 // Do array -> pointer decay. The builtin should use the decayed type.
6184 if (Ty->isArrayType())
6185 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00006186
Chris Lattner86df27b2009-06-14 00:45:47 +00006187 ArgTypes.push_back(Ty);
6188 }
6189
6190 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6191 "'.' should only occur at end of builtin type list!");
6192
John McCall00ccbef2010-12-21 00:44:39 +00006193 FunctionType::ExtInfo EI;
6194 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6195
6196 bool Variadic = (TypeStr[0] == '.');
6197
6198 // We really shouldn't be making a no-proto type here, especially in C++.
6199 if (ArgTypes.empty() && Variadic)
6200 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00006201
John McCalle23cf432010-12-14 08:05:40 +00006202 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00006203 EPI.ExtInfo = EI;
6204 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00006205
6206 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00006207}
Eli Friedmana95d7572009-08-19 07:44:53 +00006208
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006209GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6210 GVALinkage External = GVA_StrongExternal;
6211
6212 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006213 switch (L) {
6214 case NoLinkage:
6215 case InternalLinkage:
6216 case UniqueExternalLinkage:
6217 return GVA_Internal;
6218
6219 case ExternalLinkage:
6220 switch (FD->getTemplateSpecializationKind()) {
6221 case TSK_Undeclared:
6222 case TSK_ExplicitSpecialization:
6223 External = GVA_StrongExternal;
6224 break;
6225
6226 case TSK_ExplicitInstantiationDefinition:
6227 return GVA_ExplicitTemplateInstantiation;
6228
6229 case TSK_ExplicitInstantiationDeclaration:
6230 case TSK_ImplicitInstantiation:
6231 External = GVA_TemplateInstantiation;
6232 break;
6233 }
6234 }
6235
6236 if (!FD->isInlined())
6237 return External;
6238
6239 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6240 // GNU or C99 inline semantics. Determine whether this symbol should be
6241 // externally visible.
6242 if (FD->isInlineDefinitionExternallyVisible())
6243 return External;
6244
6245 // C99 inline semantics, where the symbol is not externally visible.
6246 return GVA_C99Inline;
6247 }
6248
6249 // C++0x [temp.explicit]p9:
6250 // [ Note: The intent is that an inline function that is the subject of
6251 // an explicit instantiation declaration will still be implicitly
6252 // instantiated when used so that the body can be considered for
6253 // inlining, but that no out-of-line copy of the inline function would be
6254 // generated in the translation unit. -- end note ]
6255 if (FD->getTemplateSpecializationKind()
6256 == TSK_ExplicitInstantiationDeclaration)
6257 return GVA_C99Inline;
6258
6259 return GVA_CXXInline;
6260}
6261
6262GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6263 // If this is a static data member, compute the kind of template
6264 // specialization. Otherwise, this variable is not part of a
6265 // template.
6266 TemplateSpecializationKind TSK = TSK_Undeclared;
6267 if (VD->isStaticDataMember())
6268 TSK = VD->getTemplateSpecializationKind();
6269
6270 Linkage L = VD->getLinkage();
6271 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6272 VD->getType()->getLinkage() == UniqueExternalLinkage)
6273 L = UniqueExternalLinkage;
6274
6275 switch (L) {
6276 case NoLinkage:
6277 case InternalLinkage:
6278 case UniqueExternalLinkage:
6279 return GVA_Internal;
6280
6281 case ExternalLinkage:
6282 switch (TSK) {
6283 case TSK_Undeclared:
6284 case TSK_ExplicitSpecialization:
6285 return GVA_StrongExternal;
6286
6287 case TSK_ExplicitInstantiationDeclaration:
6288 llvm_unreachable("Variable should not be instantiated");
6289 // Fall through to treat this like any other instantiation.
6290
6291 case TSK_ExplicitInstantiationDefinition:
6292 return GVA_ExplicitTemplateInstantiation;
6293
6294 case TSK_ImplicitInstantiation:
6295 return GVA_TemplateInstantiation;
6296 }
6297 }
6298
6299 return GVA_StrongExternal;
6300}
6301
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00006302bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006303 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6304 if (!VD->isFileVarDecl())
6305 return false;
6306 } else if (!isa<FunctionDecl>(D))
6307 return false;
6308
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006309 // Weak references don't produce any output by themselves.
6310 if (D->hasAttr<WeakRefAttr>())
6311 return false;
6312
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006313 // Aliases and used decls are required.
6314 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6315 return true;
6316
6317 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6318 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00006319 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00006320 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006321
6322 // Constructors and destructors are required.
6323 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6324 return true;
6325
6326 // The key function for a class is required.
6327 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6328 const CXXRecordDecl *RD = MD->getParent();
6329 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6330 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6331 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6332 return true;
6333 }
6334 }
6335
6336 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6337
6338 // static, static inline, always_inline, and extern inline functions can
6339 // always be deferred. Normal inline functions can be deferred in C99/C++.
6340 // Implicit template instantiations can also be deferred in C++.
6341 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6342 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6343 return false;
6344 return true;
6345 }
6346
6347 const VarDecl *VD = cast<VarDecl>(D);
6348 assert(VD->isFileVarDecl() && "Expected file scoped var");
6349
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006350 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6351 return false;
6352
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006353 // Structs that have non-trivial constructors or destructors are required.
6354
6355 // FIXME: Handle references.
Sean Hunt023df372011-05-09 18:22:59 +00006356 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006357 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6358 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Sean Hunt023df372011-05-09 18:22:59 +00006359 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6360 RD->hasTrivialCopyConstructor() &&
6361 RD->hasTrivialMoveConstructor() &&
6362 RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006363 return true;
6364 }
6365 }
6366
6367 GVALinkage L = GetGVALinkageForVariable(VD);
6368 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6369 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6370 return false;
6371 }
6372
6373 return true;
6374}
Charles Davis071cc7d2010-08-16 03:33:14 +00006375
Charles Davisee743f92010-11-09 18:04:24 +00006376CallingConv ASTContext::getDefaultMethodCallConv() {
6377 // Pass through to the C++ ABI object
6378 return ABI->getDefaultMethodCallConv();
6379}
6380
Jay Foad4ba2a172011-01-12 09:06:06 +00006381bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00006382 // Pass through to the C++ ABI object
6383 return ABI->isNearlyEmpty(RD);
6384}
6385
Peter Collingbourne14110472011-01-13 18:57:25 +00006386MangleContext *ASTContext::createMangleContext() {
6387 switch (Target.getCXXABI()) {
6388 case CXXABI_ARM:
6389 case CXXABI_Itanium:
6390 return createItaniumMangleContext(*this, getDiagnostics());
6391 case CXXABI_Microsoft:
6392 return createMicrosoftMangleContext(*this, getDiagnostics());
6393 }
6394 assert(0 && "Unsupported ABI");
6395 return 0;
6396}
6397
Charles Davis071cc7d2010-08-16 03:33:14 +00006398CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00006399
6400size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00006401 return ASTRecordLayouts.getMemorySize()
6402 + llvm::capacity_in_bytes(ObjCLayouts)
6403 + llvm::capacity_in_bytes(KeyFunctions)
6404 + llvm::capacity_in_bytes(ObjCImpls)
6405 + llvm::capacity_in_bytes(BlockVarCopyInits)
6406 + llvm::capacity_in_bytes(DeclAttrs)
6407 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6408 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6409 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6410 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6411 + llvm::capacity_in_bytes(OverriddenMethods)
6412 + llvm::capacity_in_bytes(Types)
6413 + llvm::capacity_in_bytes(VariableArrayTypes);
Ted Kremenekba29bd22011-04-28 04:53:38 +00006414}