blob: bb93a68d26550ea3daecd85c28534ec51cfd4680 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCallea1471e2010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +000033#include "llvm/Support/Capacity.h"
Charles Davis071cc7d2010-08-16 03:33:14 +000034#include "CXXABI.h"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000035#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000036
Reid Spencer5f016e22007-07-11 17:01:13 +000037using namespace clang;
38
Douglas Gregor18274032010-07-03 00:47:00 +000039unsigned ASTContext::NumImplicitDefaultConstructors;
40unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000041unsigned ASTContext::NumImplicitCopyConstructors;
42unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000043unsigned ASTContext::NumImplicitMoveConstructors;
44unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000045unsigned ASTContext::NumImplicitCopyAssignmentOperators;
46unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000047unsigned ASTContext::NumImplicitMoveAssignmentOperators;
48unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000049unsigned ASTContext::NumImplicitDestructors;
50unsigned ASTContext::NumImplicitDestructorsDeclared;
51
Reid Spencer5f016e22007-07-11 17:01:13 +000052enum FloatingRank {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +000053 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Reid Spencer5f016e22007-07-11 17:01:13 +000054};
55
Douglas Gregor3e1274f2010-06-16 21:09:37 +000056void
57ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
58 TemplateTemplateParmDecl *Parm) {
59 ID.AddInteger(Parm->getDepth());
60 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +000061 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000062
63 TemplateParameterList *Params = Parm->getTemplateParameters();
64 ID.AddInteger(Params->size());
65 for (TemplateParameterList::const_iterator P = Params->begin(),
66 PEnd = Params->end();
67 P != PEnd; ++P) {
68 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
69 ID.AddInteger(0);
70 ID.AddBoolean(TTP->isParameterPack());
71 continue;
72 }
73
74 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
75 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +000076 ID.AddBoolean(NTTP->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000077 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +000078 if (NTTP->isExpandedParameterPack()) {
79 ID.AddBoolean(true);
80 ID.AddInteger(NTTP->getNumExpansionTypes());
81 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
82 ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
83 } else
84 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +000085 continue;
86 }
87
88 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
89 ID.AddInteger(2);
90 Profile(ID, TTP);
91 }
92}
93
94TemplateTemplateParmDecl *
95ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +000096 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +000097 // Check if we already have a canonical template template parameter.
98 llvm::FoldingSetNodeID ID;
99 CanonicalTemplateTemplateParm::Profile(ID, TTP);
100 void *InsertPos = 0;
101 CanonicalTemplateTemplateParm *Canonical
102 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
103 if (Canonical)
104 return Canonical->getParam();
105
106 // Build a canonical template parameter list.
107 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000108 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000109 CanonParams.reserve(Params->size());
110 for (TemplateParameterList::const_iterator P = Params->begin(),
111 PEnd = Params->end();
112 P != PEnd; ++P) {
113 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
114 CanonParams.push_back(
115 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000116 SourceLocation(),
117 SourceLocation(),
118 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000119 TTP->getIndex(), 0, false,
120 TTP->isParameterPack()));
121 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000122 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
123 QualType T = getCanonicalType(NTTP->getType());
124 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
125 NonTypeTemplateParmDecl *Param;
126 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000127 SmallVector<QualType, 2> ExpandedTypes;
128 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000129 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
130 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
131 ExpandedTInfos.push_back(
132 getTrivialTypeSourceInfo(ExpandedTypes.back()));
133 }
134
135 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000136 SourceLocation(),
137 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000138 NTTP->getDepth(),
139 NTTP->getPosition(), 0,
140 T,
141 TInfo,
142 ExpandedTypes.data(),
143 ExpandedTypes.size(),
144 ExpandedTInfos.data());
145 } else {
146 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000147 SourceLocation(),
148 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000149 NTTP->getDepth(),
150 NTTP->getPosition(), 0,
151 T,
152 NTTP->isParameterPack(),
153 TInfo);
154 }
155 CanonParams.push_back(Param);
156
157 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000158 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
159 cast<TemplateTemplateParmDecl>(*P)));
160 }
161
162 TemplateTemplateParmDecl *CanonTTP
163 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
164 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000165 TTP->getPosition(),
166 TTP->isParameterPack(),
167 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000168 TemplateParameterList::Create(*this, SourceLocation(),
169 SourceLocation(),
170 CanonParams.data(),
171 CanonParams.size(),
172 SourceLocation()));
173
174 // Get the new insert position for the node we care about.
175 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
176 assert(Canonical == 0 && "Shouldn't be in the map!");
177 (void)Canonical;
178
179 // Create the canonical template template parameter entry.
180 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
181 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
182 return CanonTTP;
183}
184
Charles Davis071cc7d2010-08-16 03:33:14 +0000185CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000186 if (!LangOpts.CPlusPlus) return 0;
187
Charles Davis20cf7172010-08-19 02:18:14 +0000188 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000189 case CXXABI_ARM:
190 return CreateARMCXXABI(*this);
191 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000192 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000193 case CXXABI_Microsoft:
194 return CreateMicrosoftCXXABI(*this);
195 }
David Blaikie7530c032012-01-17 06:56:22 +0000196 llvm_unreachable("Invalid CXXABI type!");
Charles Davis071cc7d2010-08-16 03:33:14 +0000197}
198
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000199static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000200 const LangOptions &LOpts) {
201 if (LOpts.FakeAddressSpaceMap) {
202 // The fake address space map must have a distinct entry for each
203 // language-specific address space.
204 static const unsigned FakeAddrSpaceMap[] = {
205 1, // opencl_global
206 2, // opencl_local
207 3 // opencl_constant
208 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000209 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000210 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000211 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000212 }
213}
214
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000215ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000216 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000217 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000218 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000219 unsigned size_reserve,
220 bool DelayInitialization)
221 : FunctionProtoTypes(this_()),
222 TemplateSpecializationTypes(this_()),
223 DependentTemplateSpecializationTypes(this_()),
224 SubstTemplateTemplateParmPacks(this_()),
225 GlobalNestedNameSpecifier(0),
226 Int128Decl(0), UInt128Decl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000227 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000228 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000229 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000230 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
231 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
232 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000233 NullTypeSourceInfo(QualType()),
234 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000235 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000236 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000237 Idents(idents), Selectors(sels),
238 BuiltinInfo(builtins),
239 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000240 ExternalSource(0), Listener(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000241 LastSDM(0, 0),
242 UniqueBlockByRefTypeID(0)
243{
Mike Stump1eb44332009-09-09 15:08:12 +0000244 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000245 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000246
247 if (!DelayInitialization) {
248 assert(t && "No target supplied for ASTContext initialization");
249 InitBuiltinTypes(*t);
250 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000251}
252
Reid Spencer5f016e22007-07-11 17:01:13 +0000253ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000254 // Release the DenseMaps associated with DeclContext objects.
255 // FIXME: Is this the ideal solution?
256 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000257
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000258 // Call all of the deallocation functions.
259 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
260 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000261
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000262 // Release all of the memory associated with overridden C++ methods.
263 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
264 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
265 OM != OMEnd; ++OM)
266 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +0000267
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000268 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000269 // because they can contain DenseMaps.
270 for (llvm::DenseMap<const ObjCContainerDecl*,
271 const ASTRecordLayout*>::iterator
272 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
273 // Increment in loop to prevent using deallocated memory.
274 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
275 R->Destroy(*this);
276
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000277 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
278 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
279 // Increment in loop to prevent using deallocated memory.
280 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
281 R->Destroy(*this);
282 }
Douglas Gregor63200642010-08-30 16:49:28 +0000283
284 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
285 AEnd = DeclAttrs.end();
286 A != AEnd; ++A)
287 A->second->~AttrVec();
288}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000289
Douglas Gregor00545312010-05-23 18:26:36 +0000290void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
291 Deallocations.push_back(std::make_pair(Callback, Data));
292}
293
Mike Stump1eb44332009-09-09 15:08:12 +0000294void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000295ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000296 ExternalSource.reset(Source.take());
297}
298
Reid Spencer5f016e22007-07-11 17:01:13 +0000299void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000300 llvm::errs() << "\n*** AST Context Stats:\n";
301 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000302
Douglas Gregordbe833d2009-05-26 14:40:08 +0000303 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000304#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000305#define ABSTRACT_TYPE(Name, Parent)
306#include "clang/AST/TypeNodes.def"
307 0 // Extra
308 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000309
Reid Spencer5f016e22007-07-11 17:01:13 +0000310 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
311 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000312 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000313 }
314
Douglas Gregordbe833d2009-05-26 14:40:08 +0000315 unsigned Idx = 0;
316 unsigned TotalBytes = 0;
317#define TYPE(Name, Parent) \
318 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000319 llvm::errs() << " " << counts[Idx] << " " << #Name \
320 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000321 TotalBytes += counts[Idx] * sizeof(Name##Type); \
322 ++Idx;
323#define ABSTRACT_TYPE(Name, Parent)
324#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Chandler Carruthcd92a652011-07-04 05:32:14 +0000326 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
327
Douglas Gregor4923aa22010-07-02 20:37:36 +0000328 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000329 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
330 << NumImplicitDefaultConstructors
331 << " implicit default constructors created\n";
332 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
333 << NumImplicitCopyConstructors
334 << " implicit copy constructors created\n";
Sean Huntffe37fd2011-05-25 20:50:04 +0000335 if (getLangOptions().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000336 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
337 << NumImplicitMoveConstructors
338 << " implicit move constructors created\n";
339 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
340 << NumImplicitCopyAssignmentOperators
341 << " implicit copy assignment operators created\n";
Sean Huntffe37fd2011-05-25 20:50:04 +0000342 if (getLangOptions().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000343 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
344 << NumImplicitMoveAssignmentOperators
345 << " implicit move assignment operators created\n";
346 llvm::errs() << NumImplicitDestructorsDeclared << "/"
347 << NumImplicitDestructors
348 << " implicit destructors created\n";
349
Douglas Gregor2cf26342009-04-09 22:27:44 +0000350 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000351 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000352 ExternalSource->PrintStats();
353 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000354
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000355 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000356}
357
Douglas Gregor772eeae2011-08-12 06:49:56 +0000358TypedefDecl *ASTContext::getInt128Decl() const {
359 if (!Int128Decl) {
360 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
361 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
362 getTranslationUnitDecl(),
363 SourceLocation(),
364 SourceLocation(),
365 &Idents.get("__int128_t"),
366 TInfo);
367 }
368
369 return Int128Decl;
370}
371
372TypedefDecl *ASTContext::getUInt128Decl() const {
373 if (!UInt128Decl) {
374 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
375 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
376 getTranslationUnitDecl(),
377 SourceLocation(),
378 SourceLocation(),
379 &Idents.get("__uint128_t"),
380 TInfo);
381 }
382
383 return UInt128Decl;
384}
Reid Spencer5f016e22007-07-11 17:01:13 +0000385
John McCalle27ec8a2009-10-23 23:03:21 +0000386void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000387 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000388 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000389 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000390}
391
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000392void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
393 assert((!this->Target || this->Target == &Target) &&
394 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000395 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000397 this->Target = &Target;
398
399 ABI.reset(createCXXABI(Target));
400 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
401
Reid Spencer5f016e22007-07-11 17:01:13 +0000402 // C99 6.2.5p19.
403 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Reid Spencer5f016e22007-07-11 17:01:13 +0000405 // C99 6.2.5p2.
406 InitBuiltinType(BoolTy, BuiltinType::Bool);
407 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000408 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000409 InitBuiltinType(CharTy, BuiltinType::Char_S);
410 else
411 InitBuiltinType(CharTy, BuiltinType::Char_U);
412 // C99 6.2.5p4.
413 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
414 InitBuiltinType(ShortTy, BuiltinType::Short);
415 InitBuiltinType(IntTy, BuiltinType::Int);
416 InitBuiltinType(LongTy, BuiltinType::Long);
417 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Reid Spencer5f016e22007-07-11 17:01:13 +0000419 // C99 6.2.5p6.
420 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
421 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
422 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
423 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
424 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000425
Reid Spencer5f016e22007-07-11 17:01:13 +0000426 // C99 6.2.5p10.
427 InitBuiltinType(FloatTy, BuiltinType::Float);
428 InitBuiltinType(DoubleTy, BuiltinType::Double);
429 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000430
Chris Lattner2df9ced2009-04-30 02:43:43 +0000431 // GNU extension, 128-bit integers.
432 InitBuiltinType(Int128Ty, BuiltinType::Int128);
433 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
434
Chris Lattner3f59c972010-12-25 23:25:43 +0000435 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedmand3d77cd2011-04-30 19:24:24 +0000436 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattner3f59c972010-12-25 23:25:43 +0000437 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
438 else // -fshort-wchar makes wchar_t be unsigned.
439 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
440 } else // C99
Chris Lattner3a250322009-02-26 23:43:47 +0000441 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000442
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000443 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
444 InitBuiltinType(Char16Ty, BuiltinType::Char16);
445 else // C99
446 Char16Ty = getFromTargetType(Target.getChar16Type());
447
448 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
449 InitBuiltinType(Char32Ty, BuiltinType::Char32);
450 else // C99
451 Char32Ty = getFromTargetType(Target.getChar32Type());
452
Douglas Gregor898574e2008-12-05 23:32:09 +0000453 // Placeholder type for type-dependent expressions whose type is
454 // completely unknown. No code should ever check a type against
455 // DependentTy and users should never see it; however, it is here to
456 // help diagnose failures to properly check for type-dependent
457 // expressions.
458 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000459
John McCall2a984ca2010-10-12 00:20:44 +0000460 // Placeholder type for functions.
461 InitBuiltinType(OverloadTy, BuiltinType::Overload);
462
John McCall864c0412011-04-26 20:42:42 +0000463 // Placeholder type for bound members.
464 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
465
John McCall3c3b7f92011-10-25 17:37:35 +0000466 // Placeholder type for pseudo-objects.
467 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
468
John McCall1de4d4e2011-04-07 08:22:57 +0000469 // "any" type; useful for debugger-like clients.
470 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
471
John McCall0ddaeb92011-10-17 18:09:15 +0000472 // Placeholder type for unbridged ARC casts.
473 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
474
Reid Spencer5f016e22007-07-11 17:01:13 +0000475 // C99 6.2.5p11.
476 FloatComplexTy = getComplexType(FloatTy);
477 DoubleComplexTy = getComplexType(DoubleTy);
478 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000479
Steve Naroff7e219e42007-10-15 14:41:52 +0000480 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000481
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000482 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000483 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
484 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000485 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000486
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000487 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000489 // void * type
490 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000491
492 // nullptr type (C++0x 2.14.7)
493 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000494
495 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
496 InitBuiltinType(HalfTy, BuiltinType::Half);
Reid Spencer5f016e22007-07-11 17:01:13 +0000497}
498
David Blaikied6471f72011-09-25 23:23:43 +0000499DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000500 return SourceMgr.getDiagnostics();
501}
502
Douglas Gregor63200642010-08-30 16:49:28 +0000503AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
504 AttrVec *&Result = DeclAttrs[D];
505 if (!Result) {
506 void *Mem = Allocate(sizeof(AttrVec));
507 Result = new (Mem) AttrVec;
508 }
509
510 return *Result;
511}
512
513/// \brief Erase the attributes corresponding to the given declaration.
514void ASTContext::eraseDeclAttrs(const Decl *D) {
515 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
516 if (Pos != DeclAttrs.end()) {
517 Pos->second->~AttrVec();
518 DeclAttrs.erase(Pos);
519 }
520}
521
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000522MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000523ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000524 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000525 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000526 = InstantiatedFromStaticDataMember.find(Var);
527 if (Pos == InstantiatedFromStaticDataMember.end())
528 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000529
Douglas Gregor7caa6822009-07-24 20:34:43 +0000530 return Pos->second;
531}
532
Mike Stump1eb44332009-09-09 15:08:12 +0000533void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000534ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000535 TemplateSpecializationKind TSK,
536 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000537 assert(Inst->isStaticDataMember() && "Not a static data member");
538 assert(Tmpl->isStaticDataMember() && "Not a static data member");
539 assert(!InstantiatedFromStaticDataMember[Inst] &&
540 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000541 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000542 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000543}
544
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000545FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
546 const FunctionDecl *FD){
547 assert(FD && "Specialization is 0");
548 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000549 = ClassScopeSpecializationPattern.find(FD);
550 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000551 return 0;
552
553 return Pos->second;
554}
555
556void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
557 FunctionDecl *Pattern) {
558 assert(FD && "Specialization is 0");
559 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000560 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000561}
562
John McCall7ba107a2009-11-18 02:36:19 +0000563NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000564ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000565 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000566 = InstantiatedFromUsingDecl.find(UUD);
567 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000568 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000569
Anders Carlsson0d8df782009-08-29 19:37:28 +0000570 return Pos->second;
571}
572
573void
John McCalled976492009-12-04 22:46:56 +0000574ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
575 assert((isa<UsingDecl>(Pattern) ||
576 isa<UnresolvedUsingValueDecl>(Pattern) ||
577 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
578 "pattern decl is not a using decl");
579 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
580 InstantiatedFromUsingDecl[Inst] = Pattern;
581}
582
583UsingShadowDecl *
584ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
585 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
586 = InstantiatedFromUsingShadowDecl.find(Inst);
587 if (Pos == InstantiatedFromUsingShadowDecl.end())
588 return 0;
589
590 return Pos->second;
591}
592
593void
594ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
595 UsingShadowDecl *Pattern) {
596 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
597 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000598}
599
Anders Carlssond8b285f2009-09-01 04:26:58 +0000600FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
601 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
602 = InstantiatedFromUnnamedFieldDecl.find(Field);
603 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
604 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000605
Anders Carlssond8b285f2009-09-01 04:26:58 +0000606 return Pos->second;
607}
608
609void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
610 FieldDecl *Tmpl) {
611 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
612 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
613 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
614 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000615
Anders Carlssond8b285f2009-09-01 04:26:58 +0000616 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
617}
618
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000619bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
620 const FieldDecl *LastFD) const {
621 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000622 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000623}
624
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000625bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
626 const FieldDecl *LastFD) const {
627 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000628 FD->getBitWidthValue(*this) == 0 &&
629 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000630}
631
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000632bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
633 const FieldDecl *LastFD) const {
634 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000635 FD->getBitWidthValue(*this) &&
636 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000637}
638
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000639bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000640 const FieldDecl *LastFD) const {
641 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000642 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000643}
644
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000645bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000646 const FieldDecl *LastFD) const {
647 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000648 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000649}
650
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000651ASTContext::overridden_cxx_method_iterator
652ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
653 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
654 = OverriddenMethods.find(Method);
655 if (Pos == OverriddenMethods.end())
656 return 0;
657
658 return Pos->second.begin();
659}
660
661ASTContext::overridden_cxx_method_iterator
662ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
663 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
664 = OverriddenMethods.find(Method);
665 if (Pos == OverriddenMethods.end())
666 return 0;
667
668 return Pos->second.end();
669}
670
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000671unsigned
672ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
673 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
674 = OverriddenMethods.find(Method);
675 if (Pos == OverriddenMethods.end())
676 return 0;
677
678 return Pos->second.size();
679}
680
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000681void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
682 const CXXMethodDecl *Overridden) {
683 OverriddenMethods[Method].push_back(Overridden);
684}
685
Douglas Gregore6649772011-12-03 00:30:27 +0000686void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
687 assert(!Import->NextLocalImport && "Import declaration already in the chain");
688 assert(!Import->isFromASTFile() && "Non-local import declaration");
689 if (!FirstLocalImport) {
690 FirstLocalImport = Import;
691 LastLocalImport = Import;
692 return;
693 }
694
695 LastLocalImport->NextLocalImport = Import;
696 LastLocalImport = Import;
697}
698
Chris Lattner464175b2007-07-18 17:52:12 +0000699//===----------------------------------------------------------------------===//
700// Type Sizing and Analysis
701//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000702
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000703/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
704/// scalar floating point type.
705const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000706 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000707 assert(BT && "Not a floating point type!");
708 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000709 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000710 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000711 case BuiltinType::Float: return Target->getFloatFormat();
712 case BuiltinType::Double: return Target->getDoubleFormat();
713 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000714 }
715}
716
Ken Dyck8b752f12010-01-27 17:10:57 +0000717/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000718/// specified decl. Note that bitfields do not have a valid alignment, so
719/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000720/// If @p RefAsPointee, references are treated like their underlying type
721/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +0000722CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000723 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +0000724
John McCall4081a5c2010-10-08 18:24:19 +0000725 bool UseAlignAttrOnly = false;
726 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
727 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +0000728
John McCall4081a5c2010-10-08 18:24:19 +0000729 // __attribute__((aligned)) can increase or decrease alignment
730 // *except* on a struct or struct member, where it only increases
731 // alignment unless 'packed' is also specified.
732 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +0000733 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +0000734 // ignore that possibility; Sema should diagnose it.
735 if (isa<FieldDecl>(D)) {
736 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
737 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
738 } else {
739 UseAlignAttrOnly = true;
740 }
741 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +0000742 else if (isa<FieldDecl>(D))
743 UseAlignAttrOnly =
744 D->hasAttr<PackedAttr>() ||
745 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +0000746
John McCallba4f5d52011-01-20 07:57:12 +0000747 // If we're using the align attribute only, just ignore everything
748 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +0000749 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +0000750 // do nothing
751
John McCall4081a5c2010-10-08 18:24:19 +0000752 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +0000753 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000754 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000755 if (RefAsPointee)
756 T = RT->getPointeeType();
757 else
758 T = getPointerType(RT->getPointeeType());
759 }
760 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +0000761 // Adjust alignments of declarations with array type by the
762 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000763 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +0000764 const ArrayType *arrayType;
765 if (MinWidth && (arrayType = getAsArrayType(T))) {
766 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000767 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +0000768 else if (isa<ConstantArrayType>(arrayType) &&
769 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000770 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000771
John McCall3b657512011-01-19 10:06:00 +0000772 // Walk through any array types while we're at it.
773 T = getBaseElementType(arrayType);
774 }
Chad Rosier9f1210c2011-07-26 07:03:04 +0000775 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedmandcdafb62009-02-22 02:56:25 +0000776 }
John McCallba4f5d52011-01-20 07:57:12 +0000777
778 // Fields can be subject to extra alignment constraints, like if
779 // the field is packed, the struct is packed, or the struct has a
780 // a max-field-alignment constraint (#pragma pack). So calculate
781 // the actual alignment of the field within the struct, and then
782 // (as we're expected to) constrain that by the alignment of the type.
783 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
784 // So calculate the alignment of the field.
785 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
786
787 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +0000788 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +0000789
790 // Use the GCD of that and the offset within the record.
791 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
792 if (offset > 0) {
793 // Alignment is always a power of 2, so the GCD will be a power of 2,
794 // which means we get to do this crazy thing instead of Euclid's.
795 uint64_t lowBitOfOffset = offset & (~offset + 1);
796 if (lowBitOfOffset < fieldAlign)
797 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
798 }
799
800 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +0000801 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000802 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000803
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000804 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +0000805}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000806
John McCallea1471e2010-05-20 01:18:31 +0000807std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000808ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +0000809 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000810 return std::make_pair(toCharUnitsFromBits(Info.first),
811 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +0000812}
813
814std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000815ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +0000816 return getTypeInfoInChars(T.getTypePtr());
817}
818
Chris Lattnera7674d82007-07-13 22:13:22 +0000819/// getTypeSize - Return the size of the specified type, in bits. This method
820/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000821///
822/// FIXME: Pointers into different addr spaces could have different sizes and
823/// alignment requirements: getPointerInfo should take an AddrSpace, this
824/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000825std::pair<uint64_t, unsigned>
Jay Foad4ba2a172011-01-12 09:06:06 +0000826ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +0000827 uint64_t Width=0;
828 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000829 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000830#define TYPE(Class, Base)
831#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000832#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000833#define DEPENDENT_TYPE(Class, Base) case Type::Class:
834#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +0000835 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000836
Chris Lattner692233e2007-07-13 22:27:08 +0000837 case Type::FunctionNoProto:
838 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000839 // GCC extension: alignof(function) = 32 bits
840 Width = 0;
841 Align = 32;
842 break;
843
Douglas Gregor72564e72009-02-26 23:50:07 +0000844 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000845 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000846 Width = 0;
847 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
848 break;
849
Steve Narofffb22d962007-08-30 01:06:46 +0000850 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000851 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Chris Lattner98be4942008-03-05 18:54:05 +0000853 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +0000854 uint64_t Size = CAT->getSize().getZExtValue();
855 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) && "Overflow in array type bit size evaluation");
856 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +0000857 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +0000858 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000859 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000860 }
Nate Begeman213541a2008-04-18 23:10:10 +0000861 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000862 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000863 const VectorType *VT = cast<VectorType>(T);
864 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
865 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000866 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000867 // If the alignment is not a power of 2, round up to the next power of 2.
868 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000869 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000870 Align = llvm::NextPowerOf2(Align);
871 Width = llvm::RoundUpToAlignment(Width, Align);
872 }
Chris Lattner030d8842007-07-19 22:06:24 +0000873 break;
874 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000875
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000876 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000877 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000878 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000879 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000880 // GCC extension: alignof(void) = 8 bits.
881 Width = 0;
882 Align = 8;
883 break;
884
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000885 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000886 Width = Target->getBoolWidth();
887 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000888 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000889 case BuiltinType::Char_S:
890 case BuiltinType::Char_U:
891 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000892 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000893 Width = Target->getCharWidth();
894 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000895 break;
Chris Lattner3f59c972010-12-25 23:25:43 +0000896 case BuiltinType::WChar_S:
897 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000898 Width = Target->getWCharWidth();
899 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000900 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000901 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000902 Width = Target->getChar16Width();
903 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000904 break;
905 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000906 Width = Target->getChar32Width();
907 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000908 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000909 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000910 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000911 Width = Target->getShortWidth();
912 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000913 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000914 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000915 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000916 Width = Target->getIntWidth();
917 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000918 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000919 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000920 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000921 Width = Target->getLongWidth();
922 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000923 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000924 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000925 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000926 Width = Target->getLongLongWidth();
927 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000928 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000929 case BuiltinType::Int128:
930 case BuiltinType::UInt128:
931 Width = 128;
932 Align = 128; // int128_t is 128-bit aligned on all targets.
933 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000934 case BuiltinType::Half:
935 Width = Target->getHalfWidth();
936 Align = Target->getHalfAlign();
937 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000938 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000939 Width = Target->getFloatWidth();
940 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000941 break;
942 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000943 Width = Target->getDoubleWidth();
944 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000945 break;
946 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000947 Width = Target->getLongDoubleWidth();
948 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000949 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000950 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000951 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
952 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000953 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000954 case BuiltinType::ObjCId:
955 case BuiltinType::ObjCClass:
956 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000957 Width = Target->getPointerWidth(0);
958 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000959 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000960 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000961 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000962 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000963 Width = Target->getPointerWidth(0);
964 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000965 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000966 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000967 unsigned AS = getTargetAddressSpace(
968 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000969 Width = Target->getPointerWidth(AS);
970 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +0000971 break;
972 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000973 case Type::LValueReference:
974 case Type::RValueReference: {
975 // alignof and sizeof should never enter this code path here, so we go
976 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000977 unsigned AS = getTargetAddressSpace(
978 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000979 Width = Target->getPointerWidth(AS);
980 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +0000981 break;
982 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000983 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000984 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000985 Width = Target->getPointerWidth(AS);
986 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000987 break;
988 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000989 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +0000990 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000991 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000992 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +0000993 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000994 Align = PtrDiffInfo.second;
995 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000996 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000997 case Type::Complex: {
998 // Complex types have the same alignment as their elements, but twice the
999 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001000 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001001 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001002 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001003 Align = EltInfo.second;
1004 break;
1005 }
John McCallc12c5bb2010-05-15 11:32:37 +00001006 case Type::ObjCObject:
1007 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001008 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001009 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001010 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001011 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001012 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001013 break;
1014 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001015 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001016 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001017 const TagType *TT = cast<TagType>(T);
1018
1019 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001020 Width = 8;
1021 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001022 break;
1023 }
Mike Stump1eb44332009-09-09 15:08:12 +00001024
Daniel Dunbar1d751182008-11-08 05:48:37 +00001025 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001026 return getTypeInfo(ET->getDecl()->getIntegerType());
1027
Daniel Dunbar1d751182008-11-08 05:48:37 +00001028 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001029 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001030 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001031 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001032 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001033 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001034
Chris Lattner9fcfe922009-10-22 05:17:15 +00001035 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001036 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1037 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001038
Richard Smith34b41d92011-02-20 03:19:35 +00001039 case Type::Auto: {
1040 const AutoType *A = cast<AutoType>(T);
1041 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001042 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001043 }
1044
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001045 case Type::Paren:
1046 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1047
Douglas Gregor18857642009-04-30 17:32:17 +00001048 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001049 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001050 std::pair<uint64_t, unsigned> Info
1051 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001052 // If the typedef has an aligned attribute on it, it overrides any computed
1053 // alignment we have. This violates the GCC documentation (which says that
1054 // attribute(aligned) can only round up) but matches its implementation.
1055 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1056 Align = AttrAlign;
1057 else
1058 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001059 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001060 break;
Chris Lattner71763312008-04-06 22:05:18 +00001061 }
Douglas Gregor18857642009-04-30 17:32:17 +00001062
1063 case Type::TypeOfExpr:
1064 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1065 .getTypePtr());
1066
1067 case Type::TypeOf:
1068 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1069
Anders Carlsson395b4752009-06-24 19:06:50 +00001070 case Type::Decltype:
1071 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1072 .getTypePtr());
1073
Sean Huntca63c202011-05-24 22:41:36 +00001074 case Type::UnaryTransform:
1075 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1076
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001077 case Type::Elaborated:
1078 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001079
John McCall9d156a72011-01-06 01:58:22 +00001080 case Type::Attributed:
1081 return getTypeInfo(
1082 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1083
Richard Smith3e4c6c42011-05-05 21:57:07 +00001084 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001085 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001086 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001087 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1088 // A type alias template specialization may refer to a typedef with the
1089 // aligned attribute on it.
1090 if (TST->isTypeAlias())
1091 return getTypeInfo(TST->getAliasedType().getTypePtr());
1092 else
1093 return getTypeInfo(getCanonicalType(T));
1094 }
1095
Eli Friedmanb001de72011-10-06 23:00:33 +00001096 case Type::Atomic: {
Eli Friedman2be46072011-10-14 20:59:01 +00001097 std::pair<uint64_t, unsigned> Info
1098 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1099 Width = Info.first;
1100 Align = Info.second;
1101 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1102 llvm::isPowerOf2_64(Width)) {
1103 // We can potentially perform lock-free atomic operations for this
1104 // type; promote the alignment appropriately.
1105 // FIXME: We could potentially promote the width here as well...
1106 // is that worthwhile? (Non-struct atomic types generally have
1107 // power-of-two size anyway, but structs might not. Requires a bit
1108 // of implementation work to make sure we zero out the extra bits.)
1109 Align = static_cast<unsigned>(Width);
1110 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001111 }
1112
Douglas Gregor18857642009-04-30 17:32:17 +00001113 }
Mike Stump1eb44332009-09-09 15:08:12 +00001114
Eli Friedman2be46072011-10-14 20:59:01 +00001115 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001116 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001117}
1118
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001119/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1120CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1121 return CharUnits::fromQuantity(BitSize / getCharWidth());
1122}
1123
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001124/// toBits - Convert a size in characters to a size in characters.
1125int64_t ASTContext::toBits(CharUnits CharSize) const {
1126 return CharSize.getQuantity() * getCharWidth();
1127}
1128
Ken Dyckbdc601b2009-12-22 14:23:30 +00001129/// getTypeSizeInChars - Return the size of the specified type, in characters.
1130/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001131CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001132 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001133}
Jay Foad4ba2a172011-01-12 09:06:06 +00001134CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001135 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001136}
1137
Ken Dyck16e20cc2010-01-26 17:25:18 +00001138/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001139/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001140CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001141 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001142}
Jay Foad4ba2a172011-01-12 09:06:06 +00001143CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001144 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001145}
1146
Chris Lattner34ebde42009-01-27 18:08:34 +00001147/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1148/// type for the current target in bits. This can be different than the ABI
1149/// alignment in cases where it is beneficial for performance to overalign
1150/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001151unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001152 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001153
1154 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001155 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001156 T = CT->getElementType().getTypePtr();
1157 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1158 T->isSpecificBuiltinType(BuiltinType::LongLong))
1159 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1160
Chris Lattner34ebde42009-01-27 18:08:34 +00001161 return ABIAlign;
1162}
1163
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001164/// DeepCollectObjCIvars -
1165/// This routine first collects all declared, but not synthesized, ivars in
1166/// super class and then collects all ivars, including those synthesized for
1167/// current class. This routine is used for implementation of current class
1168/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001169///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001170void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1171 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001172 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001173 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1174 DeepCollectObjCIvars(SuperClass, false, Ivars);
1175 if (!leafClass) {
1176 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1177 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanian11062e12010-02-19 00:31:17 +00001178 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001179 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001180 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001181 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001182 Iv= Iv->getNextIvar())
1183 Ivars.push_back(Iv);
1184 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001185}
1186
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001187/// CollectInheritedProtocols - Collect all protocols in current class and
1188/// those inherited by it.
1189void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001190 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001191 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001192 // We can use protocol_iterator here instead of
1193 // all_referenced_protocol_iterator since we are walking all categories.
1194 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1195 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001196 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001197 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001198 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001199 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001200 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001201 CollectInheritedProtocols(*P, Protocols);
1202 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001203 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001204
1205 // Categories of this Interface.
1206 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1207 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1208 CollectInheritedProtocols(CDeclChain, Protocols);
1209 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1210 while (SD) {
1211 CollectInheritedProtocols(SD, Protocols);
1212 SD = SD->getSuperClass();
1213 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001214 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001215 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001216 PE = OC->protocol_end(); P != PE; ++P) {
1217 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001218 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001219 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1220 PE = Proto->protocol_end(); P != PE; ++P)
1221 CollectInheritedProtocols(*P, Protocols);
1222 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001223 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001224 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1225 PE = OP->protocol_end(); P != PE; ++P) {
1226 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001227 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001228 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1229 PE = Proto->protocol_end(); P != PE; ++P)
1230 CollectInheritedProtocols(*P, Protocols);
1231 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001232 }
1233}
1234
Jay Foad4ba2a172011-01-12 09:06:06 +00001235unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001236 unsigned count = 0;
1237 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001238 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1239 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001240 count += CDecl->ivar_size();
1241
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001242 // Count ivar defined in this class's implementation. This
1243 // includes synthesized ivars.
1244 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001245 count += ImplDecl->ivar_size();
1246
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001247 return count;
1248}
1249
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001250bool ASTContext::isSentinelNullExpr(const Expr *E) {
1251 if (!E)
1252 return false;
1253
1254 // nullptr_t is always treated as null.
1255 if (E->getType()->isNullPtrType()) return true;
1256
1257 if (E->getType()->isAnyPointerType() &&
1258 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1259 Expr::NPC_ValueDependentIsNull))
1260 return true;
1261
1262 // Unfortunately, __null has type 'int'.
1263 if (isa<GNUNullExpr>(E)) return true;
1264
1265 return false;
1266}
1267
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001268/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1269ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1270 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1271 I = ObjCImpls.find(D);
1272 if (I != ObjCImpls.end())
1273 return cast<ObjCImplementationDecl>(I->second);
1274 return 0;
1275}
1276/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1277ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1278 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1279 I = ObjCImpls.find(D);
1280 if (I != ObjCImpls.end())
1281 return cast<ObjCCategoryImplDecl>(I->second);
1282 return 0;
1283}
1284
1285/// \brief Set the implementation of ObjCInterfaceDecl.
1286void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1287 ObjCImplementationDecl *ImplD) {
1288 assert(IFaceD && ImplD && "Passed null params");
1289 ObjCImpls[IFaceD] = ImplD;
1290}
1291/// \brief Set the implementation of ObjCCategoryDecl.
1292void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1293 ObjCCategoryImplDecl *ImplD) {
1294 assert(CatD && ImplD && "Passed null params");
1295 ObjCImpls[CatD] = ImplD;
1296}
1297
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001298ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1299 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1300 return ID;
1301 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1302 return CD->getClassInterface();
1303 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1304 return IMD->getClassInterface();
1305
1306 return 0;
1307}
1308
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001309/// \brief Get the copy initialization expression of VarDecl,or NULL if
1310/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001311Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001312 assert(VD && "Passed null params");
1313 assert(VD->hasAttr<BlocksAttr>() &&
1314 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001315 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001316 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001317 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1318}
1319
1320/// \brief Set the copy inialization expression of a block var decl.
1321void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1322 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001323 assert(VD->hasAttr<BlocksAttr>() &&
1324 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001325 BlockVarCopyInits[VD] = Init;
1326}
1327
John McCalla93c9342009-12-07 02:54:59 +00001328/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001329///
John McCalla93c9342009-12-07 02:54:59 +00001330/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001331/// the TypeLoc wrappers.
1332///
1333/// \param T the type that will be the basis for type source info. This type
1334/// should refer to how the declarator was written in source code, not to
1335/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001336TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001337 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001338 if (!DataSize)
1339 DataSize = TypeLoc::getFullDataSizeForType(T);
1340 else
1341 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001342 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001343
John McCalla93c9342009-12-07 02:54:59 +00001344 TypeSourceInfo *TInfo =
1345 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1346 new (TInfo) TypeSourceInfo(T);
1347 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001348}
1349
John McCalla93c9342009-12-07 02:54:59 +00001350TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001351 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001352 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001353 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001354 return DI;
1355}
1356
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001357const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001358ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001359 return getObjCLayout(D, 0);
1360}
1361
1362const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001363ASTContext::getASTObjCImplementationLayout(
1364 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001365 return getObjCLayout(D->getClassInterface(), D);
1366}
1367
Chris Lattnera7674d82007-07-13 22:13:22 +00001368//===----------------------------------------------------------------------===//
1369// Type creation/memoization methods
1370//===----------------------------------------------------------------------===//
1371
Jay Foad4ba2a172011-01-12 09:06:06 +00001372QualType
John McCall3b657512011-01-19 10:06:00 +00001373ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1374 unsigned fastQuals = quals.getFastQualifiers();
1375 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001376
1377 // Check if we've already instantiated this type.
1378 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001379 ExtQuals::Profile(ID, baseType, quals);
1380 void *insertPos = 0;
1381 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1382 assert(eq->getQualifiers() == quals);
1383 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001384 }
1385
John McCall3b657512011-01-19 10:06:00 +00001386 // If the base type is not canonical, make the appropriate canonical type.
1387 QualType canon;
1388 if (!baseType->isCanonicalUnqualified()) {
1389 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00001390 canonSplit.Quals.addConsistentQualifiers(quals);
1391 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001392
1393 // Re-find the insert position.
1394 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1395 }
1396
1397 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1398 ExtQualNodes.InsertNode(eq, insertPos);
1399 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001400}
1401
Jay Foad4ba2a172011-01-12 09:06:06 +00001402QualType
1403ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001404 QualType CanT = getCanonicalType(T);
1405 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001406 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001407
John McCall0953e762009-09-24 19:53:00 +00001408 // If we are composing extended qualifiers together, merge together
1409 // into one ExtQuals node.
1410 QualifierCollector Quals;
1411 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001412
John McCall0953e762009-09-24 19:53:00 +00001413 // If this type already has an address space specified, it cannot get
1414 // another one.
1415 assert(!Quals.hasAddressSpace() &&
1416 "Type cannot be in multiple addr spaces!");
1417 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001418
John McCall0953e762009-09-24 19:53:00 +00001419 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001420}
1421
Chris Lattnerb7d25532009-02-18 22:53:11 +00001422QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001423 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001424 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001425 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001426 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001427
John McCall7f040a92010-12-24 02:08:15 +00001428 if (const PointerType *ptr = T->getAs<PointerType>()) {
1429 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001430 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001431 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1432 return getPointerType(ResultType);
1433 }
1434 }
Mike Stump1eb44332009-09-09 15:08:12 +00001435
John McCall0953e762009-09-24 19:53:00 +00001436 // If we are composing extended qualifiers together, merge together
1437 // into one ExtQuals node.
1438 QualifierCollector Quals;
1439 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001440
John McCall0953e762009-09-24 19:53:00 +00001441 // If this type already has an ObjCGC specified, it cannot get
1442 // another one.
1443 assert(!Quals.hasObjCGCAttr() &&
1444 "Type cannot have multiple ObjCGCs!");
1445 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001446
John McCall0953e762009-09-24 19:53:00 +00001447 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001448}
Chris Lattnera7674d82007-07-13 22:13:22 +00001449
John McCalle6a365d2010-12-19 02:44:49 +00001450const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1451 FunctionType::ExtInfo Info) {
1452 if (T->getExtInfo() == Info)
1453 return T;
1454
1455 QualType Result;
1456 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1457 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1458 } else {
1459 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1460 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1461 EPI.ExtInfo = Info;
1462 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1463 FPT->getNumArgs(), EPI);
1464 }
1465
1466 return cast<FunctionType>(Result.getTypePtr());
1467}
1468
Reid Spencer5f016e22007-07-11 17:01:13 +00001469/// getComplexType - Return the uniqued reference to the type for a complex
1470/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001471QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 // Unique pointers, to guarantee there is only one pointer of a particular
1473 // structure.
1474 llvm::FoldingSetNodeID ID;
1475 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001476
Reid Spencer5f016e22007-07-11 17:01:13 +00001477 void *InsertPos = 0;
1478 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1479 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001480
Reid Spencer5f016e22007-07-11 17:01:13 +00001481 // If the pointee type isn't canonical, this won't be a canonical type either,
1482 // so fill in the canonical type field.
1483 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001484 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001485 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001486
Reid Spencer5f016e22007-07-11 17:01:13 +00001487 // Get the new insert position for the node we care about.
1488 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001489 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001490 }
John McCall6b304a02009-09-24 23:30:46 +00001491 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001492 Types.push_back(New);
1493 ComplexTypes.InsertNode(New, InsertPos);
1494 return QualType(New, 0);
1495}
1496
Reid Spencer5f016e22007-07-11 17:01:13 +00001497/// getPointerType - Return the uniqued reference to the type for a pointer to
1498/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001499QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001500 // Unique pointers, to guarantee there is only one pointer of a particular
1501 // structure.
1502 llvm::FoldingSetNodeID ID;
1503 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001504
Reid Spencer5f016e22007-07-11 17:01:13 +00001505 void *InsertPos = 0;
1506 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1507 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001508
Reid Spencer5f016e22007-07-11 17:01:13 +00001509 // If the pointee type isn't canonical, this won't be a canonical type either,
1510 // so fill in the canonical type field.
1511 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001512 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001513 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001514
Reid Spencer5f016e22007-07-11 17:01:13 +00001515 // Get the new insert position for the node we care about.
1516 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001517 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001518 }
John McCall6b304a02009-09-24 23:30:46 +00001519 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001520 Types.push_back(New);
1521 PointerTypes.InsertNode(New, InsertPos);
1522 return QualType(New, 0);
1523}
1524
Mike Stump1eb44332009-09-09 15:08:12 +00001525/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001526/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001527QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001528 assert(T->isFunctionType() && "block of function types only");
1529 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001530 // structure.
1531 llvm::FoldingSetNodeID ID;
1532 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001533
Steve Naroff5618bd42008-08-27 16:04:49 +00001534 void *InsertPos = 0;
1535 if (BlockPointerType *PT =
1536 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1537 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001538
1539 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001540 // type either so fill in the canonical type field.
1541 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001542 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001543 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001544
Steve Naroff5618bd42008-08-27 16:04:49 +00001545 // Get the new insert position for the node we care about.
1546 BlockPointerType *NewIP =
1547 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001548 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001549 }
John McCall6b304a02009-09-24 23:30:46 +00001550 BlockPointerType *New
1551 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001552 Types.push_back(New);
1553 BlockPointerTypes.InsertNode(New, InsertPos);
1554 return QualType(New, 0);
1555}
1556
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001557/// getLValueReferenceType - Return the uniqued reference to the type for an
1558/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001559QualType
1560ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00001561 assert(getCanonicalType(T) != OverloadTy &&
1562 "Unresolved overloaded function type");
1563
Reid Spencer5f016e22007-07-11 17:01:13 +00001564 // Unique pointers, to guarantee there is only one pointer of a particular
1565 // structure.
1566 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001567 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001568
1569 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001570 if (LValueReferenceType *RT =
1571 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001573
John McCall54e14c42009-10-22 22:37:11 +00001574 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1575
Reid Spencer5f016e22007-07-11 17:01:13 +00001576 // If the referencee type isn't canonical, this won't be a canonical type
1577 // either, so fill in the canonical type field.
1578 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001579 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1580 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1581 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001582
Reid Spencer5f016e22007-07-11 17:01:13 +00001583 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001584 LValueReferenceType *NewIP =
1585 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001586 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001587 }
1588
John McCall6b304a02009-09-24 23:30:46 +00001589 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001590 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1591 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001592 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001593 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001594
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001595 return QualType(New, 0);
1596}
1597
1598/// getRValueReferenceType - Return the uniqued reference to the type for an
1599/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001600QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001601 // Unique pointers, to guarantee there is only one pointer of a particular
1602 // structure.
1603 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001604 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001605
1606 void *InsertPos = 0;
1607 if (RValueReferenceType *RT =
1608 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1609 return QualType(RT, 0);
1610
John McCall54e14c42009-10-22 22:37:11 +00001611 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1612
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001613 // If the referencee type isn't canonical, this won't be a canonical type
1614 // either, so fill in the canonical type field.
1615 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001616 if (InnerRef || !T.isCanonical()) {
1617 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1618 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001619
1620 // Get the new insert position for the node we care about.
1621 RValueReferenceType *NewIP =
1622 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001623 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001624 }
1625
John McCall6b304a02009-09-24 23:30:46 +00001626 RValueReferenceType *New
1627 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001628 Types.push_back(New);
1629 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001630 return QualType(New, 0);
1631}
1632
Sebastian Redlf30208a2009-01-24 21:16:55 +00001633/// getMemberPointerType - Return the uniqued reference to the type for a
1634/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00001635QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001636 // Unique pointers, to guarantee there is only one pointer of a particular
1637 // structure.
1638 llvm::FoldingSetNodeID ID;
1639 MemberPointerType::Profile(ID, T, Cls);
1640
1641 void *InsertPos = 0;
1642 if (MemberPointerType *PT =
1643 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1644 return QualType(PT, 0);
1645
1646 // If the pointee or class type isn't canonical, this won't be a canonical
1647 // type either, so fill in the canonical type field.
1648 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001649 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001650 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1651
1652 // Get the new insert position for the node we care about.
1653 MemberPointerType *NewIP =
1654 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001655 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001656 }
John McCall6b304a02009-09-24 23:30:46 +00001657 MemberPointerType *New
1658 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001659 Types.push_back(New);
1660 MemberPointerTypes.InsertNode(New, InsertPos);
1661 return QualType(New, 0);
1662}
1663
Mike Stump1eb44332009-09-09 15:08:12 +00001664/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001665/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001666QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001667 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001668 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001669 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001670 assert((EltTy->isDependentType() ||
1671 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001672 "Constant array of VLAs is illegal!");
1673
Chris Lattner38aeec72009-05-13 04:12:56 +00001674 // Convert the array size into a canonical width matching the pointer size for
1675 // the target.
1676 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001677 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001678 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00001679
Reid Spencer5f016e22007-07-11 17:01:13 +00001680 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001681 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001682
Reid Spencer5f016e22007-07-11 17:01:13 +00001683 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001684 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001685 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001686 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001687
John McCall3b657512011-01-19 10:06:00 +00001688 // If the element type isn't canonical or has qualifiers, this won't
1689 // be a canonical type either, so fill in the canonical type field.
1690 QualType Canon;
1691 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1692 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00001693 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001694 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00001695 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001696
Reid Spencer5f016e22007-07-11 17:01:13 +00001697 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001698 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001699 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001700 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001701 }
Mike Stump1eb44332009-09-09 15:08:12 +00001702
John McCall6b304a02009-09-24 23:30:46 +00001703 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001704 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001705 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001706 Types.push_back(New);
1707 return QualType(New, 0);
1708}
1709
John McCallce889032011-01-18 08:40:38 +00001710/// getVariableArrayDecayedType - Turns the given type, which may be
1711/// variably-modified, into the corresponding type with all the known
1712/// sizes replaced with [*].
1713QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1714 // Vastly most common case.
1715 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001716
John McCallce889032011-01-18 08:40:38 +00001717 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001718
John McCallce889032011-01-18 08:40:38 +00001719 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00001720 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00001721 switch (ty->getTypeClass()) {
1722#define TYPE(Class, Base)
1723#define ABSTRACT_TYPE(Class, Base)
1724#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1725#include "clang/AST/TypeNodes.def"
1726 llvm_unreachable("didn't desugar past all non-canonical types?");
1727
1728 // These types should never be variably-modified.
1729 case Type::Builtin:
1730 case Type::Complex:
1731 case Type::Vector:
1732 case Type::ExtVector:
1733 case Type::DependentSizedExtVector:
1734 case Type::ObjCObject:
1735 case Type::ObjCInterface:
1736 case Type::ObjCObjectPointer:
1737 case Type::Record:
1738 case Type::Enum:
1739 case Type::UnresolvedUsing:
1740 case Type::TypeOfExpr:
1741 case Type::TypeOf:
1742 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00001743 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00001744 case Type::DependentName:
1745 case Type::InjectedClassName:
1746 case Type::TemplateSpecialization:
1747 case Type::DependentTemplateSpecialization:
1748 case Type::TemplateTypeParm:
1749 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00001750 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00001751 case Type::PackExpansion:
1752 llvm_unreachable("type should never be variably-modified");
1753
1754 // These types can be variably-modified but should never need to
1755 // further decay.
1756 case Type::FunctionNoProto:
1757 case Type::FunctionProto:
1758 case Type::BlockPointer:
1759 case Type::MemberPointer:
1760 return type;
1761
1762 // These types can be variably-modified. All these modifications
1763 // preserve structure except as noted by comments.
1764 // TODO: if we ever care about optimizing VLAs, there are no-op
1765 // optimizations available here.
1766 case Type::Pointer:
1767 result = getPointerType(getVariableArrayDecayedType(
1768 cast<PointerType>(ty)->getPointeeType()));
1769 break;
1770
1771 case Type::LValueReference: {
1772 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1773 result = getLValueReferenceType(
1774 getVariableArrayDecayedType(lv->getPointeeType()),
1775 lv->isSpelledAsLValue());
1776 break;
1777 }
1778
1779 case Type::RValueReference: {
1780 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1781 result = getRValueReferenceType(
1782 getVariableArrayDecayedType(lv->getPointeeType()));
1783 break;
1784 }
1785
Eli Friedmanb001de72011-10-06 23:00:33 +00001786 case Type::Atomic: {
1787 const AtomicType *at = cast<AtomicType>(ty);
1788 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1789 break;
1790 }
1791
John McCallce889032011-01-18 08:40:38 +00001792 case Type::ConstantArray: {
1793 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1794 result = getConstantArrayType(
1795 getVariableArrayDecayedType(cat->getElementType()),
1796 cat->getSize(),
1797 cat->getSizeModifier(),
1798 cat->getIndexTypeCVRQualifiers());
1799 break;
1800 }
1801
1802 case Type::DependentSizedArray: {
1803 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1804 result = getDependentSizedArrayType(
1805 getVariableArrayDecayedType(dat->getElementType()),
1806 dat->getSizeExpr(),
1807 dat->getSizeModifier(),
1808 dat->getIndexTypeCVRQualifiers(),
1809 dat->getBracketsRange());
1810 break;
1811 }
1812
1813 // Turn incomplete types into [*] types.
1814 case Type::IncompleteArray: {
1815 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1816 result = getVariableArrayType(
1817 getVariableArrayDecayedType(iat->getElementType()),
1818 /*size*/ 0,
1819 ArrayType::Normal,
1820 iat->getIndexTypeCVRQualifiers(),
1821 SourceRange());
1822 break;
1823 }
1824
1825 // Turn VLA types into [*] types.
1826 case Type::VariableArray: {
1827 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1828 result = getVariableArrayType(
1829 getVariableArrayDecayedType(vat->getElementType()),
1830 /*size*/ 0,
1831 ArrayType::Star,
1832 vat->getIndexTypeCVRQualifiers(),
1833 vat->getBracketsRange());
1834 break;
1835 }
1836 }
1837
1838 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00001839 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00001840}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001841
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001842/// getVariableArrayType - Returns a non-unique reference to the type for a
1843/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001844QualType ASTContext::getVariableArrayType(QualType EltTy,
1845 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001846 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001847 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00001848 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001849 // Since we don't unique expressions, it isn't possible to unique VLA's
1850 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00001851 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00001852
John McCall3b657512011-01-19 10:06:00 +00001853 // Be sure to pull qualifiers off the element type.
1854 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1855 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00001856 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001857 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00001858 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00001859 }
1860
John McCall6b304a02009-09-24 23:30:46 +00001861 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001862 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001863
1864 VariableArrayTypes.push_back(New);
1865 Types.push_back(New);
1866 return QualType(New, 0);
1867}
1868
Douglas Gregor898574e2008-12-05 23:32:09 +00001869/// getDependentSizedArrayType - Returns a non-unique reference to
1870/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001871/// type.
John McCall3b657512011-01-19 10:06:00 +00001872QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1873 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00001874 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001875 unsigned elementTypeQuals,
1876 SourceRange brackets) const {
1877 assert((!numElements || numElements->isTypeDependent() ||
1878 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001879 "Size must be type- or value-dependent!");
1880
John McCall3b657512011-01-19 10:06:00 +00001881 // Dependently-sized array types that do not have a specified number
1882 // of elements will have their sizes deduced from a dependent
1883 // initializer. We do no canonicalization here at all, which is okay
1884 // because they can't be used in most locations.
1885 if (!numElements) {
1886 DependentSizedArrayType *newType
1887 = new (*this, TypeAlignment)
1888 DependentSizedArrayType(*this, elementType, QualType(),
1889 numElements, ASM, elementTypeQuals,
1890 brackets);
1891 Types.push_back(newType);
1892 return QualType(newType, 0);
1893 }
1894
1895 // Otherwise, we actually build a new type every time, but we
1896 // also build a canonical type.
1897
1898 SplitQualType canonElementType = getCanonicalType(elementType).split();
1899
1900 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001901 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001902 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00001903 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00001904 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001905
John McCall3b657512011-01-19 10:06:00 +00001906 // Look for an existing type with these properties.
1907 DependentSizedArrayType *canonTy =
1908 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001909
John McCall3b657512011-01-19 10:06:00 +00001910 // If we don't have one, build one.
1911 if (!canonTy) {
1912 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00001913 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00001914 QualType(), numElements, ASM, elementTypeQuals,
1915 brackets);
1916 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1917 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001918 }
1919
John McCall3b657512011-01-19 10:06:00 +00001920 // Apply qualifiers from the element type to the array.
1921 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00001922 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00001923
John McCall3b657512011-01-19 10:06:00 +00001924 // If we didn't need extra canonicalization for the element type,
1925 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00001926 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00001927 return canon;
1928
1929 // Otherwise, we need to build a type which follows the spelling
1930 // of the element type.
1931 DependentSizedArrayType *sugaredType
1932 = new (*this, TypeAlignment)
1933 DependentSizedArrayType(*this, elementType, canon, numElements,
1934 ASM, elementTypeQuals, brackets);
1935 Types.push_back(sugaredType);
1936 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00001937}
1938
John McCall3b657512011-01-19 10:06:00 +00001939QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00001940 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001941 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001942 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001943 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001944
John McCall3b657512011-01-19 10:06:00 +00001945 void *insertPos = 0;
1946 if (IncompleteArrayType *iat =
1947 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1948 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001949
1950 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00001951 // either, so fill in the canonical type field. We also have to pull
1952 // qualifiers off the element type.
1953 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00001954
John McCall3b657512011-01-19 10:06:00 +00001955 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1956 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00001957 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00001958 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00001959 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001960
1961 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00001962 IncompleteArrayType *existing =
1963 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1964 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001965 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001966
John McCall3b657512011-01-19 10:06:00 +00001967 IncompleteArrayType *newType = new (*this, TypeAlignment)
1968 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001969
John McCall3b657512011-01-19 10:06:00 +00001970 IncompleteArrayTypes.InsertNode(newType, insertPos);
1971 Types.push_back(newType);
1972 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001973}
1974
Steve Naroff73322922007-07-18 18:00:27 +00001975/// getVectorType - Return the unique reference to a vector type of
1976/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001977QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00001978 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00001979 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001980
Reid Spencer5f016e22007-07-11 17:01:13 +00001981 // Check if we've already instantiated a vector of this type.
1982 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00001983 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00001984
Reid Spencer5f016e22007-07-11 17:01:13 +00001985 void *InsertPos = 0;
1986 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1987 return QualType(VTP, 0);
1988
1989 // If the element type isn't canonical, this won't be a canonical type either,
1990 // so fill in the canonical type field.
1991 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00001992 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00001993 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00001994
Reid Spencer5f016e22007-07-11 17:01:13 +00001995 // Get the new insert position for the node we care about.
1996 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001997 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001998 }
John McCall6b304a02009-09-24 23:30:46 +00001999 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002000 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002001 VectorTypes.InsertNode(New, InsertPos);
2002 Types.push_back(New);
2003 return QualType(New, 0);
2004}
2005
Nate Begeman213541a2008-04-18 23:10:10 +00002006/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002007/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002008QualType
2009ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002010 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002011
Steve Naroff73322922007-07-18 18:00:27 +00002012 // Check if we've already instantiated a vector of this type.
2013 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002014 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002015 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002016 void *InsertPos = 0;
2017 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2018 return QualType(VTP, 0);
2019
2020 // If the element type isn't canonical, this won't be a canonical type either,
2021 // so fill in the canonical type field.
2022 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002023 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002024 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002025
Steve Naroff73322922007-07-18 18:00:27 +00002026 // Get the new insert position for the node we care about.
2027 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002028 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002029 }
John McCall6b304a02009-09-24 23:30:46 +00002030 ExtVectorType *New = new (*this, TypeAlignment)
2031 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002032 VectorTypes.InsertNode(New, InsertPos);
2033 Types.push_back(New);
2034 return QualType(New, 0);
2035}
2036
Jay Foad4ba2a172011-01-12 09:06:06 +00002037QualType
2038ASTContext::getDependentSizedExtVectorType(QualType vecType,
2039 Expr *SizeExpr,
2040 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002041 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002042 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002043 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002044
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002045 void *InsertPos = 0;
2046 DependentSizedExtVectorType *Canon
2047 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2048 DependentSizedExtVectorType *New;
2049 if (Canon) {
2050 // We already have a canonical version of this array type; use it as
2051 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002052 New = new (*this, TypeAlignment)
2053 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2054 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002055 } else {
2056 QualType CanonVecTy = getCanonicalType(vecType);
2057 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002058 New = new (*this, TypeAlignment)
2059 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2060 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002061
2062 DependentSizedExtVectorType *CanonCheck
2063 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2064 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2065 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002066 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2067 } else {
2068 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2069 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002070 New = new (*this, TypeAlignment)
2071 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002072 }
2073 }
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002075 Types.push_back(New);
2076 return QualType(New, 0);
2077}
2078
Douglas Gregor72564e72009-02-26 23:50:07 +00002079/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002080///
Jay Foad4ba2a172011-01-12 09:06:06 +00002081QualType
2082ASTContext::getFunctionNoProtoType(QualType ResultTy,
2083 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002084 const CallingConv DefaultCC = Info.getCC();
2085 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2086 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002087 // Unique functions, to guarantee there is only one function of a particular
2088 // structure.
2089 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002090 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002091
Reid Spencer5f016e22007-07-11 17:01:13 +00002092 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002093 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002094 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002095 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002096
Reid Spencer5f016e22007-07-11 17:01:13 +00002097 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002098 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002099 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002100 Canonical =
2101 getFunctionNoProtoType(getCanonicalType(ResultTy),
2102 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002103
Reid Spencer5f016e22007-07-11 17:01:13 +00002104 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002105 FunctionNoProtoType *NewIP =
2106 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002107 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002108 }
Mike Stump1eb44332009-09-09 15:08:12 +00002109
Roman Divackycfe9af22011-03-01 17:40:53 +00002110 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002111 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002112 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002113 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002114 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002115 return QualType(New, 0);
2116}
2117
2118/// getFunctionType - Return a normal function type with a typed argument
2119/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002120QualType
2121ASTContext::getFunctionType(QualType ResultTy,
2122 const QualType *ArgArray, unsigned NumArgs,
2123 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002124 // Unique functions, to guarantee there is only one function of a particular
2125 // structure.
2126 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002127 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002128
2129 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002130 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002131 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002132 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002133
2134 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002135 bool isCanonical =
2136 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2137 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002138 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002139 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002140 isCanonical = false;
2141
Roman Divackycfe9af22011-03-01 17:40:53 +00002142 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2143 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2144 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002145
Reid Spencer5f016e22007-07-11 17:01:13 +00002146 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002147 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002148 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002149 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002150 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002151 CanonicalArgs.reserve(NumArgs);
2152 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002153 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002154
John McCalle23cf432010-12-14 08:05:40 +00002155 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002156 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002157 CanonicalEPI.ExceptionSpecType = EST_None;
2158 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002159 CanonicalEPI.ExtInfo
2160 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2161
Chris Lattnerf52ab252008-04-06 22:59:24 +00002162 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00002163 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002164 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002165
Reid Spencer5f016e22007-07-11 17:01:13 +00002166 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002167 FunctionProtoType *NewIP =
2168 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002169 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002170 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002171
John McCallf85e1932011-06-15 23:02:42 +00002172 // FunctionProtoType objects are allocated with extra bytes after
2173 // them for three variable size arrays at the end:
2174 // - parameter types
2175 // - exception types
2176 // - consumed-arguments flags
2177 // Instead of the exception types, there could be a noexcept
2178 // expression.
John McCalle23cf432010-12-14 08:05:40 +00002179 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002180 NumArgs * sizeof(QualType);
2181 if (EPI.ExceptionSpecType == EST_Dynamic)
2182 Size += EPI.NumExceptions * sizeof(QualType);
2183 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002184 Size += sizeof(Expr*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002185 }
John McCallf85e1932011-06-15 23:02:42 +00002186 if (EPI.ConsumedArguments)
2187 Size += NumArgs * sizeof(bool);
2188
John McCalle23cf432010-12-14 08:05:40 +00002189 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002190 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2191 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002192 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002193 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002194 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002195 return QualType(FTP, 0);
2196}
2197
John McCall3cb0ebd2010-03-10 03:28:59 +00002198#ifndef NDEBUG
2199static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2200 if (!isa<CXXRecordDecl>(D)) return false;
2201 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2202 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2203 return true;
2204 if (RD->getDescribedClassTemplate() &&
2205 !isa<ClassTemplateSpecializationDecl>(RD))
2206 return true;
2207 return false;
2208}
2209#endif
2210
2211/// getInjectedClassNameType - Return the unique reference to the
2212/// injected class name type for the specified templated declaration.
2213QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002214 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002215 assert(NeedsInjectedClassNameType(Decl));
2216 if (Decl->TypeForDecl) {
2217 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002218 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002219 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2220 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2221 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2222 } else {
John McCallf4c73712011-01-19 06:33:43 +00002223 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002224 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002225 Decl->TypeForDecl = newType;
2226 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002227 }
2228 return QualType(Decl->TypeForDecl, 0);
2229}
2230
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002231/// getTypeDeclType - Return the unique reference to the type for the
2232/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002233QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002234 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002235 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002236
Richard Smith162e1c12011-04-15 14:24:37 +00002237 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002238 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002239
John McCallbecb8d52010-03-10 06:48:02 +00002240 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2241 "Template type parameter types are always available.");
2242
John McCall19c85762010-02-16 03:57:14 +00002243 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002244 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002245 "struct/union has previous declaration");
2246 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002247 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002248 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002249 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002250 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002251 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002252 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002253 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002254 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2255 Decl->TypeForDecl = newType;
2256 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002257 } else
John McCallbecb8d52010-03-10 06:48:02 +00002258 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002259
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002260 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002261}
2262
Reid Spencer5f016e22007-07-11 17:01:13 +00002263/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002264/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002265QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002266ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2267 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002268 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002269
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002270 if (Canonical.isNull())
2271 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002272 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002273 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002274 Decl->TypeForDecl = newType;
2275 Types.push_back(newType);
2276 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002277}
2278
Jay Foad4ba2a172011-01-12 09:06:06 +00002279QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002280 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2281
Douglas Gregoref96ee02012-01-14 16:38:05 +00002282 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002283 if (PrevDecl->TypeForDecl)
2284 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2285
John McCallf4c73712011-01-19 06:33:43 +00002286 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2287 Decl->TypeForDecl = newType;
2288 Types.push_back(newType);
2289 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002290}
2291
Jay Foad4ba2a172011-01-12 09:06:06 +00002292QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002293 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2294
Douglas Gregoref96ee02012-01-14 16:38:05 +00002295 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002296 if (PrevDecl->TypeForDecl)
2297 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2298
John McCallf4c73712011-01-19 06:33:43 +00002299 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2300 Decl->TypeForDecl = newType;
2301 Types.push_back(newType);
2302 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002303}
2304
John McCall9d156a72011-01-06 01:58:22 +00002305QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2306 QualType modifiedType,
2307 QualType equivalentType) {
2308 llvm::FoldingSetNodeID id;
2309 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2310
2311 void *insertPos = 0;
2312 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2313 if (type) return QualType(type, 0);
2314
2315 QualType canon = getCanonicalType(equivalentType);
2316 type = new (*this, TypeAlignment)
2317 AttributedType(canon, attrKind, modifiedType, equivalentType);
2318
2319 Types.push_back(type);
2320 AttributedTypes.InsertNode(type, insertPos);
2321
2322 return QualType(type, 0);
2323}
2324
2325
John McCall49a832b2009-10-18 09:09:24 +00002326/// \brief Retrieve a substitution-result type.
2327QualType
2328ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002329 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002330 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002331 && "replacement types must always be canonical");
2332
2333 llvm::FoldingSetNodeID ID;
2334 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2335 void *InsertPos = 0;
2336 SubstTemplateTypeParmType *SubstParm
2337 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2338
2339 if (!SubstParm) {
2340 SubstParm = new (*this, TypeAlignment)
2341 SubstTemplateTypeParmType(Parm, Replacement);
2342 Types.push_back(SubstParm);
2343 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2344 }
2345
2346 return QualType(SubstParm, 0);
2347}
2348
Douglas Gregorc3069d62011-01-14 02:55:32 +00002349/// \brief Retrieve a
2350QualType ASTContext::getSubstTemplateTypeParmPackType(
2351 const TemplateTypeParmType *Parm,
2352 const TemplateArgument &ArgPack) {
2353#ifndef NDEBUG
2354 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2355 PEnd = ArgPack.pack_end();
2356 P != PEnd; ++P) {
2357 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2358 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2359 }
2360#endif
2361
2362 llvm::FoldingSetNodeID ID;
2363 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2364 void *InsertPos = 0;
2365 if (SubstTemplateTypeParmPackType *SubstParm
2366 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2367 return QualType(SubstParm, 0);
2368
2369 QualType Canon;
2370 if (!Parm->isCanonicalUnqualified()) {
2371 Canon = getCanonicalType(QualType(Parm, 0));
2372 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2373 ArgPack);
2374 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2375 }
2376
2377 SubstTemplateTypeParmPackType *SubstParm
2378 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2379 ArgPack);
2380 Types.push_back(SubstParm);
2381 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2382 return QualType(SubstParm, 0);
2383}
2384
Douglas Gregorfab9d672009-02-05 23:33:38 +00002385/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002386/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002387/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002388QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002389 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002390 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002391 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002392 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002393 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002394 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002395 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2396
2397 if (TypeParm)
2398 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002399
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002400 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002401 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002402 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002403
2404 TemplateTypeParmType *TypeCheck
2405 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2406 assert(!TypeCheck && "Template type parameter canonical type broken");
2407 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002408 } else
John McCall6b304a02009-09-24 23:30:46 +00002409 TypeParm = new (*this, TypeAlignment)
2410 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002411
2412 Types.push_back(TypeParm);
2413 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2414
2415 return QualType(TypeParm, 0);
2416}
2417
John McCall3cb0ebd2010-03-10 03:28:59 +00002418TypeSourceInfo *
2419ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2420 SourceLocation NameLoc,
2421 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002422 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002423 assert(!Name.getAsDependentTemplateName() &&
2424 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002425 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002426
2427 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2428 TemplateSpecializationTypeLoc TL
2429 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002430 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00002431 TL.setTemplateNameLoc(NameLoc);
2432 TL.setLAngleLoc(Args.getLAngleLoc());
2433 TL.setRAngleLoc(Args.getRAngleLoc());
2434 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2435 TL.setArgLocInfo(i, Args[i].getLocInfo());
2436 return DI;
2437}
2438
Mike Stump1eb44332009-09-09 15:08:12 +00002439QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002440ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002441 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002442 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002443 assert(!Template.getAsDependentTemplateName() &&
2444 "No dependent template names here!");
2445
John McCalld5532b62009-11-23 01:53:49 +00002446 unsigned NumArgs = Args.size();
2447
Chris Lattner5f9e2722011-07-23 10:55:15 +00002448 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002449 ArgVec.reserve(NumArgs);
2450 for (unsigned i = 0; i != NumArgs; ++i)
2451 ArgVec.push_back(Args[i].getArgument());
2452
John McCall31f17ec2010-04-27 00:57:59 +00002453 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002454 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002455}
2456
Douglas Gregorb70126a2012-02-03 17:16:23 +00002457#ifndef NDEBUG
2458static bool hasAnyPackExpansions(const TemplateArgument *Args,
2459 unsigned NumArgs) {
2460 for (unsigned I = 0; I != NumArgs; ++I)
2461 if (Args[I].isPackExpansion())
2462 return true;
2463
2464 return true;
2465}
2466#endif
2467
John McCall833ca992009-10-29 08:12:44 +00002468QualType
2469ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002470 const TemplateArgument *Args,
2471 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002472 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002473 assert(!Template.getAsDependentTemplateName() &&
2474 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002475 // Look through qualified template names.
2476 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2477 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002478
Douglas Gregorb70126a2012-02-03 17:16:23 +00002479 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00002480 Template.getAsTemplateDecl() &&
2481 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00002482 QualType CanonType;
2483 if (!Underlying.isNull())
2484 CanonType = getCanonicalType(Underlying);
2485 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00002486 // We can get here with an alias template when the specialization contains
2487 // a pack expansion that does not match up with a parameter pack.
2488 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2489 "Caller must compute aliased type");
2490 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00002491 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2492 NumArgs);
2493 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002494
Douglas Gregor1275ae02009-07-28 23:00:59 +00002495 // Allocate the (non-canonical) template specialization type, but don't
2496 // try to unique it: these types typically have location information that
2497 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002498 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2499 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00002500 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00002501 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002502 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00002503 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2504 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00002505
Douglas Gregor55f6b142009-02-09 18:46:07 +00002506 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002507 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002508}
2509
Mike Stump1eb44332009-09-09 15:08:12 +00002510QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002511ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2512 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002513 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002514 assert(!Template.getAsDependentTemplateName() &&
2515 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002516
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002517 // Look through qualified template names.
2518 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2519 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002520
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002521 // Build the canonical template specialization type.
2522 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002523 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002524 CanonArgs.reserve(NumArgs);
2525 for (unsigned I = 0; I != NumArgs; ++I)
2526 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2527
2528 // Determine whether this canonical template specialization type already
2529 // exists.
2530 llvm::FoldingSetNodeID ID;
2531 TemplateSpecializationType::Profile(ID, CanonTemplate,
2532 CanonArgs.data(), NumArgs, *this);
2533
2534 void *InsertPos = 0;
2535 TemplateSpecializationType *Spec
2536 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2537
2538 if (!Spec) {
2539 // Allocate a new canonical template specialization type.
2540 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2541 sizeof(TemplateArgument) * NumArgs),
2542 TypeAlignment);
2543 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2544 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002545 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002546 Types.push_back(Spec);
2547 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2548 }
2549
2550 assert(Spec->isDependentType() &&
2551 "Non-dependent template-id type must have a canonical type");
2552 return QualType(Spec, 0);
2553}
2554
2555QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002556ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2557 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002558 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002559 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002560 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002561
2562 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002563 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002564 if (T)
2565 return QualType(T, 0);
2566
Douglas Gregor789b1f62010-02-04 18:10:26 +00002567 QualType Canon = NamedType;
2568 if (!Canon.isCanonical()) {
2569 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002570 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2571 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002572 (void)CheckT;
2573 }
2574
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002575 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002576 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002577 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002578 return QualType(T, 0);
2579}
2580
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002581QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002582ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002583 llvm::FoldingSetNodeID ID;
2584 ParenType::Profile(ID, InnerType);
2585
2586 void *InsertPos = 0;
2587 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2588 if (T)
2589 return QualType(T, 0);
2590
2591 QualType Canon = InnerType;
2592 if (!Canon.isCanonical()) {
2593 Canon = getCanonicalType(InnerType);
2594 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2595 assert(!CheckT && "Paren canonical type broken");
2596 (void)CheckT;
2597 }
2598
2599 T = new (*this) ParenType(InnerType, Canon);
2600 Types.push_back(T);
2601 ParenTypes.InsertNode(T, InsertPos);
2602 return QualType(T, 0);
2603}
2604
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002605QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2606 NestedNameSpecifier *NNS,
2607 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002608 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002609 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2610
2611 if (Canon.isNull()) {
2612 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002613 ElaboratedTypeKeyword CanonKeyword = Keyword;
2614 if (Keyword == ETK_None)
2615 CanonKeyword = ETK_Typename;
2616
2617 if (CanonNNS != NNS || CanonKeyword != Keyword)
2618 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002619 }
2620
2621 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002622 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002623
2624 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002625 DependentNameType *T
2626 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002627 if (T)
2628 return QualType(T, 0);
2629
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002630 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002631 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002632 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002633 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002634}
2635
Mike Stump1eb44332009-09-09 15:08:12 +00002636QualType
John McCall33500952010-06-11 00:33:02 +00002637ASTContext::getDependentTemplateSpecializationType(
2638 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002639 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002640 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002641 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00002642 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00002643 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00002644 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2645 ArgCopy.push_back(Args[I].getArgument());
2646 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2647 ArgCopy.size(),
2648 ArgCopy.data());
2649}
2650
2651QualType
2652ASTContext::getDependentTemplateSpecializationType(
2653 ElaboratedTypeKeyword Keyword,
2654 NestedNameSpecifier *NNS,
2655 const IdentifierInfo *Name,
2656 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002657 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00002658 assert((!NNS || NNS->isDependent()) &&
2659 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00002660
Douglas Gregor789b1f62010-02-04 18:10:26 +00002661 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002662 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2663 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002664
2665 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002666 DependentTemplateSpecializationType *T
2667 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002668 if (T)
2669 return QualType(T, 0);
2670
John McCall33500952010-06-11 00:33:02 +00002671 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002672
John McCall33500952010-06-11 00:33:02 +00002673 ElaboratedTypeKeyword CanonKeyword = Keyword;
2674 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2675
2676 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002677 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00002678 for (unsigned I = 0; I != NumArgs; ++I) {
2679 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2680 if (!CanonArgs[I].structurallyEquals(Args[I]))
2681 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002682 }
2683
John McCall33500952010-06-11 00:33:02 +00002684 QualType Canon;
2685 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2686 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2687 Name, NumArgs,
2688 CanonArgs.data());
2689
2690 // Find the insert position again.
2691 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2692 }
2693
2694 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2695 sizeof(TemplateArgument) * NumArgs),
2696 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002697 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002698 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002699 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002700 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002701 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002702}
2703
Douglas Gregorcded4f62011-01-14 17:04:44 +00002704QualType ASTContext::getPackExpansionType(QualType Pattern,
2705 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00002706 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002707 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002708
2709 assert(Pattern->containsUnexpandedParameterPack() &&
2710 "Pack expansions must expand one or more parameter packs");
2711 void *InsertPos = 0;
2712 PackExpansionType *T
2713 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2714 if (T)
2715 return QualType(T, 0);
2716
2717 QualType Canon;
2718 if (!Pattern.isCanonical()) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002719 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002720
2721 // Find the insert position again.
2722 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2723 }
2724
Douglas Gregorcded4f62011-01-14 17:04:44 +00002725 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002726 Types.push_back(T);
2727 PackExpansionTypes.InsertNode(T, InsertPos);
2728 return QualType(T, 0);
2729}
2730
Chris Lattner88cb27a2008-04-07 04:56:42 +00002731/// CmpProtocolNames - Comparison predicate for sorting protocols
2732/// alphabetically.
2733static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2734 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002735 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002736}
2737
John McCallc12c5bb2010-05-15 11:32:37 +00002738static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002739 unsigned NumProtocols) {
2740 if (NumProtocols == 0) return true;
2741
Douglas Gregor61cc2962012-01-02 02:00:30 +00002742 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2743 return false;
2744
John McCall54e14c42009-10-22 22:37:11 +00002745 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00002746 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2747 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00002748 return false;
2749 return true;
2750}
2751
2752static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002753 unsigned &NumProtocols) {
2754 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002755
Chris Lattner88cb27a2008-04-07 04:56:42 +00002756 // Sort protocols, keyed by name.
2757 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2758
Douglas Gregor61cc2962012-01-02 02:00:30 +00002759 // Canonicalize.
2760 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2761 Protocols[I] = Protocols[I]->getCanonicalDecl();
2762
Chris Lattner88cb27a2008-04-07 04:56:42 +00002763 // Remove duplicates.
2764 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2765 NumProtocols = ProtocolsEnd-Protocols;
2766}
2767
John McCallc12c5bb2010-05-15 11:32:37 +00002768QualType ASTContext::getObjCObjectType(QualType BaseType,
2769 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00002770 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002771 // If the base type is an interface and there aren't any protocols
2772 // to add, then the interface type will do just fine.
2773 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2774 return BaseType;
2775
2776 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002777 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002778 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002779 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002780 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2781 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002782
John McCallc12c5bb2010-05-15 11:32:37 +00002783 // Build the canonical type, which has the canonical base type and
2784 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002785 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002786 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2787 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2788 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002789 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00002790 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002791 unsigned UniqueCount = NumProtocols;
2792
John McCall54e14c42009-10-22 22:37:11 +00002793 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002794 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2795 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002796 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002797 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2798 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002799 }
2800
2801 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002802 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2803 }
2804
2805 unsigned Size = sizeof(ObjCObjectTypeImpl);
2806 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2807 void *Mem = Allocate(Size, TypeAlignment);
2808 ObjCObjectTypeImpl *T =
2809 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2810
2811 Types.push_back(T);
2812 ObjCObjectTypes.InsertNode(T, InsertPos);
2813 return QualType(T, 0);
2814}
2815
2816/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2817/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002818QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002819 llvm::FoldingSetNodeID ID;
2820 ObjCObjectPointerType::Profile(ID, ObjectT);
2821
2822 void *InsertPos = 0;
2823 if (ObjCObjectPointerType *QT =
2824 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2825 return QualType(QT, 0);
2826
2827 // Find the canonical object type.
2828 QualType Canonical;
2829 if (!ObjectT.isCanonical()) {
2830 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2831
2832 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002833 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2834 }
2835
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002836 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002837 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2838 ObjCObjectPointerType *QType =
2839 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002840
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002841 Types.push_back(QType);
2842 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002843 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002844}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002845
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002846/// getObjCInterfaceType - Return the unique reference to the type for the
2847/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00002848QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
2849 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002850 if (Decl->TypeForDecl)
2851 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002852
Douglas Gregor0af55012011-12-16 03:12:41 +00002853 if (PrevDecl) {
2854 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
2855 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2856 return QualType(PrevDecl->TypeForDecl, 0);
2857 }
2858
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00002859 // Prefer the definition, if there is one.
2860 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
2861 Decl = Def;
2862
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002863 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2864 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2865 Decl->TypeForDecl = T;
2866 Types.push_back(T);
2867 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002868}
2869
Douglas Gregor72564e72009-02-26 23:50:07 +00002870/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2871/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002872/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002873/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002874/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002875QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002876 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002877 if (tofExpr->isTypeDependent()) {
2878 llvm::FoldingSetNodeID ID;
2879 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002880
Douglas Gregorb1975722009-07-30 23:18:24 +00002881 void *InsertPos = 0;
2882 DependentTypeOfExprType *Canon
2883 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2884 if (Canon) {
2885 // We already have a "canonical" version of an identical, dependent
2886 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002887 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002888 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00002889 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00002890 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002891 Canon
2892 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002893 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2894 toe = Canon;
2895 }
2896 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002897 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002898 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002899 }
Steve Naroff9752f252007-08-01 18:02:17 +00002900 Types.push_back(toe);
2901 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002902}
2903
Steve Naroff9752f252007-08-01 18:02:17 +00002904/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2905/// TypeOfType AST's. The only motivation to unique these nodes would be
2906/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002907/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002908/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002909QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002910 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002911 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002912 Types.push_back(tot);
2913 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002914}
2915
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002916/// getDecltypeForExpr - Given an expr, will return the decltype for that
2917/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad4ba2a172011-01-12 09:06:06 +00002918static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002919 if (e->isTypeDependent())
2920 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002921
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002922 // If e is an id expression or a class member access, decltype(e) is defined
2923 // as the type of the entity named by e.
2924 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2925 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2926 return VD->getType();
2927 }
2928 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2929 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2930 return FD->getType();
2931 }
2932 // If e is a function call or an invocation of an overloaded operator,
2933 // (parentheses around e are ignored), decltype(e) is defined as the
2934 // return type of that function.
2935 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2936 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002937
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002938 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002939
2940 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002941 // defined as T&, otherwise decltype(e) is defined as T.
John McCall7eb0a9e2010-11-24 05:12:34 +00002942 if (e->isLValue())
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002943 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002944
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002945 return T;
2946}
2947
Anders Carlsson395b4752009-06-24 19:06:50 +00002948/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2949/// DecltypeType AST's. The only motivation to unique these nodes would be
2950/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002951/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00002952/// on canonical types (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002953QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002954 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00002955
2956 // C++0x [temp.type]p2:
2957 // If an expression e involves a template parameter, decltype(e) denotes a
2958 // unique dependent type. Two such decltype-specifiers refer to the same
2959 // type only if their expressions are equivalent (14.5.6.1).
2960 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002961 llvm::FoldingSetNodeID ID;
2962 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002963
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002964 void *InsertPos = 0;
2965 DependentDecltypeType *Canon
2966 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2967 if (Canon) {
2968 // We already have a "canonical" version of an equivalent, dependent
2969 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002970 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002971 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00002972 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002973 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002974 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002975 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2976 dt = Canon;
2977 }
2978 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002979 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002980 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002981 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002982 Types.push_back(dt);
2983 return QualType(dt, 0);
2984}
2985
Sean Huntca63c202011-05-24 22:41:36 +00002986/// getUnaryTransformationType - We don't unique these, since the memory
2987/// savings are minimal and these are rare.
2988QualType ASTContext::getUnaryTransformType(QualType BaseType,
2989 QualType UnderlyingType,
2990 UnaryTransformType::UTTKind Kind)
2991 const {
2992 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00002993 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2994 Kind,
2995 UnderlyingType->isDependentType() ?
2996 QualType() : UnderlyingType);
Sean Huntca63c202011-05-24 22:41:36 +00002997 Types.push_back(Ty);
2998 return QualType(Ty, 0);
2999}
3000
Richard Smith483b9f32011-02-21 20:05:19 +00003001/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00003002QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00003003 void *InsertPos = 0;
3004 if (!DeducedType.isNull()) {
3005 // Look in the folding set for an existing type.
3006 llvm::FoldingSetNodeID ID;
3007 AutoType::Profile(ID, DeducedType);
3008 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3009 return QualType(AT, 0);
3010 }
3011
3012 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3013 Types.push_back(AT);
3014 if (InsertPos)
3015 AutoTypes.InsertNode(AT, InsertPos);
3016 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003017}
3018
Eli Friedmanb001de72011-10-06 23:00:33 +00003019/// getAtomicType - Return the uniqued reference to the atomic type for
3020/// the given value type.
3021QualType ASTContext::getAtomicType(QualType T) const {
3022 // Unique pointers, to guarantee there is only one pointer of a particular
3023 // structure.
3024 llvm::FoldingSetNodeID ID;
3025 AtomicType::Profile(ID, T);
3026
3027 void *InsertPos = 0;
3028 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3029 return QualType(AT, 0);
3030
3031 // If the atomic value type isn't canonical, this won't be a canonical type
3032 // either, so fill in the canonical type field.
3033 QualType Canonical;
3034 if (!T.isCanonical()) {
3035 Canonical = getAtomicType(getCanonicalType(T));
3036
3037 // Get the new insert position for the node we care about.
3038 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3039 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3040 }
3041 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3042 Types.push_back(New);
3043 AtomicTypes.InsertNode(New, InsertPos);
3044 return QualType(New, 0);
3045}
3046
Richard Smithad762fc2011-04-14 22:09:26 +00003047/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3048QualType ASTContext::getAutoDeductType() const {
3049 if (AutoDeductTy.isNull())
3050 AutoDeductTy = getAutoType(QualType());
3051 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3052 return AutoDeductTy;
3053}
3054
3055/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3056QualType ASTContext::getAutoRRefDeductType() const {
3057 if (AutoRRefDeductTy.isNull())
3058 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3059 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3060 return AutoRRefDeductTy;
3061}
3062
Reid Spencer5f016e22007-07-11 17:01:13 +00003063/// getTagDeclType - Return the unique reference to the type for the
3064/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003065QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003066 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003067 // FIXME: What is the design on getTagDeclType when it requires casting
3068 // away const? mutable?
3069 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003070}
3071
Mike Stump1eb44332009-09-09 15:08:12 +00003072/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3073/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3074/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003075CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003076 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003077}
3078
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003079/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3080CanQualType ASTContext::getIntMaxType() const {
3081 return getFromTargetType(Target->getIntMaxType());
3082}
3083
3084/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3085CanQualType ASTContext::getUIntMaxType() const {
3086 return getFromTargetType(Target->getUIntMaxType());
3087}
3088
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003089/// getSignedWCharType - Return the type of "signed wchar_t".
3090/// Used when in C++, as a GCC extension.
3091QualType ASTContext::getSignedWCharType() const {
3092 // FIXME: derive from "Target" ?
3093 return WCharTy;
3094}
3095
3096/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3097/// Used when in C++, as a GCC extension.
3098QualType ASTContext::getUnsignedWCharType() const {
3099 // FIXME: derive from "Target" ?
3100 return UnsignedIntTy;
3101}
3102
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003103/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003104/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3105QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003106 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003107}
3108
Chris Lattnere6327742008-04-02 05:18:44 +00003109//===----------------------------------------------------------------------===//
3110// Type Operators
3111//===----------------------------------------------------------------------===//
3112
Jay Foad4ba2a172011-01-12 09:06:06 +00003113CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003114 // Push qualifiers into arrays, and then discard any remaining
3115 // qualifiers.
3116 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003117 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003118 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003119 QualType Result;
3120 if (isa<ArrayType>(Ty)) {
3121 Result = getArrayDecayedType(QualType(Ty,0));
3122 } else if (isa<FunctionType>(Ty)) {
3123 Result = getPointerType(QualType(Ty, 0));
3124 } else {
3125 Result = QualType(Ty, 0);
3126 }
3127
3128 return CanQualType::CreateUnsafe(Result);
3129}
3130
John McCall62c28c82011-01-18 07:41:22 +00003131QualType ASTContext::getUnqualifiedArrayType(QualType type,
3132 Qualifiers &quals) {
3133 SplitQualType splitType = type.getSplitUnqualifiedType();
3134
3135 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3136 // the unqualified desugared type and then drops it on the floor.
3137 // We then have to strip that sugar back off with
3138 // getUnqualifiedDesugaredType(), which is silly.
3139 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003140 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003141
3142 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003143 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003144 quals = splitType.Quals;
3145 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003146 }
3147
John McCall62c28c82011-01-18 07:41:22 +00003148 // Otherwise, recurse on the array's element type.
3149 QualType elementType = AT->getElementType();
3150 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3151
3152 // If that didn't change the element type, AT has no qualifiers, so we
3153 // can just use the results in splitType.
3154 if (elementType == unqualElementType) {
3155 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003156 quals = splitType.Quals;
3157 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003158 }
3159
3160 // Otherwise, add in the qualifiers from the outermost type, then
3161 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003162 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003163
Douglas Gregor9dadd942010-05-17 18:45:21 +00003164 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003165 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003166 CAT->getSizeModifier(), 0);
3167 }
3168
Douglas Gregor9dadd942010-05-17 18:45:21 +00003169 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003170 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003171 }
3172
Douglas Gregor9dadd942010-05-17 18:45:21 +00003173 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003174 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003175 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003176 VAT->getSizeModifier(),
3177 VAT->getIndexTypeCVRQualifiers(),
3178 VAT->getBracketsRange());
3179 }
3180
3181 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003182 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003183 DSAT->getSizeModifier(), 0,
3184 SourceRange());
3185}
3186
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003187/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3188/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3189/// they point to and return true. If T1 and T2 aren't pointer types
3190/// or pointer-to-member types, or if they are not similar at this
3191/// level, returns false and leaves T1 and T2 unchanged. Top-level
3192/// qualifiers on T1 and T2 are ignored. This function will typically
3193/// be called in a loop that successively "unwraps" pointer and
3194/// pointer-to-member types to compare them at each level.
3195bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3196 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3197 *T2PtrType = T2->getAs<PointerType>();
3198 if (T1PtrType && T2PtrType) {
3199 T1 = T1PtrType->getPointeeType();
3200 T2 = T2PtrType->getPointeeType();
3201 return true;
3202 }
3203
3204 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3205 *T2MPType = T2->getAs<MemberPointerType>();
3206 if (T1MPType && T2MPType &&
3207 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3208 QualType(T2MPType->getClass(), 0))) {
3209 T1 = T1MPType->getPointeeType();
3210 T2 = T2MPType->getPointeeType();
3211 return true;
3212 }
3213
3214 if (getLangOptions().ObjC1) {
3215 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3216 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3217 if (T1OPType && T2OPType) {
3218 T1 = T1OPType->getPointeeType();
3219 T2 = T2OPType->getPointeeType();
3220 return true;
3221 }
3222 }
3223
3224 // FIXME: Block pointers, too?
3225
3226 return false;
3227}
3228
Jay Foad4ba2a172011-01-12 09:06:06 +00003229DeclarationNameInfo
3230ASTContext::getNameForTemplate(TemplateName Name,
3231 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003232 switch (Name.getKind()) {
3233 case TemplateName::QualifiedTemplate:
3234 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003235 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003236 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3237 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003238
John McCall14606042011-06-30 08:33:18 +00003239 case TemplateName::OverloadedTemplate: {
3240 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3241 // DNInfo work in progress: CHECKME: what about DNLoc?
3242 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3243 }
3244
3245 case TemplateName::DependentTemplate: {
3246 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003247 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003248 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003249 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3250 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003251 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003252 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3253 // DNInfo work in progress: FIXME: source locations?
3254 DeclarationNameLoc DNLoc;
3255 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3256 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3257 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003258 }
3259 }
3260
John McCall14606042011-06-30 08:33:18 +00003261 case TemplateName::SubstTemplateTemplateParm: {
3262 SubstTemplateTemplateParmStorage *subst
3263 = Name.getAsSubstTemplateTemplateParm();
3264 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3265 NameLoc);
3266 }
3267
3268 case TemplateName::SubstTemplateTemplateParmPack: {
3269 SubstTemplateTemplateParmPackStorage *subst
3270 = Name.getAsSubstTemplateTemplateParmPack();
3271 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3272 NameLoc);
3273 }
3274 }
3275
3276 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003277}
3278
Jay Foad4ba2a172011-01-12 09:06:06 +00003279TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003280 switch (Name.getKind()) {
3281 case TemplateName::QualifiedTemplate:
3282 case TemplateName::Template: {
3283 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003284 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003285 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003286 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3287
3288 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003289 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003290 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003291
John McCall14606042011-06-30 08:33:18 +00003292 case TemplateName::OverloadedTemplate:
3293 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003294
John McCall14606042011-06-30 08:33:18 +00003295 case TemplateName::DependentTemplate: {
3296 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3297 assert(DTN && "Non-dependent template names must refer to template decls.");
3298 return DTN->CanonicalTemplateName;
3299 }
3300
3301 case TemplateName::SubstTemplateTemplateParm: {
3302 SubstTemplateTemplateParmStorage *subst
3303 = Name.getAsSubstTemplateTemplateParm();
3304 return getCanonicalTemplateName(subst->getReplacement());
3305 }
3306
3307 case TemplateName::SubstTemplateTemplateParmPack: {
3308 SubstTemplateTemplateParmPackStorage *subst
3309 = Name.getAsSubstTemplateTemplateParmPack();
3310 TemplateTemplateParmDecl *canonParameter
3311 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3312 TemplateArgument canonArgPack
3313 = getCanonicalTemplateArgument(subst->getArgumentPack());
3314 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3315 }
3316 }
3317
3318 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003319}
3320
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003321bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3322 X = getCanonicalTemplateName(X);
3323 Y = getCanonicalTemplateName(Y);
3324 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3325}
3326
Mike Stump1eb44332009-09-09 15:08:12 +00003327TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003328ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003329 switch (Arg.getKind()) {
3330 case TemplateArgument::Null:
3331 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003332
Douglas Gregor1275ae02009-07-28 23:00:59 +00003333 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003334 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003335
Douglas Gregor1275ae02009-07-28 23:00:59 +00003336 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00003337 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003338
Douglas Gregor788cd062009-11-11 01:00:40 +00003339 case TemplateArgument::Template:
3340 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003341
3342 case TemplateArgument::TemplateExpansion:
3343 return TemplateArgument(getCanonicalTemplateName(
3344 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003345 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003346
Douglas Gregor1275ae02009-07-28 23:00:59 +00003347 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00003348 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003349 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003350
Douglas Gregor1275ae02009-07-28 23:00:59 +00003351 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003352 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003353
Douglas Gregor1275ae02009-07-28 23:00:59 +00003354 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003355 if (Arg.pack_size() == 0)
3356 return Arg;
3357
Douglas Gregor910f8002010-11-07 23:05:16 +00003358 TemplateArgument *CanonArgs
3359 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003360 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003361 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003362 AEnd = Arg.pack_end();
3363 A != AEnd; (void)++A, ++Idx)
3364 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003365
Douglas Gregor910f8002010-11-07 23:05:16 +00003366 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003367 }
3368 }
3369
3370 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00003371 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00003372}
3373
Douglas Gregord57959a2009-03-27 23:10:48 +00003374NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003375ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003376 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003377 return 0;
3378
3379 switch (NNS->getKind()) {
3380 case NestedNameSpecifier::Identifier:
3381 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003382 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003383 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3384 NNS->getAsIdentifier());
3385
3386 case NestedNameSpecifier::Namespace:
3387 // A namespace is canonical; build a nested-name-specifier with
3388 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003389 return NestedNameSpecifier::Create(*this, 0,
3390 NNS->getAsNamespace()->getOriginalNamespace());
3391
3392 case NestedNameSpecifier::NamespaceAlias:
3393 // A namespace is canonical; build a nested-name-specifier with
3394 // this namespace and no prefix.
3395 return NestedNameSpecifier::Create(*this, 0,
3396 NNS->getAsNamespaceAlias()->getNamespace()
3397 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003398
3399 case NestedNameSpecifier::TypeSpec:
3400 case NestedNameSpecifier::TypeSpecWithTemplate: {
3401 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003402
3403 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3404 // break it apart into its prefix and identifier, then reconsititute those
3405 // as the canonical nested-name-specifier. This is required to canonicalize
3406 // a dependent nested-name-specifier involving typedefs of dependent-name
3407 // types, e.g.,
3408 // typedef typename T::type T1;
3409 // typedef typename T1::type T2;
3410 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3411 NestedNameSpecifier *Prefix
3412 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3413 return NestedNameSpecifier::Create(*this, Prefix,
3414 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3415 }
3416
Douglas Gregor643f8432010-11-04 00:14:23 +00003417 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor264bf662010-11-04 00:09:33 +00003418 if (const DependentTemplateSpecializationType *DTST
3419 = T->getAs<DependentTemplateSpecializationType>()) {
3420 NestedNameSpecifier *Prefix
3421 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003422
3423 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3424 Prefix, DTST->getIdentifier(),
3425 DTST->getNumArgs(),
3426 DTST->getArgs());
Douglas Gregor264bf662010-11-04 00:09:33 +00003427 T = getCanonicalType(T);
3428 }
3429
John McCall3b657512011-01-19 10:06:00 +00003430 return NestedNameSpecifier::Create(*this, 0, false,
3431 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003432 }
3433
3434 case NestedNameSpecifier::Global:
3435 // The global specifier is canonical and unique.
3436 return NNS;
3437 }
3438
David Blaikie7530c032012-01-17 06:56:22 +00003439 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00003440}
3441
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003442
Jay Foad4ba2a172011-01-12 09:06:06 +00003443const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003444 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003445 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003446 // Handle the common positive case fast.
3447 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3448 return AT;
3449 }
Mike Stump1eb44332009-09-09 15:08:12 +00003450
John McCall0953e762009-09-24 19:53:00 +00003451 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003452 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003453 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003454
John McCall0953e762009-09-24 19:53:00 +00003455 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003456 // implements C99 6.7.3p8: "If the specification of an array type includes
3457 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003458
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003459 // If we get here, we either have type qualifiers on the type, or we have
3460 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003461 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003462
John McCall3b657512011-01-19 10:06:00 +00003463 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00003464 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00003465
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003466 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00003467 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00003468 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003469 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003470
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003471 // Otherwise, we have an array and we have qualifiers on it. Push the
3472 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003473 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003474
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003475 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3476 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3477 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003478 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003479 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3480 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3481 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003482 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003483
Mike Stump1eb44332009-09-09 15:08:12 +00003484 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003485 = dyn_cast<DependentSizedArrayType>(ATy))
3486 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003487 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003488 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003489 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003490 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003491 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003492
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003493 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003494 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003495 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003496 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003497 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003498 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003499}
3500
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003501QualType ASTContext::getAdjustedParameterType(QualType T) {
3502 // C99 6.7.5.3p7:
3503 // A declaration of a parameter as "array of type" shall be
3504 // adjusted to "qualified pointer to type", where the type
3505 // qualifiers (if any) are those specified within the [ and ] of
3506 // the array type derivation.
3507 if (T->isArrayType())
3508 return getArrayDecayedType(T);
3509
3510 // C99 6.7.5.3p8:
3511 // A declaration of a parameter as "function returning type"
3512 // shall be adjusted to "pointer to function returning type", as
3513 // in 6.3.2.1.
3514 if (T->isFunctionType())
3515 return getPointerType(T);
3516
3517 return T;
3518}
3519
3520QualType ASTContext::getSignatureParameterType(QualType T) {
3521 T = getVariableArrayDecayedType(T);
3522 T = getAdjustedParameterType(T);
3523 return T.getUnqualifiedType();
3524}
3525
Chris Lattnere6327742008-04-02 05:18:44 +00003526/// getArrayDecayedType - Return the properly qualified result of decaying the
3527/// specified array type to a pointer. This operation is non-trivial when
3528/// handling typedefs etc. The canonical type of "T" must be an array type,
3529/// this returns a pointer to a properly qualified element of the array.
3530///
3531/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003532QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003533 // Get the element type with 'getAsArrayType' so that we don't lose any
3534 // typedefs in the element type of the array. This also handles propagation
3535 // of type qualifiers from the array type into the element type if present
3536 // (C99 6.7.3p8).
3537 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3538 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003539
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003540 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003541
3542 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003543 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003544}
3545
John McCall3b657512011-01-19 10:06:00 +00003546QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3547 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003548}
3549
John McCall3b657512011-01-19 10:06:00 +00003550QualType ASTContext::getBaseElementType(QualType type) const {
3551 Qualifiers qs;
3552 while (true) {
3553 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00003554 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00003555 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003556
John McCall3b657512011-01-19 10:06:00 +00003557 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00003558 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00003559 }
Mike Stump1eb44332009-09-09 15:08:12 +00003560
John McCall3b657512011-01-19 10:06:00 +00003561 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003562}
3563
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003564/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003565uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003566ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3567 uint64_t ElementCount = 1;
3568 do {
3569 ElementCount *= CA->getSize().getZExtValue();
3570 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3571 } while (CA);
3572 return ElementCount;
3573}
3574
Reid Spencer5f016e22007-07-11 17:01:13 +00003575/// getFloatingRank - Return a relative rank for floating point types.
3576/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003577static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003578 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003579 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003580
John McCall183700f2009-09-21 23:43:11 +00003581 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3582 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003583 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00003584 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00003585 case BuiltinType::Float: return FloatRank;
3586 case BuiltinType::Double: return DoubleRank;
3587 case BuiltinType::LongDouble: return LongDoubleRank;
3588 }
3589}
3590
Mike Stump1eb44332009-09-09 15:08:12 +00003591/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3592/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003593/// 'typeDomain' is a real floating point or complex type.
3594/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003595QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3596 QualType Domain) const {
3597 FloatingRank EltRank = getFloatingRank(Size);
3598 if (Domain->isComplexType()) {
3599 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00003600 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00003601 case FloatRank: return FloatComplexTy;
3602 case DoubleRank: return DoubleComplexTy;
3603 case LongDoubleRank: return LongDoubleComplexTy;
3604 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003605 }
Chris Lattner1361b112008-04-06 23:58:54 +00003606
3607 assert(Domain->isRealFloatingType() && "Unknown domain!");
3608 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00003609 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattner1361b112008-04-06 23:58:54 +00003610 case FloatRank: return FloatTy;
3611 case DoubleRank: return DoubleTy;
3612 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003613 }
David Blaikie561d3ab2012-01-17 02:30:50 +00003614 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00003615}
3616
Chris Lattner7cfeb082008-04-06 23:55:33 +00003617/// getFloatingTypeOrder - Compare the rank of the two specified floating
3618/// point types, ignoring the domain of the type (i.e. 'double' ==
3619/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003620/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003621int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003622 FloatingRank LHSR = getFloatingRank(LHS);
3623 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003624
Chris Lattnera75cea32008-04-06 23:38:49 +00003625 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003626 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003627 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003628 return 1;
3629 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003630}
3631
Chris Lattnerf52ab252008-04-06 22:59:24 +00003632/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3633/// routine will assert if passed a built-in type that isn't an integer or enum,
3634/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003635unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003636 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003637
Chris Lattnerf52ab252008-04-06 22:59:24 +00003638 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003639 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00003640 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003641 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003642 case BuiltinType::Char_S:
3643 case BuiltinType::Char_U:
3644 case BuiltinType::SChar:
3645 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003646 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003647 case BuiltinType::Short:
3648 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003649 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003650 case BuiltinType::Int:
3651 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003652 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003653 case BuiltinType::Long:
3654 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003655 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003656 case BuiltinType::LongLong:
3657 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003658 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003659 case BuiltinType::Int128:
3660 case BuiltinType::UInt128:
3661 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003662 }
3663}
3664
Eli Friedman04e83572009-08-20 04:21:42 +00003665/// \brief Whether this is a promotable bitfield reference according
3666/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3667///
3668/// \returns the type this bit-field will promote to, or NULL if no
3669/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00003670QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003671 if (E->isTypeDependent() || E->isValueDependent())
3672 return QualType();
3673
Eli Friedman04e83572009-08-20 04:21:42 +00003674 FieldDecl *Field = E->getBitField();
3675 if (!Field)
3676 return QualType();
3677
3678 QualType FT = Field->getType();
3679
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003680 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00003681 uint64_t IntSize = getTypeSize(IntTy);
3682 // GCC extension compatibility: if the bit-field size is less than or equal
3683 // to the size of int, it gets promoted no matter what its type is.
3684 // For instance, unsigned long bf : 4 gets promoted to signed int.
3685 if (BitWidth < IntSize)
3686 return IntTy;
3687
3688 if (BitWidth == IntSize)
3689 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3690
3691 // Types bigger than int are not subject to promotions, and therefore act
3692 // like the base type.
3693 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3694 // is ridiculous.
3695 return QualType();
3696}
3697
Eli Friedmana95d7572009-08-19 07:44:53 +00003698/// getPromotedIntegerType - Returns the type that Promotable will
3699/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3700/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003701QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003702 assert(!Promotable.isNull());
3703 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003704 if (const EnumType *ET = Promotable->getAs<EnumType>())
3705 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00003706
3707 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3708 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3709 // (3.9.1) can be converted to a prvalue of the first of the following
3710 // types that can represent all the values of its underlying type:
3711 // int, unsigned int, long int, unsigned long int, long long int, or
3712 // unsigned long long int [...]
3713 // FIXME: Is there some better way to compute this?
3714 if (BT->getKind() == BuiltinType::WChar_S ||
3715 BT->getKind() == BuiltinType::WChar_U ||
3716 BT->getKind() == BuiltinType::Char16 ||
3717 BT->getKind() == BuiltinType::Char32) {
3718 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3719 uint64_t FromSize = getTypeSize(BT);
3720 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3721 LongLongTy, UnsignedLongLongTy };
3722 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3723 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3724 if (FromSize < ToSize ||
3725 (FromSize == ToSize &&
3726 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3727 return PromoteTypes[Idx];
3728 }
3729 llvm_unreachable("char type should fit into long long");
3730 }
3731 }
3732
3733 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00003734 if (Promotable->isSignedIntegerType())
3735 return IntTy;
3736 uint64_t PromotableSize = getTypeSize(Promotable);
3737 uint64_t IntSize = getTypeSize(IntTy);
3738 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3739 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3740}
3741
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003742/// \brief Recurses in pointer/array types until it finds an objc retainable
3743/// type and returns its ownership.
3744Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3745 while (!T.isNull()) {
3746 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3747 return T.getObjCLifetime();
3748 if (T->isArrayType())
3749 T = getBaseElementType(T);
3750 else if (const PointerType *PT = T->getAs<PointerType>())
3751 T = PT->getPointeeType();
3752 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00003753 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003754 else
3755 break;
3756 }
3757
3758 return Qualifiers::OCL_None;
3759}
3760
Mike Stump1eb44332009-09-09 15:08:12 +00003761/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003762/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003763/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003764int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00003765 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3766 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003767 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003768
Chris Lattnerf52ab252008-04-06 22:59:24 +00003769 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3770 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003771
Chris Lattner7cfeb082008-04-06 23:55:33 +00003772 unsigned LHSRank = getIntegerRank(LHSC);
3773 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003774
Chris Lattner7cfeb082008-04-06 23:55:33 +00003775 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3776 if (LHSRank == RHSRank) return 0;
3777 return LHSRank > RHSRank ? 1 : -1;
3778 }
Mike Stump1eb44332009-09-09 15:08:12 +00003779
Chris Lattner7cfeb082008-04-06 23:55:33 +00003780 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3781 if (LHSUnsigned) {
3782 // If the unsigned [LHS] type is larger, return it.
3783 if (LHSRank >= RHSRank)
3784 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003785
Chris Lattner7cfeb082008-04-06 23:55:33 +00003786 // If the signed type can represent all values of the unsigned type, it
3787 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003788 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003789 return -1;
3790 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003791
Chris Lattner7cfeb082008-04-06 23:55:33 +00003792 // If the unsigned [RHS] type is larger, return it.
3793 if (RHSRank >= LHSRank)
3794 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003795
Chris Lattner7cfeb082008-04-06 23:55:33 +00003796 // If the signed type can represent all values of the unsigned type, it
3797 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003798 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003799 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003800}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003801
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003802static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003803CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3804 DeclContext *DC, IdentifierInfo *Id) {
3805 SourceLocation Loc;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003806 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003807 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003808 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003809 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003810}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003811
Mike Stump1eb44332009-09-09 15:08:12 +00003812// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003813QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003814 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003815 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003816 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003817 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003818 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003819
Anders Carlssonf06273f2007-11-19 00:25:30 +00003820 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003821
Anders Carlsson71993dd2007-08-17 05:31:46 +00003822 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003823 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003824 // int flags;
3825 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003826 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003827 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003828 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003829 FieldTypes[3] = LongTy;
3830
Anders Carlsson71993dd2007-08-17 05:31:46 +00003831 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003832 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003833 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003834 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00003835 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003836 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003837 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003838 /*Mutable=*/false,
3839 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003840 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003841 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003842 }
3843
Douglas Gregor838db382010-02-11 01:19:42 +00003844 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003845 }
Mike Stump1eb44332009-09-09 15:08:12 +00003846
Anders Carlsson71993dd2007-08-17 05:31:46 +00003847 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003848}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003849
Douglas Gregor319ac892009-04-23 22:29:11 +00003850void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003851 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003852 assert(Rec && "Invalid CFConstantStringType");
3853 CFConstantStringTypeDecl = Rec->getDecl();
3854}
3855
Jay Foad4ba2a172011-01-12 09:06:06 +00003856QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00003857 if (BlockDescriptorType)
3858 return getTagDeclType(BlockDescriptorType);
3859
3860 RecordDecl *T;
3861 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003862 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003863 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003864 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003865
3866 QualType FieldTypes[] = {
3867 UnsignedLongTy,
3868 UnsignedLongTy,
3869 };
3870
3871 const char *FieldNames[] = {
3872 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003873 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003874 };
3875
3876 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003877 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003878 SourceLocation(),
3879 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003880 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003881 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003882 /*Mutable=*/false,
3883 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003884 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003885 T->addDecl(Field);
3886 }
3887
Douglas Gregor838db382010-02-11 01:19:42 +00003888 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003889
3890 BlockDescriptorType = T;
3891
3892 return getTagDeclType(BlockDescriptorType);
3893}
3894
Jay Foad4ba2a172011-01-12 09:06:06 +00003895QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00003896 if (BlockDescriptorExtendedType)
3897 return getTagDeclType(BlockDescriptorExtendedType);
3898
3899 RecordDecl *T;
3900 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003901 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003902 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003903 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003904
3905 QualType FieldTypes[] = {
3906 UnsignedLongTy,
3907 UnsignedLongTy,
3908 getPointerType(VoidPtrTy),
3909 getPointerType(VoidPtrTy)
3910 };
3911
3912 const char *FieldNames[] = {
3913 "reserved",
3914 "Size",
3915 "CopyFuncPtr",
3916 "DestroyFuncPtr"
3917 };
3918
3919 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003920 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00003921 SourceLocation(),
3922 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003923 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003924 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003925 /*Mutable=*/false,
3926 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003927 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003928 T->addDecl(Field);
3929 }
3930
Douglas Gregor838db382010-02-11 01:19:42 +00003931 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003932
3933 BlockDescriptorExtendedType = T;
3934
3935 return getTagDeclType(BlockDescriptorExtendedType);
3936}
3937
Jay Foad4ba2a172011-01-12 09:06:06 +00003938bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCallf85e1932011-06-15 23:02:42 +00003939 if (Ty->isObjCRetainableType())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003940 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003941 if (getLangOptions().CPlusPlus) {
3942 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3943 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Huntffe37fd2011-05-25 20:50:04 +00003944 return RD->hasConstCopyConstructor();
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003945
3946 }
3947 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003948 return false;
3949}
3950
Jay Foad4ba2a172011-01-12 09:06:06 +00003951QualType
Chris Lattner5f9e2722011-07-23 10:55:15 +00003952ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003953 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003954 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003955 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003956 // unsigned int __flags;
3957 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003958 // void *__copy_helper; // as needed
3959 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003960 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003961 // } *
3962
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003963 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3964
3965 // FIXME: Move up
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003966 SmallString<36> Name;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003967 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3968 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003969 RecordDecl *T;
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003970 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003971 T->startDefinition();
3972 QualType Int32Ty = IntTy;
3973 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3974 QualType FieldTypes[] = {
3975 getPointerType(VoidPtrTy),
3976 getPointerType(getTagDeclType(T)),
3977 Int32Ty,
3978 Int32Ty,
3979 getPointerType(VoidPtrTy),
3980 getPointerType(VoidPtrTy),
3981 Ty
3982 };
3983
Chris Lattner5f9e2722011-07-23 10:55:15 +00003984 StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003985 "__isa",
3986 "__forwarding",
3987 "__flags",
3988 "__size",
3989 "__copy_helper",
3990 "__destroy_helper",
3991 DeclName,
3992 };
3993
3994 for (size_t i = 0; i < 7; ++i) {
3995 if (!HasCopyAndDispose && i >=4 && i <= 5)
3996 continue;
3997 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003998 SourceLocation(),
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003999 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004000 FieldTypes[i], /*TInfo=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004001 /*BitWidth=*/0, /*Mutable=*/false,
4002 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00004003 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004004 T->addDecl(Field);
4005 }
4006
Douglas Gregor838db382010-02-11 01:19:42 +00004007 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004008
4009 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00004010}
4011
Douglas Gregore97179c2011-09-08 01:46:34 +00004012TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4013 if (!ObjCInstanceTypeDecl)
4014 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4015 getTranslationUnitDecl(),
4016 SourceLocation(),
4017 SourceLocation(),
4018 &Idents.get("instancetype"),
4019 getTrivialTypeSourceInfo(getObjCIdType()));
4020 return ObjCInstanceTypeDecl;
4021}
4022
Anders Carlssone8c49532007-10-29 06:33:42 +00004023// This returns true if a type has been typedefed to BOOL:
4024// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004025static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004026 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004027 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4028 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004029
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004030 return false;
4031}
4032
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004033/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004034/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004035CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004036 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4037 return CharUnits::Zero();
4038
Ken Dyck199c3d62010-01-11 17:06:35 +00004039 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004040
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004041 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004042 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004043 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004044 // Treat arrays as pointers, since that's how they're passed in.
4045 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004046 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004047 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004048}
4049
4050static inline
4051std::string charUnitsToString(const CharUnits &CU) {
4052 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004053}
4054
John McCall6b5a61b2011-02-07 10:33:21 +00004055/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004056/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004057std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4058 std::string S;
4059
David Chisnall5e530af2009-11-17 19:33:30 +00004060 const BlockDecl *Decl = Expr->getBlockDecl();
4061 QualType BlockTy =
4062 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4063 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00004064 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00004065 // Compute size of all parameters.
4066 // Start with computing size of a pointer in number of bytes.
4067 // FIXME: There might(should) be a better way of doing this computation!
4068 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004069 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4070 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004071 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004072 E = Decl->param_end(); PI != E; ++PI) {
4073 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004074 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00004075 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004076 ParmOffset += sz;
4077 }
4078 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004079 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004080 // Block pointer and offset.
4081 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004082
4083 // Argument types.
4084 ParmOffset = PtrSize;
4085 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4086 Decl->param_end(); PI != E; ++PI) {
4087 ParmVarDecl *PVDecl = *PI;
4088 QualType PType = PVDecl->getOriginalType();
4089 if (const ArrayType *AT =
4090 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4091 // Use array's original type only if it has known number of
4092 // elements.
4093 if (!isa<ConstantArrayType>(AT))
4094 PType = PVDecl->getType();
4095 } else if (PType->isFunctionType())
4096 PType = PVDecl->getType();
4097 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004098 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004099 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004100 }
John McCall6b5a61b2011-02-07 10:33:21 +00004101
4102 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004103}
4104
Douglas Gregorf968d832011-05-27 01:19:52 +00004105bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004106 std::string& S) {
4107 // Encode result type.
4108 getObjCEncodingForType(Decl->getResultType(), S);
4109 CharUnits ParmOffset;
4110 // Compute size of all parameters.
4111 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4112 E = Decl->param_end(); PI != E; ++PI) {
4113 QualType PType = (*PI)->getType();
4114 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004115 if (sz.isZero())
4116 return true;
4117
David Chisnall5389f482010-12-30 14:05:53 +00004118 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004119 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004120 ParmOffset += sz;
4121 }
4122 S += charUnitsToString(ParmOffset);
4123 ParmOffset = CharUnits::Zero();
4124
4125 // Argument types.
4126 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4127 E = Decl->param_end(); PI != E; ++PI) {
4128 ParmVarDecl *PVDecl = *PI;
4129 QualType PType = PVDecl->getOriginalType();
4130 if (const ArrayType *AT =
4131 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4132 // Use array's original type only if it has known number of
4133 // elements.
4134 if (!isa<ConstantArrayType>(AT))
4135 PType = PVDecl->getType();
4136 } else if (PType->isFunctionType())
4137 PType = PVDecl->getType();
4138 getObjCEncodingForType(PType, S);
4139 S += charUnitsToString(ParmOffset);
4140 ParmOffset += getObjCEncodingTypeSize(PType);
4141 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004142
4143 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004144}
4145
Bob Wilsondc8dab62011-11-30 01:57:58 +00004146/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4147/// method parameter or return type. If Extended, include class names and
4148/// block object types.
4149void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4150 QualType T, std::string& S,
4151 bool Extended) const {
4152 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4153 getObjCEncodingForTypeQualifier(QT, S);
4154 // Encode parameter type.
4155 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4156 true /*OutermostType*/,
4157 false /*EncodingProperty*/,
4158 false /*StructField*/,
4159 Extended /*EncodeBlockParameters*/,
4160 Extended /*EncodeClassNames*/);
4161}
4162
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004163/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004164/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004165bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004166 std::string& S,
4167 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004168 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004169 // Encode return type.
4170 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4171 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004172 // Compute size of all parameters.
4173 // Start with computing size of a pointer in number of bytes.
4174 // FIXME: There might(should) be a better way of doing this computation!
4175 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004176 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004177 // The first two arguments (self and _cmd) are pointers; account for
4178 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004179 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004180 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004181 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004182 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004183 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004184 if (sz.isZero())
4185 return true;
4186
Ken Dyck199c3d62010-01-11 17:06:35 +00004187 assert (sz.isPositive() &&
4188 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004189 ParmOffset += sz;
4190 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004191 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004192 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004193 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004194
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004195 // Argument types.
4196 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004197 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004198 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004199 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004200 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004201 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004202 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4203 // Use array's original type only if it has known number of
4204 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004205 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004206 PType = PVDecl->getType();
4207 } else if (PType->isFunctionType())
4208 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004209 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4210 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004211 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004212 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004213 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004214
4215 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004216}
4217
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004218/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004219/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004220/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4221/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004222/// Property attributes are stored as a comma-delimited C string. The simple
4223/// attributes readonly and bycopy are encoded as single characters. The
4224/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4225/// encoded as single characters, followed by an identifier. Property types
4226/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004227/// these attributes are defined by the following enumeration:
4228/// @code
4229/// enum PropertyAttributes {
4230/// kPropertyReadOnly = 'R', // property is read-only.
4231/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4232/// kPropertyByref = '&', // property is a reference to the value last assigned
4233/// kPropertyDynamic = 'D', // property is dynamic
4234/// kPropertyGetter = 'G', // followed by getter selector name
4235/// kPropertySetter = 'S', // followed by setter selector name
4236/// kPropertyInstanceVariable = 'V' // followed by instance variable name
4237/// kPropertyType = 't' // followed by old-style type encoding.
4238/// kPropertyWeak = 'W' // 'weak' property
4239/// kPropertyStrong = 'P' // property GC'able
4240/// kPropertyNonAtomic = 'N' // property non-atomic
4241/// };
4242/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004243void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004244 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004245 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004246 // Collect information from the property implementation decl(s).
4247 bool Dynamic = false;
4248 ObjCPropertyImplDecl *SynthesizePID = 0;
4249
4250 // FIXME: Duplicated code due to poor abstraction.
4251 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004252 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004253 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4254 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004255 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004256 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004257 ObjCPropertyImplDecl *PID = *i;
4258 if (PID->getPropertyDecl() == PD) {
4259 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4260 Dynamic = true;
4261 } else {
4262 SynthesizePID = PID;
4263 }
4264 }
4265 }
4266 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004267 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004268 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004269 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004270 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004271 ObjCPropertyImplDecl *PID = *i;
4272 if (PID->getPropertyDecl() == PD) {
4273 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4274 Dynamic = true;
4275 } else {
4276 SynthesizePID = PID;
4277 }
4278 }
Mike Stump1eb44332009-09-09 15:08:12 +00004279 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004280 }
4281 }
4282
4283 // FIXME: This is not very efficient.
4284 S = "T";
4285
4286 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004287 // GCC has some special rules regarding encoding of properties which
4288 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004289 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004290 true /* outermost type */,
4291 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004292
4293 if (PD->isReadOnly()) {
4294 S += ",R";
4295 } else {
4296 switch (PD->getSetterKind()) {
4297 case ObjCPropertyDecl::Assign: break;
4298 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004299 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004300 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004301 }
4302 }
4303
4304 // It really isn't clear at all what this means, since properties
4305 // are "dynamic by default".
4306 if (Dynamic)
4307 S += ",D";
4308
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004309 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4310 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004311
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004312 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4313 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004314 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004315 }
4316
4317 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4318 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004319 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004320 }
4321
4322 if (SynthesizePID) {
4323 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4324 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004325 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004326 }
4327
4328 // FIXME: OBJCGC: weak & strong
4329}
4330
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004331/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004332/// Another legacy compatibility encoding: 32-bit longs are encoded as
4333/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004334/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4335///
4336void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004337 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004338 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004339 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004340 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004341 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004342 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004343 PointeeTy = IntTy;
4344 }
4345 }
4346}
4347
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004348void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004349 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004350 // We follow the behavior of gcc, expanding structures which are
4351 // directly pointed to, and expanding embedded structures. Note that
4352 // these rules are sufficient to prevent recursive encoding of the
4353 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004354 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004355 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004356}
4357
David Chisnall64fd7e82010-06-04 01:10:52 +00004358static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4359 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004360 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnall64fd7e82010-06-04 01:10:52 +00004361 case BuiltinType::Void: return 'v';
4362 case BuiltinType::Bool: return 'B';
4363 case BuiltinType::Char_U:
4364 case BuiltinType::UChar: return 'C';
4365 case BuiltinType::UShort: return 'S';
4366 case BuiltinType::UInt: return 'I';
4367 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00004368 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004369 case BuiltinType::UInt128: return 'T';
4370 case BuiltinType::ULongLong: return 'Q';
4371 case BuiltinType::Char_S:
4372 case BuiltinType::SChar: return 'c';
4373 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004374 case BuiltinType::WChar_S:
4375 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004376 case BuiltinType::Int: return 'i';
4377 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00004378 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004379 case BuiltinType::LongLong: return 'q';
4380 case BuiltinType::Int128: return 't';
4381 case BuiltinType::Float: return 'f';
4382 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004383 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004384 }
4385}
4386
Douglas Gregor5471bc82011-09-08 17:18:35 +00004387static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4388 EnumDecl *Enum = ET->getDecl();
4389
4390 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4391 if (!Enum->isFixed())
4392 return 'i';
4393
4394 // The encoding of a fixed enum type matches its fixed underlying type.
4395 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4396}
4397
Jay Foad4ba2a172011-01-12 09:06:06 +00004398static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004399 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004400 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004401 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004402 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4403 // The GNU runtime requires more information; bitfields are encoded as b,
4404 // then the offset (in bits) of the first element, then the type of the
4405 // bitfield, then the size in bits. For example, in this structure:
4406 //
4407 // struct
4408 // {
4409 // int integer;
4410 // int flags:2;
4411 // };
4412 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4413 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4414 // information is not especially sensible, but we're stuck with it for
4415 // compatibility with GCC, although providing it breaks anything that
4416 // actually uses runtime introspection and wants to work on both runtimes...
4417 if (!Ctx->getLangOptions().NeXTRuntime) {
4418 const RecordDecl *RD = FD->getParent();
4419 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004420 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00004421 if (const EnumType *ET = T->getAs<EnumType>())
4422 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnallc7ff82c2010-12-26 20:12:30 +00004423 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004424 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004425 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004426 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004427}
4428
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004429// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004430void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4431 bool ExpandPointedToStructures,
4432 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004433 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004434 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004435 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004436 bool StructField,
4437 bool EncodeBlockParameters,
4438 bool EncodeClassNames) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004439 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004440 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004441 return EncodeBitField(this, S, T, FD);
4442 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004443 return;
4444 }
Mike Stump1eb44332009-09-09 15:08:12 +00004445
John McCall183700f2009-09-21 23:43:11 +00004446 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004447 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004448 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004449 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004450 return;
4451 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004452
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004453 // encoding for pointer or r3eference types.
4454 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004455 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004456 if (PT->isObjCSelType()) {
4457 S += ':';
4458 return;
4459 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004460 PointeeTy = PT->getPointeeType();
4461 }
4462 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4463 PointeeTy = RT->getPointeeType();
4464 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004465 bool isReadOnly = false;
4466 // For historical/compatibility reasons, the read-only qualifier of the
4467 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4468 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004469 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004470 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004471 if (OutermostType && T.isConstQualified()) {
4472 isReadOnly = true;
4473 S += 'r';
4474 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004475 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004476 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004477 while (P->getAs<PointerType>())
4478 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004479 if (P.isConstQualified()) {
4480 isReadOnly = true;
4481 S += 'r';
4482 }
4483 }
4484 if (isReadOnly) {
4485 // Another legacy compatibility encoding. Some ObjC qualifier and type
4486 // combinations need to be rearranged.
4487 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00004488 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00004489 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004490 }
Mike Stump1eb44332009-09-09 15:08:12 +00004491
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004492 if (PointeeTy->isCharType()) {
4493 // char pointer types should be encoded as '*' unless it is a
4494 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004495 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004496 S += '*';
4497 return;
4498 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004499 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004500 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4501 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4502 S += '#';
4503 return;
4504 }
4505 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4506 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4507 S += '@';
4508 return;
4509 }
4510 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004511 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004512 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004513 getLegacyIntegralTypeEncoding(PointeeTy);
4514
Mike Stump1eb44332009-09-09 15:08:12 +00004515 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004516 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004517 return;
4518 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004519
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004520 if (const ArrayType *AT =
4521 // Ignore type qualifiers etc.
4522 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004523 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004524 // Incomplete arrays are encoded as a pointer to the array element.
4525 S += '^';
4526
Mike Stump1eb44332009-09-09 15:08:12 +00004527 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004528 false, ExpandStructures, FD);
4529 } else {
4530 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004531
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004532 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4533 if (getTypeSize(CAT->getElementType()) == 0)
4534 S += '0';
4535 else
4536 S += llvm::utostr(CAT->getSize().getZExtValue());
4537 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00004538 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004539 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4540 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00004541 S += '0';
4542 }
Mike Stump1eb44332009-09-09 15:08:12 +00004543
4544 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004545 false, ExpandStructures, FD);
4546 S += ']';
4547 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004548 return;
4549 }
Mike Stump1eb44332009-09-09 15:08:12 +00004550
John McCall183700f2009-09-21 23:43:11 +00004551 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004552 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004553 return;
4554 }
Mike Stump1eb44332009-09-09 15:08:12 +00004555
Ted Kremenek6217b802009-07-29 21:53:49 +00004556 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004557 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004558 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004559 // Anonymous structures print as '?'
4560 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4561 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004562 if (ClassTemplateSpecializationDecl *Spec
4563 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4564 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4565 std::string TemplateArgsStr
4566 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004567 TemplateArgs.data(),
4568 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00004569 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004570
4571 S += TemplateArgsStr;
4572 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004573 } else {
4574 S += '?';
4575 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004576 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004577 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004578 if (!RDecl->isUnion()) {
4579 getObjCEncodingForStructureImpl(RDecl, S, FD);
4580 } else {
4581 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4582 FieldEnd = RDecl->field_end();
4583 Field != FieldEnd; ++Field) {
4584 if (FD) {
4585 S += '"';
4586 S += Field->getNameAsString();
4587 S += '"';
4588 }
Mike Stump1eb44332009-09-09 15:08:12 +00004589
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004590 // Special case bit-fields.
4591 if (Field->isBitField()) {
4592 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4593 (*Field));
4594 } else {
4595 QualType qt = Field->getType();
4596 getLegacyIntegralTypeEncoding(qt);
4597 getObjCEncodingForTypeImpl(qt, S, false, true,
4598 FD, /*OutermostType*/false,
4599 /*EncodingProperty*/false,
4600 /*StructField*/true);
4601 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004602 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004603 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004604 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004605 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004606 return;
4607 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004608
Douglas Gregor5471bc82011-09-08 17:18:35 +00004609 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004610 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004611 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004612 else
Douglas Gregor5471bc82011-09-08 17:18:35 +00004613 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004614 return;
4615 }
Mike Stump1eb44332009-09-09 15:08:12 +00004616
Bob Wilsondc8dab62011-11-30 01:57:58 +00004617 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004618 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00004619 if (EncodeBlockParameters) {
4620 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4621
4622 S += '<';
4623 // Block return type
4624 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4625 ExpandPointedToStructures, ExpandStructures,
4626 FD,
4627 false /* OutermostType */,
4628 EncodingProperty,
4629 false /* StructField */,
4630 EncodeBlockParameters,
4631 EncodeClassNames);
4632 // Block self
4633 S += "@?";
4634 // Block parameters
4635 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4636 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4637 E = FPT->arg_type_end(); I && (I != E); ++I) {
4638 getObjCEncodingForTypeImpl(*I, S,
4639 ExpandPointedToStructures,
4640 ExpandStructures,
4641 FD,
4642 false /* OutermostType */,
4643 EncodingProperty,
4644 false /* StructField */,
4645 EncodeBlockParameters,
4646 EncodeClassNames);
4647 }
4648 }
4649 S += '>';
4650 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004651 return;
4652 }
Mike Stump1eb44332009-09-09 15:08:12 +00004653
John McCallc12c5bb2010-05-15 11:32:37 +00004654 // Ignore protocol qualifiers when mangling at this level.
4655 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4656 T = OT->getBaseType();
4657
John McCall0953e762009-09-24 19:53:00 +00004658 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004659 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004660 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004661 S += '{';
4662 const IdentifierInfo *II = OI->getIdentifier();
4663 S += II->getName();
4664 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00004665 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004666 DeepCollectObjCIvars(OI, true, Ivars);
4667 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00004668 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004669 if (Field->isBitField())
4670 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004671 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004672 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004673 }
4674 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004675 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004676 }
Mike Stump1eb44332009-09-09 15:08:12 +00004677
John McCall183700f2009-09-21 23:43:11 +00004678 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004679 if (OPT->isObjCIdType()) {
4680 S += '@';
4681 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004682 }
Mike Stump1eb44332009-09-09 15:08:12 +00004683
Steve Naroff27d20a22009-10-28 22:03:49 +00004684 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4685 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4686 // Since this is a binary compatibility issue, need to consult with runtime
4687 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004688 S += '#';
4689 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004690 }
Mike Stump1eb44332009-09-09 15:08:12 +00004691
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004692 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004693 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004694 ExpandPointedToStructures,
4695 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00004696 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00004697 // Note that we do extended encoding of protocol qualifer list
4698 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004699 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004700 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4701 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004702 S += '<';
4703 S += (*I)->getNameAsString();
4704 S += '>';
4705 }
4706 S += '"';
4707 }
4708 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004709 }
Mike Stump1eb44332009-09-09 15:08:12 +00004710
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004711 QualType PointeeTy = OPT->getPointeeType();
4712 if (!EncodingProperty &&
4713 isa<TypedefType>(PointeeTy.getTypePtr())) {
4714 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004715 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004716 // {...};
4717 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004718 getObjCEncodingForTypeImpl(PointeeTy, S,
4719 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004720 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004721 return;
4722 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004723
4724 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00004725 if (OPT->getInterfaceDecl() &&
4726 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004727 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004728 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004729 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4730 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004731 S += '<';
4732 S += (*I)->getNameAsString();
4733 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004734 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004735 S += '"';
4736 }
4737 return;
4738 }
Mike Stump1eb44332009-09-09 15:08:12 +00004739
John McCall532ec7b2010-05-17 23:56:34 +00004740 // gcc just blithely ignores member pointers.
4741 // TODO: maybe there should be a mangling for these
4742 if (T->getAs<MemberPointerType>())
4743 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004744
4745 if (T->isVectorType()) {
4746 // This matches gcc's encoding, even though technically it is
4747 // insufficient.
4748 // FIXME. We should do a better job than gcc.
4749 return;
4750 }
4751
David Blaikieb219cfc2011-09-23 05:06:16 +00004752 llvm_unreachable("@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004753}
4754
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004755void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4756 std::string &S,
4757 const FieldDecl *FD,
4758 bool includeVBases) const {
4759 assert(RDecl && "Expected non-null RecordDecl");
4760 assert(!RDecl->isUnion() && "Should not be called for unions");
4761 if (!RDecl->getDefinition())
4762 return;
4763
4764 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4765 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4766 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4767
4768 if (CXXRec) {
4769 for (CXXRecordDecl::base_class_iterator
4770 BI = CXXRec->bases_begin(),
4771 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4772 if (!BI->isVirtual()) {
4773 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004774 if (base->isEmpty())
4775 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004776 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4777 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4778 std::make_pair(offs, base));
4779 }
4780 }
4781 }
4782
4783 unsigned i = 0;
4784 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4785 FieldEnd = RDecl->field_end();
4786 Field != FieldEnd; ++Field, ++i) {
4787 uint64_t offs = layout.getFieldOffset(i);
4788 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4789 std::make_pair(offs, *Field));
4790 }
4791
4792 if (CXXRec && includeVBases) {
4793 for (CXXRecordDecl::base_class_iterator
4794 BI = CXXRec->vbases_begin(),
4795 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4796 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004797 if (base->isEmpty())
4798 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004799 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00004800 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4801 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4802 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004803 }
4804 }
4805
4806 CharUnits size;
4807 if (CXXRec) {
4808 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4809 } else {
4810 size = layout.getSize();
4811 }
4812
4813 uint64_t CurOffs = 0;
4814 std::multimap<uint64_t, NamedDecl *>::iterator
4815 CurLayObj = FieldOrBaseOffsets.begin();
4816
Argyrios Kyrtzidiscb8061e2011-08-22 16:03:14 +00004817 if ((CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) ||
4818 (CurLayObj == FieldOrBaseOffsets.end() &&
4819 CXXRec && CXXRec->isDynamicClass())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004820 assert(CXXRec && CXXRec->isDynamicClass() &&
4821 "Offset 0 was empty but no VTable ?");
4822 if (FD) {
4823 S += "\"_vptr$";
4824 std::string recname = CXXRec->getNameAsString();
4825 if (recname.empty()) recname = "?";
4826 S += recname;
4827 S += '"';
4828 }
4829 S += "^^?";
4830 CurOffs += getTypeSize(VoidPtrTy);
4831 }
4832
4833 if (!RDecl->hasFlexibleArrayMember()) {
4834 // Mark the end of the structure.
4835 uint64_t offs = toBits(size);
4836 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4837 std::make_pair(offs, (NamedDecl*)0));
4838 }
4839
4840 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4841 assert(CurOffs <= CurLayObj->first);
4842
4843 if (CurOffs < CurLayObj->first) {
4844 uint64_t padding = CurLayObj->first - CurOffs;
4845 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4846 // packing/alignment of members is different that normal, in which case
4847 // the encoding will be out-of-sync with the real layout.
4848 // If the runtime switches to just consider the size of types without
4849 // taking into account alignment, we could make padding explicit in the
4850 // encoding (e.g. using arrays of chars). The encoding strings would be
4851 // longer then though.
4852 CurOffs += padding;
4853 }
4854
4855 NamedDecl *dcl = CurLayObj->second;
4856 if (dcl == 0)
4857 break; // reached end of structure.
4858
4859 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4860 // We expand the bases without their virtual bases since those are going
4861 // in the initial structure. Note that this differs from gcc which
4862 // expands virtual bases each time one is encountered in the hierarchy,
4863 // making the encoding type bigger than it really is.
4864 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004865 assert(!base->isEmpty());
4866 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004867 } else {
4868 FieldDecl *field = cast<FieldDecl>(dcl);
4869 if (FD) {
4870 S += '"';
4871 S += field->getNameAsString();
4872 S += '"';
4873 }
4874
4875 if (field->isBitField()) {
4876 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004877 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004878 } else {
4879 QualType qt = field->getType();
4880 getLegacyIntegralTypeEncoding(qt);
4881 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4882 /*OutermostType*/false,
4883 /*EncodingProperty*/false,
4884 /*StructField*/true);
4885 CurOffs += getTypeSize(field->getType());
4886 }
4887 }
4888 }
4889}
4890
Mike Stump1eb44332009-09-09 15:08:12 +00004891void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004892 std::string& S) const {
4893 if (QT & Decl::OBJC_TQ_In)
4894 S += 'n';
4895 if (QT & Decl::OBJC_TQ_Inout)
4896 S += 'N';
4897 if (QT & Decl::OBJC_TQ_Out)
4898 S += 'o';
4899 if (QT & Decl::OBJC_TQ_Bycopy)
4900 S += 'O';
4901 if (QT & Decl::OBJC_TQ_Byref)
4902 S += 'R';
4903 if (QT & Decl::OBJC_TQ_Oneway)
4904 S += 'V';
4905}
4906
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004907void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004908 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004909
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004910 BuiltinVaListType = T;
4911}
4912
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00004913TypedefDecl *ASTContext::getObjCIdDecl() const {
4914 if (!ObjCIdDecl) {
4915 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4916 T = getObjCObjectPointerType(T);
4917 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4918 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4919 getTranslationUnitDecl(),
4920 SourceLocation(), SourceLocation(),
4921 &Idents.get("id"), IdInfo);
4922 }
4923
4924 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00004925}
4926
Douglas Gregor7a27ea52011-08-12 06:17:30 +00004927TypedefDecl *ASTContext::getObjCSelDecl() const {
4928 if (!ObjCSelDecl) {
4929 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4930 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4931 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4932 getTranslationUnitDecl(),
4933 SourceLocation(), SourceLocation(),
4934 &Idents.get("SEL"), SelInfo);
4935 }
4936 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004937}
4938
Douglas Gregor79d67262011-08-12 05:59:41 +00004939TypedefDecl *ASTContext::getObjCClassDecl() const {
4940 if (!ObjCClassDecl) {
4941 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4942 T = getObjCObjectPointerType(T);
4943 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4944 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4945 getTranslationUnitDecl(),
4946 SourceLocation(), SourceLocation(),
4947 &Idents.get("Class"), ClassInfo);
4948 }
4949
4950 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004951}
4952
Douglas Gregora6ea10e2012-01-17 18:09:05 +00004953ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
4954 if (!ObjCProtocolClassDecl) {
4955 ObjCProtocolClassDecl
4956 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
4957 SourceLocation(),
4958 &Idents.get("Protocol"),
4959 /*PrevDecl=*/0,
4960 SourceLocation(), true);
4961 }
4962
4963 return ObjCProtocolClassDecl;
4964}
4965
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004966void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004967 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004968 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004969
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004970 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004971}
4972
John McCall0bd6feb2009-12-02 08:04:21 +00004973/// \brief Retrieve the template name that corresponds to a non-empty
4974/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00004975TemplateName
4976ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4977 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00004978 unsigned size = End - Begin;
4979 assert(size > 1 && "set is not overloaded!");
4980
4981 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4982 size * sizeof(FunctionTemplateDecl*));
4983 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4984
4985 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004986 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004987 NamedDecl *D = *I;
4988 assert(isa<FunctionTemplateDecl>(D) ||
4989 (isa<UsingShadowDecl>(D) &&
4990 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4991 *Storage++ = D;
4992 }
4993
4994 return TemplateName(OT);
4995}
4996
Douglas Gregor7532dc62009-03-30 22:58:21 +00004997/// \brief Retrieve the template name that represents a qualified
4998/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00004999TemplateName
5000ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5001 bool TemplateKeyword,
5002 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00005003 assert(NNS && "Missing nested-name-specifier in qualified template name");
5004
Douglas Gregor789b1f62010-02-04 18:10:26 +00005005 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00005006 llvm::FoldingSetNodeID ID;
5007 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5008
5009 void *InsertPos = 0;
5010 QualifiedTemplateName *QTN =
5011 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5012 if (!QTN) {
5013 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
5014 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5015 }
5016
5017 return TemplateName(QTN);
5018}
5019
5020/// \brief Retrieve the template name that represents a dependent
5021/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00005022TemplateName
5023ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5024 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00005025 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00005026 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00005027
5028 llvm::FoldingSetNodeID ID;
5029 DependentTemplateName::Profile(ID, NNS, Name);
5030
5031 void *InsertPos = 0;
5032 DependentTemplateName *QTN =
5033 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5034
5035 if (QTN)
5036 return TemplateName(QTN);
5037
5038 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5039 if (CanonNNS == NNS) {
5040 QTN = new (*this,4) DependentTemplateName(NNS, Name);
5041 } else {
5042 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5043 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005044 DependentTemplateName *CheckQTN =
5045 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5046 assert(!CheckQTN && "Dependent type name canonicalization broken");
5047 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00005048 }
5049
5050 DependentTemplateNames.InsertNode(QTN, InsertPos);
5051 return TemplateName(QTN);
5052}
5053
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005054/// \brief Retrieve the template name that represents a dependent
5055/// template name such as \c MetaFun::template operator+.
5056TemplateName
5057ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00005058 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005059 assert((!NNS || NNS->isDependent()) &&
5060 "Nested name specifier must be dependent");
5061
5062 llvm::FoldingSetNodeID ID;
5063 DependentTemplateName::Profile(ID, NNS, Operator);
5064
5065 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00005066 DependentTemplateName *QTN
5067 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005068
5069 if (QTN)
5070 return TemplateName(QTN);
5071
5072 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5073 if (CanonNNS == NNS) {
5074 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5075 } else {
5076 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5077 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005078
5079 DependentTemplateName *CheckQTN
5080 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5081 assert(!CheckQTN && "Dependent template name canonicalization broken");
5082 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005083 }
5084
5085 DependentTemplateNames.InsertNode(QTN, InsertPos);
5086 return TemplateName(QTN);
5087}
5088
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005089TemplateName
John McCall14606042011-06-30 08:33:18 +00005090ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5091 TemplateName replacement) const {
5092 llvm::FoldingSetNodeID ID;
5093 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5094
5095 void *insertPos = 0;
5096 SubstTemplateTemplateParmStorage *subst
5097 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5098
5099 if (!subst) {
5100 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5101 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5102 }
5103
5104 return TemplateName(subst);
5105}
5106
5107TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005108ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5109 const TemplateArgument &ArgPack) const {
5110 ASTContext &Self = const_cast<ASTContext &>(*this);
5111 llvm::FoldingSetNodeID ID;
5112 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5113
5114 void *InsertPos = 0;
5115 SubstTemplateTemplateParmPackStorage *Subst
5116 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5117
5118 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00005119 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005120 ArgPack.pack_size(),
5121 ArgPack.pack_begin());
5122 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5123 }
5124
5125 return TemplateName(Subst);
5126}
5127
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005128/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00005129/// TargetInfo, produce the corresponding type. The unsigned @p Type
5130/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00005131CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005132 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00005133 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005134 case TargetInfo::SignedShort: return ShortTy;
5135 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5136 case TargetInfo::SignedInt: return IntTy;
5137 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5138 case TargetInfo::SignedLong: return LongTy;
5139 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5140 case TargetInfo::SignedLongLong: return LongLongTy;
5141 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5142 }
5143
David Blaikieb219cfc2011-09-23 05:06:16 +00005144 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005145}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00005146
5147//===----------------------------------------------------------------------===//
5148// Type Predicates.
5149//===----------------------------------------------------------------------===//
5150
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005151/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5152/// garbage collection attribute.
5153///
John McCallae278a32011-01-12 00:34:59 +00005154Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
Douglas Gregore289d812011-09-13 17:21:33 +00005155 if (getLangOptions().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00005156 return Qualifiers::GCNone;
5157
5158 assert(getLangOptions().ObjC1);
5159 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5160
5161 // Default behaviour under objective-C's gc is for ObjC pointers
5162 // (or pointers to them) be treated as though they were declared
5163 // as __strong.
5164 if (GCAttrs == Qualifiers::GCNone) {
5165 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5166 return Qualifiers::Strong;
5167 else if (Ty->isPointerType())
5168 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5169 } else {
5170 // It's not valid to set GC attributes on anything that isn't a
5171 // pointer.
5172#ifndef NDEBUG
5173 QualType CT = Ty->getCanonicalTypeInternal();
5174 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5175 CT = AT->getElementType();
5176 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5177#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005178 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00005179 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005180}
5181
Chris Lattner6ac46a42008-04-07 06:51:04 +00005182//===----------------------------------------------------------------------===//
5183// Type Compatibility Testing
5184//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00005185
Mike Stump1eb44332009-09-09 15:08:12 +00005186/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005187/// compatible.
5188static bool areCompatVectorTypes(const VectorType *LHS,
5189 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00005190 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00005191 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00005192 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00005193}
5194
Douglas Gregor255210e2010-08-06 10:14:59 +00005195bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5196 QualType SecondVec) {
5197 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5198 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5199
5200 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5201 return true;
5202
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005203 // Treat Neon vector types and most AltiVec vector types as if they are the
5204 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00005205 const VectorType *First = FirstVec->getAs<VectorType>();
5206 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005207 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00005208 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005209 First->getVectorKind() != VectorType::AltiVecPixel &&
5210 First->getVectorKind() != VectorType::AltiVecBool &&
5211 Second->getVectorKind() != VectorType::AltiVecPixel &&
5212 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00005213 return true;
5214
5215 return false;
5216}
5217
Steve Naroff4084c302009-07-23 01:01:38 +00005218//===----------------------------------------------------------------------===//
5219// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5220//===----------------------------------------------------------------------===//
5221
5222/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5223/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00005224bool
5225ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5226 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005227 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00005228 return true;
5229 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5230 E = rProto->protocol_end(); PI != E; ++PI)
5231 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5232 return true;
5233 return false;
5234}
5235
Steve Naroff4084c302009-07-23 01:01:38 +00005236/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5237/// return true if lhs's protocols conform to rhs's protocol; false
5238/// otherwise.
5239bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5240 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5241 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5242 return false;
5243}
5244
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005245/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5246/// Class<p1, ...>.
5247bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5248 QualType rhs) {
5249 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5250 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5251 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5252
5253 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5254 E = lhsQID->qual_end(); I != E; ++I) {
5255 bool match = false;
5256 ObjCProtocolDecl *lhsProto = *I;
5257 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5258 E = rhsOPT->qual_end(); J != E; ++J) {
5259 ObjCProtocolDecl *rhsProto = *J;
5260 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5261 match = true;
5262 break;
5263 }
5264 }
5265 if (!match)
5266 return false;
5267 }
5268 return true;
5269}
5270
Steve Naroff4084c302009-07-23 01:01:38 +00005271/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5272/// ObjCQualifiedIDType.
5273bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5274 bool compare) {
5275 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00005276 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005277 lhs->isObjCIdType() || lhs->isObjCClassType())
5278 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005279 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005280 rhs->isObjCIdType() || rhs->isObjCClassType())
5281 return true;
5282
5283 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00005284 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005285
Steve Naroff4084c302009-07-23 01:01:38 +00005286 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005287
Steve Naroff4084c302009-07-23 01:01:38 +00005288 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005289 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00005290 // make sure we check the class hierarchy.
5291 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5292 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5293 E = lhsQID->qual_end(); I != E; ++I) {
5294 // when comparing an id<P> on lhs with a static type on rhs,
5295 // see if static class implements all of id's protocols, directly or
5296 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005297 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00005298 return false;
5299 }
5300 }
5301 // If there are no qualifiers and no interface, we have an 'id'.
5302 return true;
5303 }
Mike Stump1eb44332009-09-09 15:08:12 +00005304 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005305 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5306 E = lhsQID->qual_end(); I != E; ++I) {
5307 ObjCProtocolDecl *lhsProto = *I;
5308 bool match = false;
5309
5310 // when comparing an id<P> on lhs with a static type on rhs,
5311 // see if static class implements all of id's protocols, directly or
5312 // through its super class and categories.
5313 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5314 E = rhsOPT->qual_end(); J != E; ++J) {
5315 ObjCProtocolDecl *rhsProto = *J;
5316 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5317 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5318 match = true;
5319 break;
5320 }
5321 }
Mike Stump1eb44332009-09-09 15:08:12 +00005322 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00005323 // make sure we check the class hierarchy.
5324 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5325 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5326 E = lhsQID->qual_end(); I != E; ++I) {
5327 // when comparing an id<P> on lhs with a static type on rhs,
5328 // see if static class implements all of id's protocols, directly or
5329 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005330 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00005331 match = true;
5332 break;
5333 }
5334 }
5335 }
5336 if (!match)
5337 return false;
5338 }
Mike Stump1eb44332009-09-09 15:08:12 +00005339
Steve Naroff4084c302009-07-23 01:01:38 +00005340 return true;
5341 }
Mike Stump1eb44332009-09-09 15:08:12 +00005342
Steve Naroff4084c302009-07-23 01:01:38 +00005343 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5344 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5345
Mike Stump1eb44332009-09-09 15:08:12 +00005346 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00005347 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005348 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005349 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5350 E = lhsOPT->qual_end(); I != E; ++I) {
5351 ObjCProtocolDecl *lhsProto = *I;
5352 bool match = false;
5353
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005354 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00005355 // see if static class implements all of id's protocols, directly or
5356 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005357 // First, lhs protocols in the qualifier list must be found, direct
5358 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00005359 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5360 E = rhsQID->qual_end(); J != E; ++J) {
5361 ObjCProtocolDecl *rhsProto = *J;
5362 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5363 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5364 match = true;
5365 break;
5366 }
5367 }
5368 if (!match)
5369 return false;
5370 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005371
5372 // Static class's protocols, or its super class or category protocols
5373 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5374 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5375 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5376 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5377 // This is rather dubious but matches gcc's behavior. If lhs has
5378 // no type qualifier and its class has no static protocol(s)
5379 // assume that it is mismatch.
5380 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5381 return false;
5382 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5383 LHSInheritedProtocols.begin(),
5384 E = LHSInheritedProtocols.end(); I != E; ++I) {
5385 bool match = false;
5386 ObjCProtocolDecl *lhsProto = (*I);
5387 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5388 E = rhsQID->qual_end(); J != E; ++J) {
5389 ObjCProtocolDecl *rhsProto = *J;
5390 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5391 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5392 match = true;
5393 break;
5394 }
5395 }
5396 if (!match)
5397 return false;
5398 }
5399 }
Steve Naroff4084c302009-07-23 01:01:38 +00005400 return true;
5401 }
5402 return false;
5403}
5404
Eli Friedman3d815e72008-08-22 00:56:42 +00005405/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005406/// compatible for assignment from RHS to LHS. This handles validation of any
5407/// protocol qualifiers on the LHS or RHS.
5408///
Steve Naroff14108da2009-07-10 23:34:53 +00005409bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5410 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00005411 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5412 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5413
Steve Naroffde2e22d2009-07-15 18:40:39 +00005414 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00005415 if (LHS->isObjCUnqualifiedIdOrClass() ||
5416 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00005417 return true;
5418
John McCallc12c5bb2010-05-15 11:32:37 +00005419 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00005420 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5421 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00005422 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005423
5424 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5425 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5426 QualType(RHSOPT,0));
5427
John McCallc12c5bb2010-05-15 11:32:37 +00005428 // If we have 2 user-defined types, fall into that path.
5429 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00005430 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00005431
Steve Naroff4084c302009-07-23 01:01:38 +00005432 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005433}
5434
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005435/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00005436/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005437/// arguments in block literals. When passed as arguments, passing 'A*' where
5438/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5439/// not OK. For the return type, the opposite is not OK.
5440bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5441 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005442 const ObjCObjectPointerType *RHSOPT,
5443 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005444 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005445 return true;
5446
5447 if (LHSOPT->isObjCBuiltinType()) {
5448 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5449 }
5450
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005451 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005452 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5453 QualType(RHSOPT,0),
5454 false);
5455
5456 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5457 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5458 if (LHS && RHS) { // We have 2 user-defined types.
5459 if (LHS != RHS) {
5460 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005461 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005462 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005463 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005464 }
5465 else
5466 return true;
5467 }
5468 return false;
5469}
5470
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005471/// getIntersectionOfProtocols - This routine finds the intersection of set
5472/// of protocols inherited from two distinct objective-c pointer objects.
5473/// It is used to build composite qualifier list of the composite type of
5474/// the conditional expression involving two objective-c pointer objects.
5475static
5476void getIntersectionOfProtocols(ASTContext &Context,
5477 const ObjCObjectPointerType *LHSOPT,
5478 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005479 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005480
John McCallc12c5bb2010-05-15 11:32:37 +00005481 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5482 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5483 assert(LHS->getInterface() && "LHS must have an interface base");
5484 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005485
5486 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5487 unsigned LHSNumProtocols = LHS->getNumProtocols();
5488 if (LHSNumProtocols > 0)
5489 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5490 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005491 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005492 Context.CollectInheritedProtocols(LHS->getInterface(),
5493 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005494 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5495 LHSInheritedProtocols.end());
5496 }
5497
5498 unsigned RHSNumProtocols = RHS->getNumProtocols();
5499 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00005500 ObjCProtocolDecl **RHSProtocols =
5501 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005502 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5503 if (InheritedProtocolSet.count(RHSProtocols[i]))
5504 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00005505 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005506 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005507 Context.CollectInheritedProtocols(RHS->getInterface(),
5508 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005509 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5510 RHSInheritedProtocols.begin(),
5511 E = RHSInheritedProtocols.end(); I != E; ++I)
5512 if (InheritedProtocolSet.count((*I)))
5513 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005514 }
5515}
5516
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005517/// areCommonBaseCompatible - Returns common base class of the two classes if
5518/// one found. Note that this is O'2 algorithm. But it will be called as the
5519/// last type comparison in a ?-exp of ObjC pointer types before a
5520/// warning is issued. So, its invokation is extremely rare.
5521QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00005522 const ObjCObjectPointerType *Lptr,
5523 const ObjCObjectPointerType *Rptr) {
5524 const ObjCObjectType *LHS = Lptr->getObjectType();
5525 const ObjCObjectType *RHS = Rptr->getObjectType();
5526 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5527 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00005528 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005529 return QualType();
5530
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005531 do {
John McCallc12c5bb2010-05-15 11:32:37 +00005532 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005533 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005534 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005535 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5536
5537 QualType Result = QualType(LHS, 0);
5538 if (!Protocols.empty())
5539 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5540 Result = getObjCObjectPointerType(Result);
5541 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005542 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005543 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005544
5545 return QualType();
5546}
5547
John McCallc12c5bb2010-05-15 11:32:37 +00005548bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5549 const ObjCObjectType *RHS) {
5550 assert(LHS->getInterface() && "LHS is not an interface type");
5551 assert(RHS->getInterface() && "RHS is not an interface type");
5552
Chris Lattner6ac46a42008-04-07 06:51:04 +00005553 // Verify that the base decls are compatible: the RHS must be a subclass of
5554 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00005555 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00005556 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005557
Chris Lattner6ac46a42008-04-07 06:51:04 +00005558 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5559 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00005560 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00005561 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005562
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005563 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5564 // more detailed analysis is required.
5565 if (RHS->getNumProtocols() == 0) {
5566 // OK, if LHS is a superclass of RHS *and*
5567 // this superclass is assignment compatible with LHS.
5568 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005569 bool IsSuperClass =
5570 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5571 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005572 // OK if conversion of LHS to SuperClass results in narrowing of types
5573 // ; i.e., SuperClass may implement at least one of the protocols
5574 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5575 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5576 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005577 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005578 // If super class has no protocols, it is not a match.
5579 if (SuperClassInheritedProtocols.empty())
5580 return false;
5581
5582 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5583 LHSPE = LHS->qual_end();
5584 LHSPI != LHSPE; LHSPI++) {
5585 bool SuperImplementsProtocol = false;
5586 ObjCProtocolDecl *LHSProto = (*LHSPI);
5587
5588 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5589 SuperClassInheritedProtocols.begin(),
5590 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5591 ObjCProtocolDecl *SuperClassProto = (*I);
5592 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5593 SuperImplementsProtocol = true;
5594 break;
5595 }
5596 }
5597 if (!SuperImplementsProtocol)
5598 return false;
5599 }
5600 return true;
5601 }
5602 return false;
5603 }
Mike Stump1eb44332009-09-09 15:08:12 +00005604
John McCallc12c5bb2010-05-15 11:32:37 +00005605 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5606 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005607 LHSPI != LHSPE; LHSPI++) {
5608 bool RHSImplementsProtocol = false;
5609
5610 // If the RHS doesn't implement the protocol on the left, the types
5611 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00005612 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5613 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00005614 RHSPI != RHSPE; RHSPI++) {
5615 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005616 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00005617 break;
5618 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005619 }
5620 // FIXME: For better diagnostics, consider passing back the protocol name.
5621 if (!RHSImplementsProtocol)
5622 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005623 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005624 // The RHS implements all protocols listed on the LHS.
5625 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005626}
5627
Steve Naroff389bf462009-02-12 17:52:19 +00005628bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5629 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00005630 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5631 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005632
Steve Naroff14108da2009-07-10 23:34:53 +00005633 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00005634 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005635
5636 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5637 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00005638}
5639
Douglas Gregor569c3162010-08-07 11:51:51 +00005640bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5641 return canAssignObjCInterfaces(
5642 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5643 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5644}
5645
Mike Stump1eb44332009-09-09 15:08:12 +00005646/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00005647/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00005648/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00005649/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00005650bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5651 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005652 if (getLangOptions().CPlusPlus)
5653 return hasSameType(LHS, RHS);
5654
Douglas Gregor447234d2010-07-29 15:18:02 +00005655 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00005656}
5657
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005658bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00005659 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005660}
5661
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005662bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5663 return !mergeTypes(LHS, RHS, true).isNull();
5664}
5665
Peter Collingbourne48466752010-10-24 18:30:18 +00005666/// mergeTransparentUnionType - if T is a transparent union type and a member
5667/// of T is compatible with SubType, return the merged type, else return
5668/// QualType()
5669QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5670 bool OfBlockPointer,
5671 bool Unqualified) {
5672 if (const RecordType *UT = T->getAsUnionType()) {
5673 RecordDecl *UD = UT->getDecl();
5674 if (UD->hasAttr<TransparentUnionAttr>()) {
5675 for (RecordDecl::field_iterator it = UD->field_begin(),
5676 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00005677 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005678 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5679 if (!MT.isNull())
5680 return MT;
5681 }
5682 }
5683 }
5684
5685 return QualType();
5686}
5687
5688/// mergeFunctionArgumentTypes - merge two types which appear as function
5689/// argument types
5690QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5691 bool OfBlockPointer,
5692 bool Unqualified) {
5693 // GNU extension: two types are compatible if they appear as a function
5694 // argument, one of the types is a transparent union type and the other
5695 // type is compatible with a union member
5696 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5697 Unqualified);
5698 if (!lmerge.isNull())
5699 return lmerge;
5700
5701 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5702 Unqualified);
5703 if (!rmerge.isNull())
5704 return rmerge;
5705
5706 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5707}
5708
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005709QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00005710 bool OfBlockPointer,
5711 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00005712 const FunctionType *lbase = lhs->getAs<FunctionType>();
5713 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00005714 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5715 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00005716 bool allLTypes = true;
5717 bool allRTypes = true;
5718
5719 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005720 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005721 if (OfBlockPointer) {
5722 QualType RHS = rbase->getResultType();
5723 QualType LHS = lbase->getResultType();
5724 bool UnqualifiedResult = Unqualified;
5725 if (!UnqualifiedResult)
5726 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005727 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005728 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005729 else
John McCall8cc246c2010-12-15 01:06:38 +00005730 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5731 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005732 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005733
5734 if (Unqualified)
5735 retType = retType.getUnqualifiedType();
5736
5737 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5738 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5739 if (Unqualified) {
5740 LRetType = LRetType.getUnqualifiedType();
5741 RRetType = RRetType.getUnqualifiedType();
5742 }
5743
5744 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005745 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00005746 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005747 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005748
Daniel Dunbar6a15c852010-04-28 16:20:58 +00005749 // FIXME: double check this
5750 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5751 // rbase->getRegParmAttr() != 0 &&
5752 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00005753 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5754 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00005755
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005756 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00005757 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005758 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005759
John McCall8cc246c2010-12-15 01:06:38 +00005760 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00005761 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5762 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00005763 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5764 return QualType();
5765
John McCallf85e1932011-06-15 23:02:42 +00005766 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5767 return QualType();
5768
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005769 // functypes which return are preferred over those that do not.
5770 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5771 allLTypes = false;
5772 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5773 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005774 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5775 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00005776
John McCallf85e1932011-06-15 23:02:42 +00005777 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00005778
Eli Friedman3d815e72008-08-22 00:56:42 +00005779 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00005780 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5781 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005782 unsigned lproto_nargs = lproto->getNumArgs();
5783 unsigned rproto_nargs = rproto->getNumArgs();
5784
5785 // Compatible functions must have the same number of arguments
5786 if (lproto_nargs != rproto_nargs)
5787 return QualType();
5788
5789 // Variadic and non-variadic functions aren't compatible
5790 if (lproto->isVariadic() != rproto->isVariadic())
5791 return QualType();
5792
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00005793 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5794 return QualType();
5795
Fariborz Jahanian78213e42011-09-28 21:52:05 +00005796 if (LangOpts.ObjCAutoRefCount &&
5797 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5798 return QualType();
5799
Eli Friedman3d815e72008-08-22 00:56:42 +00005800 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00005801 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00005802 for (unsigned i = 0; i < lproto_nargs; i++) {
5803 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5804 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005805 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5806 OfBlockPointer,
5807 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005808 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005809
5810 if (Unqualified)
5811 argtype = argtype.getUnqualifiedType();
5812
Eli Friedman3d815e72008-08-22 00:56:42 +00005813 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00005814 if (Unqualified) {
5815 largtype = largtype.getUnqualifiedType();
5816 rargtype = rargtype.getUnqualifiedType();
5817 }
5818
Chris Lattner61710852008-10-05 17:34:18 +00005819 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5820 allLTypes = false;
5821 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5822 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00005823 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00005824
Eli Friedman3d815e72008-08-22 00:56:42 +00005825 if (allLTypes) return lhs;
5826 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005827
5828 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5829 EPI.ExtInfo = einfo;
5830 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005831 }
5832
5833 if (lproto) allRTypes = false;
5834 if (rproto) allLTypes = false;
5835
Douglas Gregor72564e72009-02-26 23:50:07 +00005836 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00005837 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00005838 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005839 if (proto->isVariadic()) return QualType();
5840 // Check that the types are compatible with the types that
5841 // would result from default argument promotions (C99 6.7.5.3p15).
5842 // The only types actually affected are promotable integer
5843 // types and floats, which would be passed as a different
5844 // type depending on whether the prototype is visible.
5845 unsigned proto_nargs = proto->getNumArgs();
5846 for (unsigned i = 0; i < proto_nargs; ++i) {
5847 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00005848
5849 // Look at the promotion type of enum types, since that is the type used
5850 // to pass enum values.
5851 if (const EnumType *Enum = argTy->getAs<EnumType>())
5852 argTy = Enum->getDecl()->getPromotionType();
5853
Eli Friedman3d815e72008-08-22 00:56:42 +00005854 if (argTy->isPromotableIntegerType() ||
5855 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5856 return QualType();
5857 }
5858
5859 if (allLTypes) return lhs;
5860 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005861
5862 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5863 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00005864 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005865 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005866 }
5867
5868 if (allLTypes) return lhs;
5869 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00005870 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00005871}
5872
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005873QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00005874 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005875 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00005876 // C++ [expr]: If an expression initially has the type "reference to T", the
5877 // type is adjusted to "T" prior to any further analysis, the expression
5878 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005879 // expression is an lvalue unless the reference is an rvalue reference and
5880 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005881 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5882 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00005883
5884 if (Unqualified) {
5885 LHS = LHS.getUnqualifiedType();
5886 RHS = RHS.getUnqualifiedType();
5887 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005888
Eli Friedman3d815e72008-08-22 00:56:42 +00005889 QualType LHSCan = getCanonicalType(LHS),
5890 RHSCan = getCanonicalType(RHS);
5891
5892 // If two types are identical, they are compatible.
5893 if (LHSCan == RHSCan)
5894 return LHS;
5895
John McCall0953e762009-09-24 19:53:00 +00005896 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005897 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5898 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00005899 if (LQuals != RQuals) {
5900 // If any of these qualifiers are different, we have a type
5901 // mismatch.
5902 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00005903 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5904 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00005905 return QualType();
5906
5907 // Exactly one GC qualifier difference is allowed: __strong is
5908 // okay if the other type has no GC qualifier but is an Objective
5909 // C object pointer (i.e. implicitly strong by default). We fix
5910 // this by pretending that the unqualified type was actually
5911 // qualified __strong.
5912 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5913 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5914 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5915
5916 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5917 return QualType();
5918
5919 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5920 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5921 }
5922 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5923 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5924 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005925 return QualType();
John McCall0953e762009-09-24 19:53:00 +00005926 }
5927
5928 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00005929
Eli Friedman852d63b2009-06-01 01:22:52 +00005930 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5931 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00005932
Chris Lattner1adb8832008-01-14 05:45:46 +00005933 // We want to consider the two function types to be the same for these
5934 // comparisons, just force one to the other.
5935 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5936 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00005937
5938 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00005939 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5940 LHSClass = Type::ConstantArray;
5941 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5942 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00005943
John McCallc12c5bb2010-05-15 11:32:37 +00005944 // ObjCInterfaces are just specialized ObjCObjects.
5945 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5946 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5947
Nate Begeman213541a2008-04-18 23:10:10 +00005948 // Canonicalize ExtVector -> Vector.
5949 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5950 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00005951
Chris Lattnera36a61f2008-04-07 05:43:21 +00005952 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005953 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00005954 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00005955 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00005956 // Compatibility is based on the underlying type, not the promotion
5957 // type.
John McCall183700f2009-09-21 23:43:11 +00005958 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00005959 QualType TINT = ETy->getDecl()->getIntegerType();
5960 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005961 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005962 }
John McCall183700f2009-09-21 23:43:11 +00005963 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00005964 QualType TINT = ETy->getDecl()->getIntegerType();
5965 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005966 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005967 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00005968 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00005969 if (OfBlockPointer && !BlockReturnType) {
5970 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
5971 return LHS;
5972 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
5973 return RHS;
5974 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00005975
Eli Friedman3d815e72008-08-22 00:56:42 +00005976 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005977 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005978
Steve Naroff4a746782008-01-09 22:43:08 +00005979 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005980 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00005981#define TYPE(Class, Base)
5982#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00005983#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00005984#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5985#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5986#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00005987 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00005988
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005989 case Type::LValueReference:
5990 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00005991 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00005992 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00005993
John McCallc12c5bb2010-05-15 11:32:37 +00005994 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00005995 case Type::IncompleteArray:
5996 case Type::VariableArray:
5997 case Type::FunctionProto:
5998 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00005999 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00006000
Chris Lattner1adb8832008-01-14 05:45:46 +00006001 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00006002 {
6003 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006004 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6005 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006006 if (Unqualified) {
6007 LHSPointee = LHSPointee.getUnqualifiedType();
6008 RHSPointee = RHSPointee.getUnqualifiedType();
6009 }
6010 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6011 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006012 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00006013 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00006014 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00006015 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00006016 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006017 return getPointerType(ResultType);
6018 }
Steve Naroffc0febd52008-12-10 17:49:55 +00006019 case Type::BlockPointer:
6020 {
6021 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006022 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6023 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006024 if (Unqualified) {
6025 LHSPointee = LHSPointee.getUnqualifiedType();
6026 RHSPointee = RHSPointee.getUnqualifiedType();
6027 }
6028 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6029 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00006030 if (ResultType.isNull()) return QualType();
6031 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6032 return LHS;
6033 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6034 return RHS;
6035 return getBlockPointerType(ResultType);
6036 }
Eli Friedmanb001de72011-10-06 23:00:33 +00006037 case Type::Atomic:
6038 {
6039 // Merge two pointer types, while trying to preserve typedef info
6040 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6041 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6042 if (Unqualified) {
6043 LHSValue = LHSValue.getUnqualifiedType();
6044 RHSValue = RHSValue.getUnqualifiedType();
6045 }
6046 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6047 Unqualified);
6048 if (ResultType.isNull()) return QualType();
6049 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6050 return LHS;
6051 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6052 return RHS;
6053 return getAtomicType(ResultType);
6054 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006055 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00006056 {
6057 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6058 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6059 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6060 return QualType();
6061
6062 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6063 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006064 if (Unqualified) {
6065 LHSElem = LHSElem.getUnqualifiedType();
6066 RHSElem = RHSElem.getUnqualifiedType();
6067 }
6068
6069 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006070 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00006071 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6072 return LHS;
6073 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6074 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00006075 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6076 ArrayType::ArraySizeModifier(), 0);
6077 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6078 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006079 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6080 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00006081 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6082 return LHS;
6083 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6084 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006085 if (LVAT) {
6086 // FIXME: This isn't correct! But tricky to implement because
6087 // the array's size has to be the size of LHS, but the type
6088 // has to be different.
6089 return LHS;
6090 }
6091 if (RVAT) {
6092 // FIXME: This isn't correct! But tricky to implement because
6093 // the array's size has to be the size of RHS, but the type
6094 // has to be different.
6095 return RHS;
6096 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00006097 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6098 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00006099 return getIncompleteArrayType(ResultType,
6100 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006101 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006102 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00006103 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00006104 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00006105 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00006106 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00006107 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006108 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00006109 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00006110 case Type::Complex:
6111 // Distinct complex types are incompatible.
6112 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006113 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006114 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00006115 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6116 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006117 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00006118 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00006119 case Type::ObjCObject: {
6120 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006121 // FIXME: This should be type compatibility, e.g. whether
6122 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00006123 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6124 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6125 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00006126 return LHS;
6127
Eli Friedman3d815e72008-08-22 00:56:42 +00006128 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00006129 }
Steve Naroff14108da2009-07-10 23:34:53 +00006130 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006131 if (OfBlockPointer) {
6132 if (canAssignObjCInterfacesInBlockPointer(
6133 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006134 RHS->getAs<ObjCObjectPointerType>(),
6135 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00006136 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006137 return QualType();
6138 }
John McCall183700f2009-09-21 23:43:11 +00006139 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6140 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00006141 return LHS;
6142
Steve Naroffbc76dd02008-12-10 22:14:21 +00006143 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00006144 }
Steve Naroffec0550f2007-10-15 20:41:53 +00006145 }
Douglas Gregor72564e72009-02-26 23:50:07 +00006146
David Blaikie7530c032012-01-17 06:56:22 +00006147 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00006148}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00006149
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006150bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6151 const FunctionProtoType *FromFunctionType,
6152 const FunctionProtoType *ToFunctionType) {
6153 if (FromFunctionType->hasAnyConsumedArgs() !=
6154 ToFunctionType->hasAnyConsumedArgs())
6155 return false;
6156 FunctionProtoType::ExtProtoInfo FromEPI =
6157 FromFunctionType->getExtProtoInfo();
6158 FunctionProtoType::ExtProtoInfo ToEPI =
6159 ToFunctionType->getExtProtoInfo();
6160 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6161 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6162 ArgIdx != NumArgs; ++ArgIdx) {
6163 if (FromEPI.ConsumedArguments[ArgIdx] !=
6164 ToEPI.ConsumedArguments[ArgIdx])
6165 return false;
6166 }
6167 return true;
6168}
6169
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006170/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6171/// 'RHS' attributes and returns the merged version; including for function
6172/// return types.
6173QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6174 QualType LHSCan = getCanonicalType(LHS),
6175 RHSCan = getCanonicalType(RHS);
6176 // If two types are identical, they are compatible.
6177 if (LHSCan == RHSCan)
6178 return LHS;
6179 if (RHSCan->isFunctionType()) {
6180 if (!LHSCan->isFunctionType())
6181 return QualType();
6182 QualType OldReturnType =
6183 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6184 QualType NewReturnType =
6185 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6186 QualType ResReturnType =
6187 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6188 if (ResReturnType.isNull())
6189 return QualType();
6190 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6191 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6192 // In either case, use OldReturnType to build the new function type.
6193 const FunctionType *F = LHS->getAs<FunctionType>();
6194 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00006195 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6196 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006197 QualType ResultType
6198 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006199 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006200 return ResultType;
6201 }
6202 }
6203 return QualType();
6204 }
6205
6206 // If the qualifiers are different, the types can still be merged.
6207 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6208 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6209 if (LQuals != RQuals) {
6210 // If any of these qualifiers are different, we have a type mismatch.
6211 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6212 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6213 return QualType();
6214
6215 // Exactly one GC qualifier difference is allowed: __strong is
6216 // okay if the other type has no GC qualifier but is an Objective
6217 // C object pointer (i.e. implicitly strong by default). We fix
6218 // this by pretending that the unqualified type was actually
6219 // qualified __strong.
6220 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6221 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6222 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6223
6224 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6225 return QualType();
6226
6227 if (GC_L == Qualifiers::Strong)
6228 return LHS;
6229 if (GC_R == Qualifiers::Strong)
6230 return RHS;
6231 return QualType();
6232 }
6233
6234 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6235 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6236 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6237 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6238 if (ResQT == LHSBaseQT)
6239 return LHS;
6240 if (ResQT == RHSBaseQT)
6241 return RHS;
6242 }
6243 return QualType();
6244}
6245
Chris Lattner5426bf62008-04-07 07:01:58 +00006246//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00006247// Integer Predicates
6248//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00006249
Jay Foad4ba2a172011-01-12 09:06:06 +00006250unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00006251 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00006252 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006253 if (T->isBooleanType())
6254 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00006255 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00006256 return (unsigned)getTypeSize(T);
6257}
6258
6259QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00006260 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00006261
6262 // Turn <4 x signed int> -> <4 x unsigned int>
6263 if (const VectorType *VTy = T->getAs<VectorType>())
6264 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00006265 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00006266
6267 // For enums, we return the unsigned version of the base type.
6268 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00006269 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00006270
6271 const BuiltinType *BTy = T->getAs<BuiltinType>();
6272 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006273 switch (BTy->getKind()) {
6274 case BuiltinType::Char_S:
6275 case BuiltinType::SChar:
6276 return UnsignedCharTy;
6277 case BuiltinType::Short:
6278 return UnsignedShortTy;
6279 case BuiltinType::Int:
6280 return UnsignedIntTy;
6281 case BuiltinType::Long:
6282 return UnsignedLongTy;
6283 case BuiltinType::LongLong:
6284 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00006285 case BuiltinType::Int128:
6286 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00006287 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00006288 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006289 }
6290}
6291
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00006292ASTMutationListener::~ASTMutationListener() { }
6293
Chris Lattner86df27b2009-06-14 00:45:47 +00006294
6295//===----------------------------------------------------------------------===//
6296// Builtin Type Computation
6297//===----------------------------------------------------------------------===//
6298
6299/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00006300/// pointer over the consumed characters. This returns the resultant type. If
6301/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6302/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6303/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00006304///
6305/// RequiresICE is filled in on return to indicate whether the value is required
6306/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00006307static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00006308 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00006309 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00006310 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00006311 // Modifiers.
6312 int HowLong = 0;
6313 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00006314 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006315
Chris Lattner33daae62010-10-01 22:42:38 +00006316 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00006317 bool Done = false;
6318 while (!Done) {
6319 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00006320 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006321 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00006322 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006323 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006324 case 'S':
6325 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6326 assert(!Signed && "Can't use 'S' modifier multiple times!");
6327 Signed = true;
6328 break;
6329 case 'U':
6330 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6331 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6332 Unsigned = true;
6333 break;
6334 case 'L':
6335 assert(HowLong <= 2 && "Can't have LLLL modifier");
6336 ++HowLong;
6337 break;
6338 }
6339 }
6340
6341 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00006342
Chris Lattner86df27b2009-06-14 00:45:47 +00006343 // Read the base type.
6344 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00006345 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00006346 case 'v':
6347 assert(HowLong == 0 && !Signed && !Unsigned &&
6348 "Bad modifiers used with 'v'!");
6349 Type = Context.VoidTy;
6350 break;
6351 case 'f':
6352 assert(HowLong == 0 && !Signed && !Unsigned &&
6353 "Bad modifiers used with 'f'!");
6354 Type = Context.FloatTy;
6355 break;
6356 case 'd':
6357 assert(HowLong < 2 && !Signed && !Unsigned &&
6358 "Bad modifiers used with 'd'!");
6359 if (HowLong)
6360 Type = Context.LongDoubleTy;
6361 else
6362 Type = Context.DoubleTy;
6363 break;
6364 case 's':
6365 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6366 if (Unsigned)
6367 Type = Context.UnsignedShortTy;
6368 else
6369 Type = Context.ShortTy;
6370 break;
6371 case 'i':
6372 if (HowLong == 3)
6373 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6374 else if (HowLong == 2)
6375 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6376 else if (HowLong == 1)
6377 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6378 else
6379 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6380 break;
6381 case 'c':
6382 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6383 if (Signed)
6384 Type = Context.SignedCharTy;
6385 else if (Unsigned)
6386 Type = Context.UnsignedCharTy;
6387 else
6388 Type = Context.CharTy;
6389 break;
6390 case 'b': // boolean
6391 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6392 Type = Context.BoolTy;
6393 break;
6394 case 'z': // size_t.
6395 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6396 Type = Context.getSizeType();
6397 break;
6398 case 'F':
6399 Type = Context.getCFConstantStringType();
6400 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00006401 case 'G':
6402 Type = Context.getObjCIdType();
6403 break;
6404 case 'H':
6405 Type = Context.getObjCSelType();
6406 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006407 case 'a':
6408 Type = Context.getBuiltinVaListType();
6409 assert(!Type.isNull() && "builtin va list type not initialized!");
6410 break;
6411 case 'A':
6412 // This is a "reference" to a va_list; however, what exactly
6413 // this means depends on how va_list is defined. There are two
6414 // different kinds of va_list: ones passed by value, and ones
6415 // passed by reference. An example of a by-value va_list is
6416 // x86, where va_list is a char*. An example of by-ref va_list
6417 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6418 // we want this argument to be a char*&; for x86-64, we want
6419 // it to be a __va_list_tag*.
6420 Type = Context.getBuiltinVaListType();
6421 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00006422 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00006423 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00006424 else
Chris Lattner86df27b2009-06-14 00:45:47 +00006425 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00006426 break;
6427 case 'V': {
6428 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00006429 unsigned NumElements = strtoul(Str, &End, 10);
6430 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00006431 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00006432
Chris Lattner14e0e742010-10-01 22:53:11 +00006433 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6434 RequiresICE, false);
6435 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00006436
6437 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00006438 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00006439 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00006440 break;
6441 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00006442 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00006443 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6444 false);
6445 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00006446 Type = Context.getComplexType(ElementType);
6447 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00006448 }
6449 case 'Y' : {
6450 Type = Context.getPointerDiffType();
6451 break;
6452 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006453 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00006454 Type = Context.getFILEType();
6455 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006456 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00006457 return QualType();
6458 }
Mike Stumpfd612db2009-07-28 23:47:15 +00006459 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006460 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00006461 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00006462 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00006463 else
6464 Type = Context.getjmp_bufType();
6465
Mike Stumpfd612db2009-07-28 23:47:15 +00006466 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006467 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00006468 return QualType();
6469 }
6470 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00006471 case 'K':
6472 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6473 Type = Context.getucontext_tType();
6474
6475 if (Type.isNull()) {
6476 Error = ASTContext::GE_Missing_ucontext;
6477 return QualType();
6478 }
6479 break;
Mike Stump782fa302009-07-28 02:25:19 +00006480 }
Mike Stump1eb44332009-09-09 15:08:12 +00006481
Chris Lattner33daae62010-10-01 22:42:38 +00006482 // If there are modifiers and if we're allowed to parse them, go for it.
6483 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00006484 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00006485 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00006486 default: Done = true; --Str; break;
6487 case '*':
6488 case '&': {
6489 // Both pointers and references can have their pointee types
6490 // qualified with an address space.
6491 char *End;
6492 unsigned AddrSpace = strtoul(Str, &End, 10);
6493 if (End != Str && AddrSpace != 0) {
6494 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6495 Str = End;
6496 }
6497 if (c == '*')
6498 Type = Context.getPointerType(Type);
6499 else
6500 Type = Context.getLValueReferenceType(Type);
6501 break;
6502 }
6503 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6504 case 'C':
6505 Type = Type.withConst();
6506 break;
6507 case 'D':
6508 Type = Context.getVolatileType(Type);
6509 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00006510 case 'R':
6511 Type = Type.withRestrict();
6512 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006513 }
6514 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00006515
Chris Lattner14e0e742010-10-01 22:53:11 +00006516 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00006517 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00006518
Chris Lattner86df27b2009-06-14 00:45:47 +00006519 return Type;
6520}
6521
6522/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00006523QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00006524 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00006525 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00006526 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00006527
Chris Lattner5f9e2722011-07-23 10:55:15 +00006528 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00006529
Chris Lattner14e0e742010-10-01 22:53:11 +00006530 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00006531 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00006532 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6533 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006534 if (Error != GE_None)
6535 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00006536
6537 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6538
Chris Lattner86df27b2009-06-14 00:45:47 +00006539 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00006540 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006541 if (Error != GE_None)
6542 return QualType();
6543
Chris Lattner14e0e742010-10-01 22:53:11 +00006544 // If this argument is required to be an IntegerConstantExpression and the
6545 // caller cares, fill in the bitmask we return.
6546 if (RequiresICE && IntegerConstantArgs)
6547 *IntegerConstantArgs |= 1 << ArgTypes.size();
6548
Chris Lattner86df27b2009-06-14 00:45:47 +00006549 // Do array -> pointer decay. The builtin should use the decayed type.
6550 if (Ty->isArrayType())
6551 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00006552
Chris Lattner86df27b2009-06-14 00:45:47 +00006553 ArgTypes.push_back(Ty);
6554 }
6555
6556 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6557 "'.' should only occur at end of builtin type list!");
6558
John McCall00ccbef2010-12-21 00:44:39 +00006559 FunctionType::ExtInfo EI;
6560 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6561
6562 bool Variadic = (TypeStr[0] == '.');
6563
6564 // We really shouldn't be making a no-proto type here, especially in C++.
6565 if (ArgTypes.empty() && Variadic)
6566 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00006567
John McCalle23cf432010-12-14 08:05:40 +00006568 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00006569 EPI.ExtInfo = EI;
6570 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00006571
6572 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00006573}
Eli Friedmana95d7572009-08-19 07:44:53 +00006574
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006575GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6576 GVALinkage External = GVA_StrongExternal;
6577
6578 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006579 switch (L) {
6580 case NoLinkage:
6581 case InternalLinkage:
6582 case UniqueExternalLinkage:
6583 return GVA_Internal;
6584
6585 case ExternalLinkage:
6586 switch (FD->getTemplateSpecializationKind()) {
6587 case TSK_Undeclared:
6588 case TSK_ExplicitSpecialization:
6589 External = GVA_StrongExternal;
6590 break;
6591
6592 case TSK_ExplicitInstantiationDefinition:
6593 return GVA_ExplicitTemplateInstantiation;
6594
6595 case TSK_ExplicitInstantiationDeclaration:
6596 case TSK_ImplicitInstantiation:
6597 External = GVA_TemplateInstantiation;
6598 break;
6599 }
6600 }
6601
6602 if (!FD->isInlined())
6603 return External;
6604
6605 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6606 // GNU or C99 inline semantics. Determine whether this symbol should be
6607 // externally visible.
6608 if (FD->isInlineDefinitionExternallyVisible())
6609 return External;
6610
6611 // C99 inline semantics, where the symbol is not externally visible.
6612 return GVA_C99Inline;
6613 }
6614
6615 // C++0x [temp.explicit]p9:
6616 // [ Note: The intent is that an inline function that is the subject of
6617 // an explicit instantiation declaration will still be implicitly
6618 // instantiated when used so that the body can be considered for
6619 // inlining, but that no out-of-line copy of the inline function would be
6620 // generated in the translation unit. -- end note ]
6621 if (FD->getTemplateSpecializationKind()
6622 == TSK_ExplicitInstantiationDeclaration)
6623 return GVA_C99Inline;
6624
6625 return GVA_CXXInline;
6626}
6627
6628GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6629 // If this is a static data member, compute the kind of template
6630 // specialization. Otherwise, this variable is not part of a
6631 // template.
6632 TemplateSpecializationKind TSK = TSK_Undeclared;
6633 if (VD->isStaticDataMember())
6634 TSK = VD->getTemplateSpecializationKind();
6635
6636 Linkage L = VD->getLinkage();
6637 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6638 VD->getType()->getLinkage() == UniqueExternalLinkage)
6639 L = UniqueExternalLinkage;
6640
6641 switch (L) {
6642 case NoLinkage:
6643 case InternalLinkage:
6644 case UniqueExternalLinkage:
6645 return GVA_Internal;
6646
6647 case ExternalLinkage:
6648 switch (TSK) {
6649 case TSK_Undeclared:
6650 case TSK_ExplicitSpecialization:
6651 return GVA_StrongExternal;
6652
6653 case TSK_ExplicitInstantiationDeclaration:
6654 llvm_unreachable("Variable should not be instantiated");
6655 // Fall through to treat this like any other instantiation.
6656
6657 case TSK_ExplicitInstantiationDefinition:
6658 return GVA_ExplicitTemplateInstantiation;
6659
6660 case TSK_ImplicitInstantiation:
6661 return GVA_TemplateInstantiation;
6662 }
6663 }
6664
David Blaikie7530c032012-01-17 06:56:22 +00006665 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006666}
6667
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00006668bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006669 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6670 if (!VD->isFileVarDecl())
6671 return false;
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00006672 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006673 return false;
6674
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006675 // Weak references don't produce any output by themselves.
6676 if (D->hasAttr<WeakRefAttr>())
6677 return false;
6678
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006679 // Aliases and used decls are required.
6680 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6681 return true;
6682
6683 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6684 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00006685 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00006686 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006687
6688 // Constructors and destructors are required.
6689 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6690 return true;
6691
6692 // The key function for a class is required.
6693 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6694 const CXXRecordDecl *RD = MD->getParent();
6695 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6696 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6697 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6698 return true;
6699 }
6700 }
6701
6702 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6703
6704 // static, static inline, always_inline, and extern inline functions can
6705 // always be deferred. Normal inline functions can be deferred in C99/C++.
6706 // Implicit template instantiations can also be deferred in C++.
6707 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00006708 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006709 return false;
6710 return true;
6711 }
Douglas Gregor94da1582011-09-10 00:22:34 +00006712
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006713 const VarDecl *VD = cast<VarDecl>(D);
6714 assert(VD->isFileVarDecl() && "Expected file scoped var");
6715
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006716 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6717 return false;
6718
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006719 // Structs that have non-trivial constructors or destructors are required.
6720
6721 // FIXME: Handle references.
Sean Hunt023df372011-05-09 18:22:59 +00006722 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006723 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6724 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Sean Hunt023df372011-05-09 18:22:59 +00006725 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6726 RD->hasTrivialCopyConstructor() &&
6727 RD->hasTrivialMoveConstructor() &&
6728 RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006729 return true;
6730 }
6731 }
6732
6733 GVALinkage L = GetGVALinkageForVariable(VD);
6734 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6735 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6736 return false;
6737 }
6738
6739 return true;
6740}
Charles Davis071cc7d2010-08-16 03:33:14 +00006741
Charles Davisee743f92010-11-09 18:04:24 +00006742CallingConv ASTContext::getDefaultMethodCallConv() {
6743 // Pass through to the C++ ABI object
6744 return ABI->getDefaultMethodCallConv();
6745}
6746
Jay Foad4ba2a172011-01-12 09:06:06 +00006747bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00006748 // Pass through to the C++ ABI object
6749 return ABI->isNearlyEmpty(RD);
6750}
6751
Peter Collingbourne14110472011-01-13 18:57:25 +00006752MangleContext *ASTContext::createMangleContext() {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00006753 switch (Target->getCXXABI()) {
Peter Collingbourne14110472011-01-13 18:57:25 +00006754 case CXXABI_ARM:
6755 case CXXABI_Itanium:
6756 return createItaniumMangleContext(*this, getDiagnostics());
6757 case CXXABI_Microsoft:
6758 return createMicrosoftMangleContext(*this, getDiagnostics());
6759 }
David Blaikieb219cfc2011-09-23 05:06:16 +00006760 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00006761}
6762
Charles Davis071cc7d2010-08-16 03:33:14 +00006763CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00006764
6765size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00006766 return ASTRecordLayouts.getMemorySize()
6767 + llvm::capacity_in_bytes(ObjCLayouts)
6768 + llvm::capacity_in_bytes(KeyFunctions)
6769 + llvm::capacity_in_bytes(ObjCImpls)
6770 + llvm::capacity_in_bytes(BlockVarCopyInits)
6771 + llvm::capacity_in_bytes(DeclAttrs)
6772 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6773 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6774 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6775 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6776 + llvm::capacity_in_bytes(OverriddenMethods)
6777 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00006778 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00006779 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00006780}
Ted Kremenekd211cb72011-10-06 05:00:56 +00006781
6782void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6783 ParamIndices[D] = index;
6784}
6785
6786unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6787 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6788 assert(I != ParamIndices.end() &&
6789 "ParmIndices lacks entry set by ParmVarDecl");
6790 return I->second;
6791}