blob: 514a013e93810b7e2a0e1f4fc6dd705c29e2e65b [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCallea1471e2010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +000033#include "llvm/Support/Capacity.h"
Charles Davis071cc7d2010-08-16 03:33:14 +000034#include "CXXABI.h"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000035#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000036
Reid Spencer5f016e22007-07-11 17:01:13 +000037using namespace clang;
38
Douglas Gregor18274032010-07-03 00:47:00 +000039unsigned ASTContext::NumImplicitDefaultConstructors;
40unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000041unsigned ASTContext::NumImplicitCopyConstructors;
42unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000043unsigned ASTContext::NumImplicitMoveConstructors;
44unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000045unsigned ASTContext::NumImplicitCopyAssignmentOperators;
46unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000047unsigned ASTContext::NumImplicitMoveAssignmentOperators;
48unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000049unsigned ASTContext::NumImplicitDestructors;
50unsigned ASTContext::NumImplicitDestructorsDeclared;
51
Reid Spencer5f016e22007-07-11 17:01:13 +000052enum FloatingRank {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +000053 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Reid Spencer5f016e22007-07-11 17:01:13 +000054};
55
Douglas Gregor3e1274f2010-06-16 21:09:37 +000056void
57ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
58 TemplateTemplateParmDecl *Parm) {
59 ID.AddInteger(Parm->getDepth());
60 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +000061 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000062
63 TemplateParameterList *Params = Parm->getTemplateParameters();
64 ID.AddInteger(Params->size());
65 for (TemplateParameterList::const_iterator P = Params->begin(),
66 PEnd = Params->end();
67 P != PEnd; ++P) {
68 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
69 ID.AddInteger(0);
70 ID.AddBoolean(TTP->isParameterPack());
71 continue;
72 }
73
74 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
75 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +000076 ID.AddBoolean(NTTP->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000077 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +000078 if (NTTP->isExpandedParameterPack()) {
79 ID.AddBoolean(true);
80 ID.AddInteger(NTTP->getNumExpansionTypes());
81 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
82 ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
83 } else
84 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +000085 continue;
86 }
87
88 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
89 ID.AddInteger(2);
90 Profile(ID, TTP);
91 }
92}
93
94TemplateTemplateParmDecl *
95ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +000096 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +000097 // Check if we already have a canonical template template parameter.
98 llvm::FoldingSetNodeID ID;
99 CanonicalTemplateTemplateParm::Profile(ID, TTP);
100 void *InsertPos = 0;
101 CanonicalTemplateTemplateParm *Canonical
102 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
103 if (Canonical)
104 return Canonical->getParam();
105
106 // Build a canonical template parameter list.
107 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000108 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000109 CanonParams.reserve(Params->size());
110 for (TemplateParameterList::const_iterator P = Params->begin(),
111 PEnd = Params->end();
112 P != PEnd; ++P) {
113 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
114 CanonParams.push_back(
115 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000116 SourceLocation(),
117 SourceLocation(),
118 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000119 TTP->getIndex(), 0, false,
120 TTP->isParameterPack()));
121 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000122 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
123 QualType T = getCanonicalType(NTTP->getType());
124 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
125 NonTypeTemplateParmDecl *Param;
126 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000127 SmallVector<QualType, 2> ExpandedTypes;
128 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000129 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
130 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
131 ExpandedTInfos.push_back(
132 getTrivialTypeSourceInfo(ExpandedTypes.back()));
133 }
134
135 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000136 SourceLocation(),
137 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000138 NTTP->getDepth(),
139 NTTP->getPosition(), 0,
140 T,
141 TInfo,
142 ExpandedTypes.data(),
143 ExpandedTypes.size(),
144 ExpandedTInfos.data());
145 } else {
146 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000147 SourceLocation(),
148 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000149 NTTP->getDepth(),
150 NTTP->getPosition(), 0,
151 T,
152 NTTP->isParameterPack(),
153 TInfo);
154 }
155 CanonParams.push_back(Param);
156
157 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000158 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
159 cast<TemplateTemplateParmDecl>(*P)));
160 }
161
162 TemplateTemplateParmDecl *CanonTTP
163 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
164 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000165 TTP->getPosition(),
166 TTP->isParameterPack(),
167 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000168 TemplateParameterList::Create(*this, SourceLocation(),
169 SourceLocation(),
170 CanonParams.data(),
171 CanonParams.size(),
172 SourceLocation()));
173
174 // Get the new insert position for the node we care about.
175 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
176 assert(Canonical == 0 && "Shouldn't be in the map!");
177 (void)Canonical;
178
179 // Create the canonical template template parameter entry.
180 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
181 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
182 return CanonTTP;
183}
184
Charles Davis071cc7d2010-08-16 03:33:14 +0000185CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000186 if (!LangOpts.CPlusPlus) return 0;
187
Charles Davis20cf7172010-08-19 02:18:14 +0000188 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000189 case CXXABI_ARM:
190 return CreateARMCXXABI(*this);
191 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000192 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000193 case CXXABI_Microsoft:
194 return CreateMicrosoftCXXABI(*this);
195 }
John McCallee79a4c2010-08-21 22:46:04 +0000196 return 0;
Charles Davis071cc7d2010-08-16 03:33:14 +0000197}
198
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000199static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000200 const LangOptions &LOpts) {
201 if (LOpts.FakeAddressSpaceMap) {
202 // The fake address space map must have a distinct entry for each
203 // language-specific address space.
204 static const unsigned FakeAddrSpaceMap[] = {
205 1, // opencl_global
206 2, // opencl_local
207 3 // opencl_constant
208 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000209 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000210 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000211 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000212 }
213}
214
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000215ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000216 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000217 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000218 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000219 unsigned size_reserve,
220 bool DelayInitialization)
221 : FunctionProtoTypes(this_()),
222 TemplateSpecializationTypes(this_()),
223 DependentTemplateSpecializationTypes(this_()),
224 SubstTemplateTemplateParmPacks(this_()),
225 GlobalNestedNameSpecifier(0),
226 Int128Decl(0), UInt128Decl(0),
227 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000228 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000229 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000230 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
231 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
232 cudaConfigureCallDecl(0),
Douglas 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
Douglas Gregor2cf26342009-04-09 22:27:44 +0000295ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
296 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 break;
837
Chris Lattner692233e2007-07-13 22:27:08 +0000838 case Type::FunctionNoProto:
839 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000840 // GCC extension: alignof(function) = 32 bits
841 Width = 0;
842 Align = 32;
843 break;
844
Douglas Gregor72564e72009-02-26 23:50:07 +0000845 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000846 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000847 Width = 0;
848 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
849 break;
850
Steve Narofffb22d962007-08-30 01:06:46 +0000851 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000852 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000853
Chris Lattner98be4942008-03-05 18:54:05 +0000854 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +0000855 uint64_t Size = CAT->getSize().getZExtValue();
856 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) && "Overflow in array type bit size evaluation");
857 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +0000858 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +0000859 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000860 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000861 }
Nate Begeman213541a2008-04-18 23:10:10 +0000862 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000863 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000864 const VectorType *VT = cast<VectorType>(T);
865 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
866 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000867 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000868 // If the alignment is not a power of 2, round up to the next power of 2.
869 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000870 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000871 Align = llvm::NextPowerOf2(Align);
872 Width = llvm::RoundUpToAlignment(Width, Align);
873 }
Chris Lattner030d8842007-07-19 22:06:24 +0000874 break;
875 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000876
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000877 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000878 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000879 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000880 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000881 // GCC extension: alignof(void) = 8 bits.
882 Width = 0;
883 Align = 8;
884 break;
885
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000886 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000887 Width = Target->getBoolWidth();
888 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000889 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000890 case BuiltinType::Char_S:
891 case BuiltinType::Char_U:
892 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000893 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000894 Width = Target->getCharWidth();
895 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000896 break;
Chris Lattner3f59c972010-12-25 23:25:43 +0000897 case BuiltinType::WChar_S:
898 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000899 Width = Target->getWCharWidth();
900 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000901 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000902 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000903 Width = Target->getChar16Width();
904 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000905 break;
906 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000907 Width = Target->getChar32Width();
908 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000909 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000910 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000911 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000912 Width = Target->getShortWidth();
913 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000914 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000915 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000916 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000917 Width = Target->getIntWidth();
918 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000919 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000920 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000921 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000922 Width = Target->getLongWidth();
923 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000924 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000925 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000926 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000927 Width = Target->getLongLongWidth();
928 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000929 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000930 case BuiltinType::Int128:
931 case BuiltinType::UInt128:
932 Width = 128;
933 Align = 128; // int128_t is 128-bit aligned on all targets.
934 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000935 case BuiltinType::Half:
936 Width = Target->getHalfWidth();
937 Align = Target->getHalfAlign();
938 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000939 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000940 Width = Target->getFloatWidth();
941 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000942 break;
943 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000944 Width = Target->getDoubleWidth();
945 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000946 break;
947 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000948 Width = Target->getLongDoubleWidth();
949 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000950 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000951 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000952 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
953 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000954 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000955 case BuiltinType::ObjCId:
956 case BuiltinType::ObjCClass:
957 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000958 Width = Target->getPointerWidth(0);
959 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000960 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000961 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000962 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000963 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000964 Width = Target->getPointerWidth(0);
965 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000966 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000967 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000968 unsigned AS = getTargetAddressSpace(
969 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000970 Width = Target->getPointerWidth(AS);
971 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +0000972 break;
973 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000974 case Type::LValueReference:
975 case Type::RValueReference: {
976 // alignof and sizeof should never enter this code path here, so we go
977 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000978 unsigned AS = getTargetAddressSpace(
979 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000980 Width = Target->getPointerWidth(AS);
981 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +0000982 break;
983 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000984 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000985 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000986 Width = Target->getPointerWidth(AS);
987 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000988 break;
989 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000990 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +0000991 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000992 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000993 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +0000994 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000995 Align = PtrDiffInfo.second;
996 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000997 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000998 case Type::Complex: {
999 // Complex types have the same alignment as their elements, but twice the
1000 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001001 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001002 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001003 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001004 Align = EltInfo.second;
1005 break;
1006 }
John McCallc12c5bb2010-05-15 11:32:37 +00001007 case Type::ObjCObject:
1008 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001009 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001010 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001011 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001012 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001013 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001014 break;
1015 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001016 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001017 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001018 const TagType *TT = cast<TagType>(T);
1019
1020 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001021 Width = 8;
1022 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001023 break;
1024 }
Mike Stump1eb44332009-09-09 15:08:12 +00001025
Daniel Dunbar1d751182008-11-08 05:48:37 +00001026 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001027 return getTypeInfo(ET->getDecl()->getIntegerType());
1028
Daniel Dunbar1d751182008-11-08 05:48:37 +00001029 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001030 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001031 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001032 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001033 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001034 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001035
Chris Lattner9fcfe922009-10-22 05:17:15 +00001036 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001037 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1038 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001039
Richard Smith34b41d92011-02-20 03:19:35 +00001040 case Type::Auto: {
1041 const AutoType *A = cast<AutoType>(T);
1042 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001043 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001044 }
1045
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001046 case Type::Paren:
1047 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1048
Douglas Gregor18857642009-04-30 17:32:17 +00001049 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001050 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001051 std::pair<uint64_t, unsigned> Info
1052 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001053 // If the typedef has an aligned attribute on it, it overrides any computed
1054 // alignment we have. This violates the GCC documentation (which says that
1055 // attribute(aligned) can only round up) but matches its implementation.
1056 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1057 Align = AttrAlign;
1058 else
1059 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001060 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001061 break;
Chris Lattner71763312008-04-06 22:05:18 +00001062 }
Douglas Gregor18857642009-04-30 17:32:17 +00001063
1064 case Type::TypeOfExpr:
1065 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1066 .getTypePtr());
1067
1068 case Type::TypeOf:
1069 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1070
Anders Carlsson395b4752009-06-24 19:06:50 +00001071 case Type::Decltype:
1072 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1073 .getTypePtr());
1074
Sean Huntca63c202011-05-24 22:41:36 +00001075 case Type::UnaryTransform:
1076 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1077
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001078 case Type::Elaborated:
1079 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001080
John McCall9d156a72011-01-06 01:58:22 +00001081 case Type::Attributed:
1082 return getTypeInfo(
1083 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1084
Richard Smith3e4c6c42011-05-05 21:57:07 +00001085 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001086 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001087 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001088 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1089 // A type alias template specialization may refer to a typedef with the
1090 // aligned attribute on it.
1091 if (TST->isTypeAlias())
1092 return getTypeInfo(TST->getAliasedType().getTypePtr());
1093 else
1094 return getTypeInfo(getCanonicalType(T));
1095 }
1096
Eli Friedmanb001de72011-10-06 23:00:33 +00001097 case Type::Atomic: {
Eli Friedman2be46072011-10-14 20:59:01 +00001098 std::pair<uint64_t, unsigned> Info
1099 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1100 Width = Info.first;
1101 Align = Info.second;
1102 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1103 llvm::isPowerOf2_64(Width)) {
1104 // We can potentially perform lock-free atomic operations for this
1105 // type; promote the alignment appropriately.
1106 // FIXME: We could potentially promote the width here as well...
1107 // is that worthwhile? (Non-struct atomic types generally have
1108 // power-of-two size anyway, but structs might not. Requires a bit
1109 // of implementation work to make sure we zero out the extra bits.)
1110 Align = static_cast<unsigned>(Width);
1111 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001112 }
1113
Douglas Gregor18857642009-04-30 17:32:17 +00001114 }
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Eli Friedman2be46072011-10-14 20:59:01 +00001116 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001117 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001118}
1119
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001120/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1121CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1122 return CharUnits::fromQuantity(BitSize / getCharWidth());
1123}
1124
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001125/// toBits - Convert a size in characters to a size in characters.
1126int64_t ASTContext::toBits(CharUnits CharSize) const {
1127 return CharSize.getQuantity() * getCharWidth();
1128}
1129
Ken Dyckbdc601b2009-12-22 14:23:30 +00001130/// getTypeSizeInChars - Return the size of the specified type, in characters.
1131/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001132CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001133 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001134}
Jay Foad4ba2a172011-01-12 09:06:06 +00001135CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001136 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001137}
1138
Ken Dyck16e20cc2010-01-26 17:25:18 +00001139/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001140/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001141CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001142 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001143}
Jay Foad4ba2a172011-01-12 09:06:06 +00001144CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001145 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001146}
1147
Chris Lattner34ebde42009-01-27 18:08:34 +00001148/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1149/// type for the current target in bits. This can be different than the ABI
1150/// alignment in cases where it is beneficial for performance to overalign
1151/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001152unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001153 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001154
1155 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001156 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001157 T = CT->getElementType().getTypePtr();
1158 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1159 T->isSpecificBuiltinType(BuiltinType::LongLong))
1160 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1161
Chris Lattner34ebde42009-01-27 18:08:34 +00001162 return ABIAlign;
1163}
1164
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001165/// DeepCollectObjCIvars -
1166/// This routine first collects all declared, but not synthesized, ivars in
1167/// super class and then collects all ivars, including those synthesized for
1168/// current class. This routine is used for implementation of current class
1169/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001170///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001171void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1172 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001173 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001174 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1175 DeepCollectObjCIvars(SuperClass, false, Ivars);
1176 if (!leafClass) {
1177 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1178 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanian11062e12010-02-19 00:31:17 +00001179 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001180 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001181 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001182 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001183 Iv= Iv->getNextIvar())
1184 Ivars.push_back(Iv);
1185 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001186}
1187
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001188/// CollectInheritedProtocols - Collect all protocols in current class and
1189/// those inherited by it.
1190void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001191 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001192 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001193 // We can use protocol_iterator here instead of
1194 // all_referenced_protocol_iterator since we are walking all categories.
1195 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1196 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001197 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001198 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001199 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001200 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001201 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001202 CollectInheritedProtocols(*P, Protocols);
1203 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001204 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001205
1206 // Categories of this Interface.
1207 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1208 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1209 CollectInheritedProtocols(CDeclChain, Protocols);
1210 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1211 while (SD) {
1212 CollectInheritedProtocols(SD, Protocols);
1213 SD = SD->getSuperClass();
1214 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001215 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001216 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001217 PE = OC->protocol_end(); P != PE; ++P) {
1218 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001219 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001220 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1221 PE = Proto->protocol_end(); P != PE; ++P)
1222 CollectInheritedProtocols(*P, Protocols);
1223 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001224 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001225 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1226 PE = OP->protocol_end(); P != PE; ++P) {
1227 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001228 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001229 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1230 PE = Proto->protocol_end(); P != PE; ++P)
1231 CollectInheritedProtocols(*P, Protocols);
1232 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001233 }
1234}
1235
Jay Foad4ba2a172011-01-12 09:06:06 +00001236unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001237 unsigned count = 0;
1238 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001239 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1240 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001241 count += CDecl->ivar_size();
1242
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001243 // Count ivar defined in this class's implementation. This
1244 // includes synthesized ivars.
1245 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001246 count += ImplDecl->ivar_size();
1247
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001248 return count;
1249}
1250
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001251/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1252ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1253 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1254 I = ObjCImpls.find(D);
1255 if (I != ObjCImpls.end())
1256 return cast<ObjCImplementationDecl>(I->second);
1257 return 0;
1258}
1259/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1260ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1261 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1262 I = ObjCImpls.find(D);
1263 if (I != ObjCImpls.end())
1264 return cast<ObjCCategoryImplDecl>(I->second);
1265 return 0;
1266}
1267
1268/// \brief Set the implementation of ObjCInterfaceDecl.
1269void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1270 ObjCImplementationDecl *ImplD) {
1271 assert(IFaceD && ImplD && "Passed null params");
1272 ObjCImpls[IFaceD] = ImplD;
1273}
1274/// \brief Set the implementation of ObjCCategoryDecl.
1275void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1276 ObjCCategoryImplDecl *ImplD) {
1277 assert(CatD && ImplD && "Passed null params");
1278 ObjCImpls[CatD] = ImplD;
1279}
1280
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001281ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1282 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1283 return ID;
1284 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1285 return CD->getClassInterface();
1286 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1287 return IMD->getClassInterface();
1288
1289 return 0;
1290}
1291
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001292/// \brief Get the copy initialization expression of VarDecl,or NULL if
1293/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001294Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001295 assert(VD && "Passed null params");
1296 assert(VD->hasAttr<BlocksAttr>() &&
1297 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001298 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001299 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001300 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1301}
1302
1303/// \brief Set the copy inialization expression of a block var decl.
1304void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1305 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001306 assert(VD->hasAttr<BlocksAttr>() &&
1307 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001308 BlockVarCopyInits[VD] = Init;
1309}
1310
John McCalla93c9342009-12-07 02:54:59 +00001311/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001312///
John McCalla93c9342009-12-07 02:54:59 +00001313/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001314/// the TypeLoc wrappers.
1315///
1316/// \param T the type that will be the basis for type source info. This type
1317/// should refer to how the declarator was written in source code, not to
1318/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001319TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001320 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001321 if (!DataSize)
1322 DataSize = TypeLoc::getFullDataSizeForType(T);
1323 else
1324 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001325 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001326
John McCalla93c9342009-12-07 02:54:59 +00001327 TypeSourceInfo *TInfo =
1328 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1329 new (TInfo) TypeSourceInfo(T);
1330 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001331}
1332
John McCalla93c9342009-12-07 02:54:59 +00001333TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001334 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001335 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001336 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001337 return DI;
1338}
1339
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001340const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001341ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001342 return getObjCLayout(D, 0);
1343}
1344
1345const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001346ASTContext::getASTObjCImplementationLayout(
1347 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001348 return getObjCLayout(D->getClassInterface(), D);
1349}
1350
Chris Lattnera7674d82007-07-13 22:13:22 +00001351//===----------------------------------------------------------------------===//
1352// Type creation/memoization methods
1353//===----------------------------------------------------------------------===//
1354
Jay Foad4ba2a172011-01-12 09:06:06 +00001355QualType
John McCall3b657512011-01-19 10:06:00 +00001356ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1357 unsigned fastQuals = quals.getFastQualifiers();
1358 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001359
1360 // Check if we've already instantiated this type.
1361 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001362 ExtQuals::Profile(ID, baseType, quals);
1363 void *insertPos = 0;
1364 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1365 assert(eq->getQualifiers() == quals);
1366 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001367 }
1368
John McCall3b657512011-01-19 10:06:00 +00001369 // If the base type is not canonical, make the appropriate canonical type.
1370 QualType canon;
1371 if (!baseType->isCanonicalUnqualified()) {
1372 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1373 canonSplit.second.addConsistentQualifiers(quals);
1374 canon = getExtQualType(canonSplit.first, canonSplit.second);
1375
1376 // Re-find the insert position.
1377 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1378 }
1379
1380 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1381 ExtQualNodes.InsertNode(eq, insertPos);
1382 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001383}
1384
Jay Foad4ba2a172011-01-12 09:06:06 +00001385QualType
1386ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001387 QualType CanT = getCanonicalType(T);
1388 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001389 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001390
John McCall0953e762009-09-24 19:53:00 +00001391 // If we are composing extended qualifiers together, merge together
1392 // into one ExtQuals node.
1393 QualifierCollector Quals;
1394 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001395
John McCall0953e762009-09-24 19:53:00 +00001396 // If this type already has an address space specified, it cannot get
1397 // another one.
1398 assert(!Quals.hasAddressSpace() &&
1399 "Type cannot be in multiple addr spaces!");
1400 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001401
John McCall0953e762009-09-24 19:53:00 +00001402 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001403}
1404
Chris Lattnerb7d25532009-02-18 22:53:11 +00001405QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001406 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001407 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001408 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001409 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001410
John McCall7f040a92010-12-24 02:08:15 +00001411 if (const PointerType *ptr = T->getAs<PointerType>()) {
1412 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001413 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001414 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1415 return getPointerType(ResultType);
1416 }
1417 }
Mike Stump1eb44332009-09-09 15:08:12 +00001418
John McCall0953e762009-09-24 19:53:00 +00001419 // If we are composing extended qualifiers together, merge together
1420 // into one ExtQuals node.
1421 QualifierCollector Quals;
1422 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001423
John McCall0953e762009-09-24 19:53:00 +00001424 // If this type already has an ObjCGC specified, it cannot get
1425 // another one.
1426 assert(!Quals.hasObjCGCAttr() &&
1427 "Type cannot have multiple ObjCGCs!");
1428 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001429
John McCall0953e762009-09-24 19:53:00 +00001430 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001431}
Chris Lattnera7674d82007-07-13 22:13:22 +00001432
John McCalle6a365d2010-12-19 02:44:49 +00001433const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1434 FunctionType::ExtInfo Info) {
1435 if (T->getExtInfo() == Info)
1436 return T;
1437
1438 QualType Result;
1439 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1440 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1441 } else {
1442 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1443 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1444 EPI.ExtInfo = Info;
1445 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1446 FPT->getNumArgs(), EPI);
1447 }
1448
1449 return cast<FunctionType>(Result.getTypePtr());
1450}
1451
Reid Spencer5f016e22007-07-11 17:01:13 +00001452/// getComplexType - Return the uniqued reference to the type for a complex
1453/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001454QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001455 // Unique pointers, to guarantee there is only one pointer of a particular
1456 // structure.
1457 llvm::FoldingSetNodeID ID;
1458 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001459
Reid Spencer5f016e22007-07-11 17:01:13 +00001460 void *InsertPos = 0;
1461 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1462 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001463
Reid Spencer5f016e22007-07-11 17:01:13 +00001464 // If the pointee type isn't canonical, this won't be a canonical type either,
1465 // so fill in the canonical type field.
1466 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001467 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001468 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001469
Reid Spencer5f016e22007-07-11 17:01:13 +00001470 // Get the new insert position for the node we care about.
1471 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001472 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001473 }
John McCall6b304a02009-09-24 23:30:46 +00001474 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001475 Types.push_back(New);
1476 ComplexTypes.InsertNode(New, InsertPos);
1477 return QualType(New, 0);
1478}
1479
Reid Spencer5f016e22007-07-11 17:01:13 +00001480/// getPointerType - Return the uniqued reference to the type for a pointer to
1481/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001482QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001483 // Unique pointers, to guarantee there is only one pointer of a particular
1484 // structure.
1485 llvm::FoldingSetNodeID ID;
1486 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001487
Reid Spencer5f016e22007-07-11 17:01:13 +00001488 void *InsertPos = 0;
1489 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1490 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001491
Reid Spencer5f016e22007-07-11 17:01:13 +00001492 // If the pointee type isn't canonical, this won't be a canonical type either,
1493 // so fill in the canonical type field.
1494 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001495 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001496 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001497
Reid Spencer5f016e22007-07-11 17:01:13 +00001498 // Get the new insert position for the node we care about.
1499 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001500 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001501 }
John McCall6b304a02009-09-24 23:30:46 +00001502 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001503 Types.push_back(New);
1504 PointerTypes.InsertNode(New, InsertPos);
1505 return QualType(New, 0);
1506}
1507
Mike Stump1eb44332009-09-09 15:08:12 +00001508/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001509/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001510QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001511 assert(T->isFunctionType() && "block of function types only");
1512 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001513 // structure.
1514 llvm::FoldingSetNodeID ID;
1515 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001516
Steve Naroff5618bd42008-08-27 16:04:49 +00001517 void *InsertPos = 0;
1518 if (BlockPointerType *PT =
1519 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1520 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001521
1522 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001523 // type either so fill in the canonical type field.
1524 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001525 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001526 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001527
Steve Naroff5618bd42008-08-27 16:04:49 +00001528 // Get the new insert position for the node we care about.
1529 BlockPointerType *NewIP =
1530 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001531 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001532 }
John McCall6b304a02009-09-24 23:30:46 +00001533 BlockPointerType *New
1534 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001535 Types.push_back(New);
1536 BlockPointerTypes.InsertNode(New, InsertPos);
1537 return QualType(New, 0);
1538}
1539
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001540/// getLValueReferenceType - Return the uniqued reference to the type for an
1541/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001542QualType
1543ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00001544 assert(getCanonicalType(T) != OverloadTy &&
1545 "Unresolved overloaded function type");
1546
Reid Spencer5f016e22007-07-11 17:01:13 +00001547 // Unique pointers, to guarantee there is only one pointer of a particular
1548 // structure.
1549 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001550 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001551
1552 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001553 if (LValueReferenceType *RT =
1554 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001555 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001556
John McCall54e14c42009-10-22 22:37:11 +00001557 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1558
Reid Spencer5f016e22007-07-11 17:01:13 +00001559 // If the referencee type isn't canonical, this won't be a canonical type
1560 // either, so fill in the canonical type field.
1561 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001562 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1563 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1564 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001565
Reid Spencer5f016e22007-07-11 17:01:13 +00001566 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001567 LValueReferenceType *NewIP =
1568 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001569 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001570 }
1571
John McCall6b304a02009-09-24 23:30:46 +00001572 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001573 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1574 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001575 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001576 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001577
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001578 return QualType(New, 0);
1579}
1580
1581/// getRValueReferenceType - Return the uniqued reference to the type for an
1582/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001583QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001584 // Unique pointers, to guarantee there is only one pointer of a particular
1585 // structure.
1586 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001587 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001588
1589 void *InsertPos = 0;
1590 if (RValueReferenceType *RT =
1591 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1592 return QualType(RT, 0);
1593
John McCall54e14c42009-10-22 22:37:11 +00001594 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1595
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001596 // If the referencee type isn't canonical, this won't be a canonical type
1597 // either, so fill in the canonical type field.
1598 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001599 if (InnerRef || !T.isCanonical()) {
1600 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1601 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001602
1603 // Get the new insert position for the node we care about.
1604 RValueReferenceType *NewIP =
1605 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001606 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001607 }
1608
John McCall6b304a02009-09-24 23:30:46 +00001609 RValueReferenceType *New
1610 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001611 Types.push_back(New);
1612 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001613 return QualType(New, 0);
1614}
1615
Sebastian Redlf30208a2009-01-24 21:16:55 +00001616/// getMemberPointerType - Return the uniqued reference to the type for a
1617/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00001618QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001619 // Unique pointers, to guarantee there is only one pointer of a particular
1620 // structure.
1621 llvm::FoldingSetNodeID ID;
1622 MemberPointerType::Profile(ID, T, Cls);
1623
1624 void *InsertPos = 0;
1625 if (MemberPointerType *PT =
1626 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1627 return QualType(PT, 0);
1628
1629 // If the pointee or class type isn't canonical, this won't be a canonical
1630 // type either, so fill in the canonical type field.
1631 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001632 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001633 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1634
1635 // Get the new insert position for the node we care about.
1636 MemberPointerType *NewIP =
1637 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001638 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001639 }
John McCall6b304a02009-09-24 23:30:46 +00001640 MemberPointerType *New
1641 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001642 Types.push_back(New);
1643 MemberPointerTypes.InsertNode(New, InsertPos);
1644 return QualType(New, 0);
1645}
1646
Mike Stump1eb44332009-09-09 15:08:12 +00001647/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001648/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001649QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001650 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001651 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001652 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001653 assert((EltTy->isDependentType() ||
1654 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001655 "Constant array of VLAs is illegal!");
1656
Chris Lattner38aeec72009-05-13 04:12:56 +00001657 // Convert the array size into a canonical width matching the pointer size for
1658 // the target.
1659 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001660 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001661 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Reid Spencer5f016e22007-07-11 17:01:13 +00001663 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001664 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001665
Reid Spencer5f016e22007-07-11 17:01:13 +00001666 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001667 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001668 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001669 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001670
John McCall3b657512011-01-19 10:06:00 +00001671 // If the element type isn't canonical or has qualifiers, this won't
1672 // be a canonical type either, so fill in the canonical type field.
1673 QualType Canon;
1674 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1675 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1676 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001677 ASM, IndexTypeQuals);
John McCall3b657512011-01-19 10:06:00 +00001678 Canon = getQualifiedType(Canon, canonSplit.second);
1679
Reid Spencer5f016e22007-07-11 17:01:13 +00001680 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001681 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001682 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001683 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001684 }
Mike Stump1eb44332009-09-09 15:08:12 +00001685
John McCall6b304a02009-09-24 23:30:46 +00001686 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001687 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001688 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001689 Types.push_back(New);
1690 return QualType(New, 0);
1691}
1692
John McCallce889032011-01-18 08:40:38 +00001693/// getVariableArrayDecayedType - Turns the given type, which may be
1694/// variably-modified, into the corresponding type with all the known
1695/// sizes replaced with [*].
1696QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1697 // Vastly most common case.
1698 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001699
John McCallce889032011-01-18 08:40:38 +00001700 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001701
John McCallce889032011-01-18 08:40:38 +00001702 SplitQualType split = type.getSplitDesugaredType();
1703 const Type *ty = split.first;
1704 switch (ty->getTypeClass()) {
1705#define TYPE(Class, Base)
1706#define ABSTRACT_TYPE(Class, Base)
1707#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1708#include "clang/AST/TypeNodes.def"
1709 llvm_unreachable("didn't desugar past all non-canonical types?");
1710
1711 // These types should never be variably-modified.
1712 case Type::Builtin:
1713 case Type::Complex:
1714 case Type::Vector:
1715 case Type::ExtVector:
1716 case Type::DependentSizedExtVector:
1717 case Type::ObjCObject:
1718 case Type::ObjCInterface:
1719 case Type::ObjCObjectPointer:
1720 case Type::Record:
1721 case Type::Enum:
1722 case Type::UnresolvedUsing:
1723 case Type::TypeOfExpr:
1724 case Type::TypeOf:
1725 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00001726 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00001727 case Type::DependentName:
1728 case Type::InjectedClassName:
1729 case Type::TemplateSpecialization:
1730 case Type::DependentTemplateSpecialization:
1731 case Type::TemplateTypeParm:
1732 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00001733 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00001734 case Type::PackExpansion:
1735 llvm_unreachable("type should never be variably-modified");
1736
1737 // These types can be variably-modified but should never need to
1738 // further decay.
1739 case Type::FunctionNoProto:
1740 case Type::FunctionProto:
1741 case Type::BlockPointer:
1742 case Type::MemberPointer:
1743 return type;
1744
1745 // These types can be variably-modified. All these modifications
1746 // preserve structure except as noted by comments.
1747 // TODO: if we ever care about optimizing VLAs, there are no-op
1748 // optimizations available here.
1749 case Type::Pointer:
1750 result = getPointerType(getVariableArrayDecayedType(
1751 cast<PointerType>(ty)->getPointeeType()));
1752 break;
1753
1754 case Type::LValueReference: {
1755 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1756 result = getLValueReferenceType(
1757 getVariableArrayDecayedType(lv->getPointeeType()),
1758 lv->isSpelledAsLValue());
1759 break;
1760 }
1761
1762 case Type::RValueReference: {
1763 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1764 result = getRValueReferenceType(
1765 getVariableArrayDecayedType(lv->getPointeeType()));
1766 break;
1767 }
1768
Eli Friedmanb001de72011-10-06 23:00:33 +00001769 case Type::Atomic: {
1770 const AtomicType *at = cast<AtomicType>(ty);
1771 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1772 break;
1773 }
1774
John McCallce889032011-01-18 08:40:38 +00001775 case Type::ConstantArray: {
1776 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1777 result = getConstantArrayType(
1778 getVariableArrayDecayedType(cat->getElementType()),
1779 cat->getSize(),
1780 cat->getSizeModifier(),
1781 cat->getIndexTypeCVRQualifiers());
1782 break;
1783 }
1784
1785 case Type::DependentSizedArray: {
1786 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1787 result = getDependentSizedArrayType(
1788 getVariableArrayDecayedType(dat->getElementType()),
1789 dat->getSizeExpr(),
1790 dat->getSizeModifier(),
1791 dat->getIndexTypeCVRQualifiers(),
1792 dat->getBracketsRange());
1793 break;
1794 }
1795
1796 // Turn incomplete types into [*] types.
1797 case Type::IncompleteArray: {
1798 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1799 result = getVariableArrayType(
1800 getVariableArrayDecayedType(iat->getElementType()),
1801 /*size*/ 0,
1802 ArrayType::Normal,
1803 iat->getIndexTypeCVRQualifiers(),
1804 SourceRange());
1805 break;
1806 }
1807
1808 // Turn VLA types into [*] types.
1809 case Type::VariableArray: {
1810 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1811 result = getVariableArrayType(
1812 getVariableArrayDecayedType(vat->getElementType()),
1813 /*size*/ 0,
1814 ArrayType::Star,
1815 vat->getIndexTypeCVRQualifiers(),
1816 vat->getBracketsRange());
1817 break;
1818 }
1819 }
1820
1821 // Apply the top-level qualifiers from the original.
1822 return getQualifiedType(result, split.second);
1823}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001824
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001825/// getVariableArrayType - Returns a non-unique reference to the type for a
1826/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001827QualType ASTContext::getVariableArrayType(QualType EltTy,
1828 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001829 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001830 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00001831 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001832 // Since we don't unique expressions, it isn't possible to unique VLA's
1833 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00001834 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00001835
John McCall3b657512011-01-19 10:06:00 +00001836 // Be sure to pull qualifiers off the element type.
1837 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1838 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1839 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001840 IndexTypeQuals, Brackets);
John McCall3b657512011-01-19 10:06:00 +00001841 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor715e9c82010-05-23 16:10:32 +00001842 }
1843
John McCall6b304a02009-09-24 23:30:46 +00001844 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001845 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001846
1847 VariableArrayTypes.push_back(New);
1848 Types.push_back(New);
1849 return QualType(New, 0);
1850}
1851
Douglas Gregor898574e2008-12-05 23:32:09 +00001852/// getDependentSizedArrayType - Returns a non-unique reference to
1853/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001854/// type.
John McCall3b657512011-01-19 10:06:00 +00001855QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1856 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00001857 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001858 unsigned elementTypeQuals,
1859 SourceRange brackets) const {
1860 assert((!numElements || numElements->isTypeDependent() ||
1861 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001862 "Size must be type- or value-dependent!");
1863
John McCall3b657512011-01-19 10:06:00 +00001864 // Dependently-sized array types that do not have a specified number
1865 // of elements will have their sizes deduced from a dependent
1866 // initializer. We do no canonicalization here at all, which is okay
1867 // because they can't be used in most locations.
1868 if (!numElements) {
1869 DependentSizedArrayType *newType
1870 = new (*this, TypeAlignment)
1871 DependentSizedArrayType(*this, elementType, QualType(),
1872 numElements, ASM, elementTypeQuals,
1873 brackets);
1874 Types.push_back(newType);
1875 return QualType(newType, 0);
1876 }
1877
1878 // Otherwise, we actually build a new type every time, but we
1879 // also build a canonical type.
1880
1881 SplitQualType canonElementType = getCanonicalType(elementType).split();
1882
1883 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001884 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001885 DependentSizedArrayType::Profile(ID, *this,
1886 QualType(canonElementType.first, 0),
1887 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001888
John McCall3b657512011-01-19 10:06:00 +00001889 // Look for an existing type with these properties.
1890 DependentSizedArrayType *canonTy =
1891 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001892
John McCall3b657512011-01-19 10:06:00 +00001893 // If we don't have one, build one.
1894 if (!canonTy) {
1895 canonTy = new (*this, TypeAlignment)
1896 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1897 QualType(), numElements, ASM, elementTypeQuals,
1898 brackets);
1899 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1900 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001901 }
1902
John McCall3b657512011-01-19 10:06:00 +00001903 // Apply qualifiers from the element type to the array.
1904 QualType canon = getQualifiedType(QualType(canonTy,0),
1905 canonElementType.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001906
John McCall3b657512011-01-19 10:06:00 +00001907 // If we didn't need extra canonicalization for the element type,
1908 // then just use that as our result.
1909 if (QualType(canonElementType.first, 0) == elementType)
1910 return canon;
1911
1912 // Otherwise, we need to build a type which follows the spelling
1913 // of the element type.
1914 DependentSizedArrayType *sugaredType
1915 = new (*this, TypeAlignment)
1916 DependentSizedArrayType(*this, elementType, canon, numElements,
1917 ASM, elementTypeQuals, brackets);
1918 Types.push_back(sugaredType);
1919 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00001920}
1921
John McCall3b657512011-01-19 10:06:00 +00001922QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00001923 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001924 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001925 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001926 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001927
John McCall3b657512011-01-19 10:06:00 +00001928 void *insertPos = 0;
1929 if (IncompleteArrayType *iat =
1930 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1931 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001932
1933 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00001934 // either, so fill in the canonical type field. We also have to pull
1935 // qualifiers off the element type.
1936 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00001937
John McCall3b657512011-01-19 10:06:00 +00001938 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1939 SplitQualType canonSplit = getCanonicalType(elementType).split();
1940 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1941 ASM, elementTypeQuals);
1942 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001943
1944 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00001945 IncompleteArrayType *existing =
1946 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1947 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001948 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001949
John McCall3b657512011-01-19 10:06:00 +00001950 IncompleteArrayType *newType = new (*this, TypeAlignment)
1951 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001952
John McCall3b657512011-01-19 10:06:00 +00001953 IncompleteArrayTypes.InsertNode(newType, insertPos);
1954 Types.push_back(newType);
1955 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001956}
1957
Steve Naroff73322922007-07-18 18:00:27 +00001958/// getVectorType - Return the unique reference to a vector type of
1959/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001960QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00001961 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00001962 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001963
Reid Spencer5f016e22007-07-11 17:01:13 +00001964 // Check if we've already instantiated a vector of this type.
1965 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00001966 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00001967
Reid Spencer5f016e22007-07-11 17:01:13 +00001968 void *InsertPos = 0;
1969 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1970 return QualType(VTP, 0);
1971
1972 // If the element type isn't canonical, this won't be a canonical type either,
1973 // so fill in the canonical type field.
1974 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00001975 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00001976 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00001977
Reid Spencer5f016e22007-07-11 17:01:13 +00001978 // Get the new insert position for the node we care about.
1979 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001980 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001981 }
John McCall6b304a02009-09-24 23:30:46 +00001982 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00001983 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001984 VectorTypes.InsertNode(New, InsertPos);
1985 Types.push_back(New);
1986 return QualType(New, 0);
1987}
1988
Nate Begeman213541a2008-04-18 23:10:10 +00001989/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001990/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001991QualType
1992ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00001993 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00001994
Steve Naroff73322922007-07-18 18:00:27 +00001995 // Check if we've already instantiated a vector of this type.
1996 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001997 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001998 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00001999 void *InsertPos = 0;
2000 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2001 return QualType(VTP, 0);
2002
2003 // If the element type isn't canonical, this won't be a canonical type either,
2004 // so fill in the canonical type field.
2005 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002006 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002007 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002008
Steve Naroff73322922007-07-18 18:00:27 +00002009 // Get the new insert position for the node we care about.
2010 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002011 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002012 }
John McCall6b304a02009-09-24 23:30:46 +00002013 ExtVectorType *New = new (*this, TypeAlignment)
2014 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002015 VectorTypes.InsertNode(New, InsertPos);
2016 Types.push_back(New);
2017 return QualType(New, 0);
2018}
2019
Jay Foad4ba2a172011-01-12 09:06:06 +00002020QualType
2021ASTContext::getDependentSizedExtVectorType(QualType vecType,
2022 Expr *SizeExpr,
2023 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002024 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002025 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002026 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002027
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002028 void *InsertPos = 0;
2029 DependentSizedExtVectorType *Canon
2030 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2031 DependentSizedExtVectorType *New;
2032 if (Canon) {
2033 // We already have a canonical version of this array type; use it as
2034 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002035 New = new (*this, TypeAlignment)
2036 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2037 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002038 } else {
2039 QualType CanonVecTy = getCanonicalType(vecType);
2040 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002041 New = new (*this, TypeAlignment)
2042 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2043 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002044
2045 DependentSizedExtVectorType *CanonCheck
2046 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2047 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2048 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002049 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2050 } else {
2051 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2052 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002053 New = new (*this, TypeAlignment)
2054 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002055 }
2056 }
Mike Stump1eb44332009-09-09 15:08:12 +00002057
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002058 Types.push_back(New);
2059 return QualType(New, 0);
2060}
2061
Douglas Gregor72564e72009-02-26 23:50:07 +00002062/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002063///
Jay Foad4ba2a172011-01-12 09:06:06 +00002064QualType
2065ASTContext::getFunctionNoProtoType(QualType ResultTy,
2066 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002067 const CallingConv DefaultCC = Info.getCC();
2068 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2069 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002070 // Unique functions, to guarantee there is only one function of a particular
2071 // structure.
2072 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002073 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Reid Spencer5f016e22007-07-11 17:01:13 +00002075 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002076 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002077 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002078 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002079
Reid Spencer5f016e22007-07-11 17:01:13 +00002080 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002081 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002082 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002083 Canonical =
2084 getFunctionNoProtoType(getCanonicalType(ResultTy),
2085 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002086
Reid Spencer5f016e22007-07-11 17:01:13 +00002087 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002088 FunctionNoProtoType *NewIP =
2089 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002090 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002091 }
Mike Stump1eb44332009-09-09 15:08:12 +00002092
Roman Divackycfe9af22011-03-01 17:40:53 +00002093 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002094 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002095 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002096 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002097 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002098 return QualType(New, 0);
2099}
2100
2101/// getFunctionType - Return a normal function type with a typed argument
2102/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002103QualType
2104ASTContext::getFunctionType(QualType ResultTy,
2105 const QualType *ArgArray, unsigned NumArgs,
2106 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002107 // Unique functions, to guarantee there is only one function of a particular
2108 // structure.
2109 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002110 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002111
2112 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002113 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002114 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002115 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002116
2117 // Determine whether the type being created is already canonical or not.
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002118 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00002119 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002120 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002121 isCanonical = false;
2122
Roman Divackycfe9af22011-03-01 17:40:53 +00002123 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2124 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2125 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002126
Reid Spencer5f016e22007-07-11 17:01:13 +00002127 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002128 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002129 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002130 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002131 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002132 CanonicalArgs.reserve(NumArgs);
2133 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002134 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002135
John McCalle23cf432010-12-14 08:05:40 +00002136 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002137 CanonicalEPI.ExceptionSpecType = EST_None;
2138 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002139 CanonicalEPI.ExtInfo
2140 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2141
Chris Lattnerf52ab252008-04-06 22:59:24 +00002142 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00002143 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002144 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002145
Reid Spencer5f016e22007-07-11 17:01:13 +00002146 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002147 FunctionProtoType *NewIP =
2148 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002149 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002150 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002151
John McCallf85e1932011-06-15 23:02:42 +00002152 // FunctionProtoType objects are allocated with extra bytes after
2153 // them for three variable size arrays at the end:
2154 // - parameter types
2155 // - exception types
2156 // - consumed-arguments flags
2157 // Instead of the exception types, there could be a noexcept
2158 // expression.
John McCalle23cf432010-12-14 08:05:40 +00002159 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002160 NumArgs * sizeof(QualType);
2161 if (EPI.ExceptionSpecType == EST_Dynamic)
2162 Size += EPI.NumExceptions * sizeof(QualType);
2163 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002164 Size += sizeof(Expr*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002165 }
John McCallf85e1932011-06-15 23:02:42 +00002166 if (EPI.ConsumedArguments)
2167 Size += NumArgs * sizeof(bool);
2168
John McCalle23cf432010-12-14 08:05:40 +00002169 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002170 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2171 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002172 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002173 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002174 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002175 return QualType(FTP, 0);
2176}
2177
John McCall3cb0ebd2010-03-10 03:28:59 +00002178#ifndef NDEBUG
2179static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2180 if (!isa<CXXRecordDecl>(D)) return false;
2181 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2182 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2183 return true;
2184 if (RD->getDescribedClassTemplate() &&
2185 !isa<ClassTemplateSpecializationDecl>(RD))
2186 return true;
2187 return false;
2188}
2189#endif
2190
2191/// getInjectedClassNameType - Return the unique reference to the
2192/// injected class name type for the specified templated declaration.
2193QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002194 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002195 assert(NeedsInjectedClassNameType(Decl));
2196 if (Decl->TypeForDecl) {
2197 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00002198 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002199 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2200 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2201 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2202 } else {
John McCallf4c73712011-01-19 06:33:43 +00002203 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002204 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002205 Decl->TypeForDecl = newType;
2206 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002207 }
2208 return QualType(Decl->TypeForDecl, 0);
2209}
2210
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002211/// getTypeDeclType - Return the unique reference to the type for the
2212/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002213QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002214 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002215 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002216
Richard Smith162e1c12011-04-15 14:24:37 +00002217 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002218 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002219
John McCallbecb8d52010-03-10 06:48:02 +00002220 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2221 "Template type parameter types are always available.");
2222
John McCall19c85762010-02-16 03:57:14 +00002223 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002224 assert(!Record->getPreviousDeclaration() &&
2225 "struct/union has previous declaration");
2226 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002227 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002228 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002229 assert(!Enum->getPreviousDeclaration() &&
2230 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002231 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002232 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002233 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002234 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2235 Decl->TypeForDecl = newType;
2236 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002237 } else
John McCallbecb8d52010-03-10 06:48:02 +00002238 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002239
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002240 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002241}
2242
Reid Spencer5f016e22007-07-11 17:01:13 +00002243/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002244/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002245QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002246ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2247 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002248 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002249
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002250 if (Canonical.isNull())
2251 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002252 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002253 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002254 Decl->TypeForDecl = newType;
2255 Types.push_back(newType);
2256 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002257}
2258
Jay Foad4ba2a172011-01-12 09:06:06 +00002259QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002260 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2261
2262 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2263 if (PrevDecl->TypeForDecl)
2264 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2265
John McCallf4c73712011-01-19 06:33:43 +00002266 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2267 Decl->TypeForDecl = newType;
2268 Types.push_back(newType);
2269 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002270}
2271
Jay Foad4ba2a172011-01-12 09:06:06 +00002272QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002273 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2274
2275 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2276 if (PrevDecl->TypeForDecl)
2277 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2278
John McCallf4c73712011-01-19 06:33:43 +00002279 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2280 Decl->TypeForDecl = newType;
2281 Types.push_back(newType);
2282 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002283}
2284
John McCall9d156a72011-01-06 01:58:22 +00002285QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2286 QualType modifiedType,
2287 QualType equivalentType) {
2288 llvm::FoldingSetNodeID id;
2289 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2290
2291 void *insertPos = 0;
2292 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2293 if (type) return QualType(type, 0);
2294
2295 QualType canon = getCanonicalType(equivalentType);
2296 type = new (*this, TypeAlignment)
2297 AttributedType(canon, attrKind, modifiedType, equivalentType);
2298
2299 Types.push_back(type);
2300 AttributedTypes.InsertNode(type, insertPos);
2301
2302 return QualType(type, 0);
2303}
2304
2305
John McCall49a832b2009-10-18 09:09:24 +00002306/// \brief Retrieve a substitution-result type.
2307QualType
2308ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002309 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002310 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002311 && "replacement types must always be canonical");
2312
2313 llvm::FoldingSetNodeID ID;
2314 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2315 void *InsertPos = 0;
2316 SubstTemplateTypeParmType *SubstParm
2317 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2318
2319 if (!SubstParm) {
2320 SubstParm = new (*this, TypeAlignment)
2321 SubstTemplateTypeParmType(Parm, Replacement);
2322 Types.push_back(SubstParm);
2323 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2324 }
2325
2326 return QualType(SubstParm, 0);
2327}
2328
Douglas Gregorc3069d62011-01-14 02:55:32 +00002329/// \brief Retrieve a
2330QualType ASTContext::getSubstTemplateTypeParmPackType(
2331 const TemplateTypeParmType *Parm,
2332 const TemplateArgument &ArgPack) {
2333#ifndef NDEBUG
2334 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2335 PEnd = ArgPack.pack_end();
2336 P != PEnd; ++P) {
2337 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2338 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2339 }
2340#endif
2341
2342 llvm::FoldingSetNodeID ID;
2343 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2344 void *InsertPos = 0;
2345 if (SubstTemplateTypeParmPackType *SubstParm
2346 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2347 return QualType(SubstParm, 0);
2348
2349 QualType Canon;
2350 if (!Parm->isCanonicalUnqualified()) {
2351 Canon = getCanonicalType(QualType(Parm, 0));
2352 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2353 ArgPack);
2354 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2355 }
2356
2357 SubstTemplateTypeParmPackType *SubstParm
2358 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2359 ArgPack);
2360 Types.push_back(SubstParm);
2361 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2362 return QualType(SubstParm, 0);
2363}
2364
Douglas Gregorfab9d672009-02-05 23:33:38 +00002365/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002366/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002367/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002368QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002369 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002370 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002371 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002372 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002373 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002374 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002375 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2376
2377 if (TypeParm)
2378 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002379
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002380 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002381 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002382 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002383
2384 TemplateTypeParmType *TypeCheck
2385 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2386 assert(!TypeCheck && "Template type parameter canonical type broken");
2387 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002388 } else
John McCall6b304a02009-09-24 23:30:46 +00002389 TypeParm = new (*this, TypeAlignment)
2390 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002391
2392 Types.push_back(TypeParm);
2393 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2394
2395 return QualType(TypeParm, 0);
2396}
2397
John McCall3cb0ebd2010-03-10 03:28:59 +00002398TypeSourceInfo *
2399ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2400 SourceLocation NameLoc,
2401 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002402 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002403 assert(!Name.getAsDependentTemplateName() &&
2404 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002405 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002406
2407 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2408 TemplateSpecializationTypeLoc TL
2409 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2410 TL.setTemplateNameLoc(NameLoc);
2411 TL.setLAngleLoc(Args.getLAngleLoc());
2412 TL.setRAngleLoc(Args.getRAngleLoc());
2413 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2414 TL.setArgLocInfo(i, Args[i].getLocInfo());
2415 return DI;
2416}
2417
Mike Stump1eb44332009-09-09 15:08:12 +00002418QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002419ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002420 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002421 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002422 assert(!Template.getAsDependentTemplateName() &&
2423 "No dependent template names here!");
2424
John McCalld5532b62009-11-23 01:53:49 +00002425 unsigned NumArgs = Args.size();
2426
Chris Lattner5f9e2722011-07-23 10:55:15 +00002427 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002428 ArgVec.reserve(NumArgs);
2429 for (unsigned i = 0; i != NumArgs; ++i)
2430 ArgVec.push_back(Args[i].getArgument());
2431
John McCall31f17ec2010-04-27 00:57:59 +00002432 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002433 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002434}
2435
2436QualType
2437ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002438 const TemplateArgument *Args,
2439 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002440 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002441 assert(!Template.getAsDependentTemplateName() &&
2442 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002443 // Look through qualified template names.
2444 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2445 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002446
Richard Smith3e4c6c42011-05-05 21:57:07 +00002447 bool isTypeAlias =
2448 Template.getAsTemplateDecl() &&
2449 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2450
2451 QualType CanonType;
2452 if (!Underlying.isNull())
2453 CanonType = getCanonicalType(Underlying);
2454 else {
2455 assert(!isTypeAlias &&
2456 "Underlying type for template alias must be computed by caller");
2457 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2458 NumArgs);
2459 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002460
Douglas Gregor1275ae02009-07-28 23:00:59 +00002461 // Allocate the (non-canonical) template specialization type, but don't
2462 // try to unique it: these types typically have location information that
2463 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002464 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2465 sizeof(TemplateArgument) * NumArgs +
2466 (isTypeAlias ? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00002467 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002468 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00002469 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00002470 Args, NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002471 CanonType,
2472 isTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00002473
Douglas Gregor55f6b142009-02-09 18:46:07 +00002474 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002475 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002476}
2477
Mike Stump1eb44332009-09-09 15:08:12 +00002478QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002479ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2480 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002481 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002482 assert(!Template.getAsDependentTemplateName() &&
2483 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002484 assert((!Template.getAsTemplateDecl() ||
2485 !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2486 "Underlying type for template alias must be computed by caller");
2487
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002488 // Look through qualified template names.
2489 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2490 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002491
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002492 // Build the canonical template specialization type.
2493 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002494 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002495 CanonArgs.reserve(NumArgs);
2496 for (unsigned I = 0; I != NumArgs; ++I)
2497 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2498
2499 // Determine whether this canonical template specialization type already
2500 // exists.
2501 llvm::FoldingSetNodeID ID;
2502 TemplateSpecializationType::Profile(ID, CanonTemplate,
2503 CanonArgs.data(), NumArgs, *this);
2504
2505 void *InsertPos = 0;
2506 TemplateSpecializationType *Spec
2507 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2508
2509 if (!Spec) {
2510 // Allocate a new canonical template specialization type.
2511 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2512 sizeof(TemplateArgument) * NumArgs),
2513 TypeAlignment);
2514 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2515 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002516 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002517 Types.push_back(Spec);
2518 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2519 }
2520
2521 assert(Spec->isDependentType() &&
2522 "Non-dependent template-id type must have a canonical type");
2523 return QualType(Spec, 0);
2524}
2525
2526QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002527ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2528 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002529 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002530 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002531 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002532
2533 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002534 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002535 if (T)
2536 return QualType(T, 0);
2537
Douglas Gregor789b1f62010-02-04 18:10:26 +00002538 QualType Canon = NamedType;
2539 if (!Canon.isCanonical()) {
2540 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002541 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2542 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002543 (void)CheckT;
2544 }
2545
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002546 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002547 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002548 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002549 return QualType(T, 0);
2550}
2551
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002552QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002553ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002554 llvm::FoldingSetNodeID ID;
2555 ParenType::Profile(ID, InnerType);
2556
2557 void *InsertPos = 0;
2558 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2559 if (T)
2560 return QualType(T, 0);
2561
2562 QualType Canon = InnerType;
2563 if (!Canon.isCanonical()) {
2564 Canon = getCanonicalType(InnerType);
2565 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2566 assert(!CheckT && "Paren canonical type broken");
2567 (void)CheckT;
2568 }
2569
2570 T = new (*this) ParenType(InnerType, Canon);
2571 Types.push_back(T);
2572 ParenTypes.InsertNode(T, InsertPos);
2573 return QualType(T, 0);
2574}
2575
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002576QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2577 NestedNameSpecifier *NNS,
2578 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002579 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002580 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2581
2582 if (Canon.isNull()) {
2583 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002584 ElaboratedTypeKeyword CanonKeyword = Keyword;
2585 if (Keyword == ETK_None)
2586 CanonKeyword = ETK_Typename;
2587
2588 if (CanonNNS != NNS || CanonKeyword != Keyword)
2589 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002590 }
2591
2592 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002593 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002594
2595 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002596 DependentNameType *T
2597 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002598 if (T)
2599 return QualType(T, 0);
2600
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002601 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002602 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002603 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002604 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002605}
2606
Mike Stump1eb44332009-09-09 15:08:12 +00002607QualType
John McCall33500952010-06-11 00:33:02 +00002608ASTContext::getDependentTemplateSpecializationType(
2609 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002610 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002611 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002612 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00002613 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00002614 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00002615 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2616 ArgCopy.push_back(Args[I].getArgument());
2617 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2618 ArgCopy.size(),
2619 ArgCopy.data());
2620}
2621
2622QualType
2623ASTContext::getDependentTemplateSpecializationType(
2624 ElaboratedTypeKeyword Keyword,
2625 NestedNameSpecifier *NNS,
2626 const IdentifierInfo *Name,
2627 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002628 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00002629 assert((!NNS || NNS->isDependent()) &&
2630 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00002631
Douglas Gregor789b1f62010-02-04 18:10:26 +00002632 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002633 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2634 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002635
2636 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002637 DependentTemplateSpecializationType *T
2638 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002639 if (T)
2640 return QualType(T, 0);
2641
John McCall33500952010-06-11 00:33:02 +00002642 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002643
John McCall33500952010-06-11 00:33:02 +00002644 ElaboratedTypeKeyword CanonKeyword = Keyword;
2645 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2646
2647 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002648 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00002649 for (unsigned I = 0; I != NumArgs; ++I) {
2650 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2651 if (!CanonArgs[I].structurallyEquals(Args[I]))
2652 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002653 }
2654
John McCall33500952010-06-11 00:33:02 +00002655 QualType Canon;
2656 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2657 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2658 Name, NumArgs,
2659 CanonArgs.data());
2660
2661 // Find the insert position again.
2662 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2663 }
2664
2665 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2666 sizeof(TemplateArgument) * NumArgs),
2667 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002668 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002669 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002670 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002671 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002672 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002673}
2674
Douglas Gregorcded4f62011-01-14 17:04:44 +00002675QualType ASTContext::getPackExpansionType(QualType Pattern,
2676 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00002677 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002678 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002679
2680 assert(Pattern->containsUnexpandedParameterPack() &&
2681 "Pack expansions must expand one or more parameter packs");
2682 void *InsertPos = 0;
2683 PackExpansionType *T
2684 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2685 if (T)
2686 return QualType(T, 0);
2687
2688 QualType Canon;
2689 if (!Pattern.isCanonical()) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002690 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002691
2692 // Find the insert position again.
2693 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2694 }
2695
Douglas Gregorcded4f62011-01-14 17:04:44 +00002696 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002697 Types.push_back(T);
2698 PackExpansionTypes.InsertNode(T, InsertPos);
2699 return QualType(T, 0);
2700}
2701
Chris Lattner88cb27a2008-04-07 04:56:42 +00002702/// CmpProtocolNames - Comparison predicate for sorting protocols
2703/// alphabetically.
2704static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2705 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002706 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002707}
2708
John McCallc12c5bb2010-05-15 11:32:37 +00002709static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002710 unsigned NumProtocols) {
2711 if (NumProtocols == 0) return true;
2712
Douglas Gregor61cc2962012-01-02 02:00:30 +00002713 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2714 return false;
2715
John McCall54e14c42009-10-22 22:37:11 +00002716 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00002717 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2718 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00002719 return false;
2720 return true;
2721}
2722
2723static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002724 unsigned &NumProtocols) {
2725 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002726
Chris Lattner88cb27a2008-04-07 04:56:42 +00002727 // Sort protocols, keyed by name.
2728 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2729
Douglas Gregor61cc2962012-01-02 02:00:30 +00002730 // Canonicalize.
2731 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2732 Protocols[I] = Protocols[I]->getCanonicalDecl();
2733
Chris Lattner88cb27a2008-04-07 04:56:42 +00002734 // Remove duplicates.
2735 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2736 NumProtocols = ProtocolsEnd-Protocols;
2737}
2738
John McCallc12c5bb2010-05-15 11:32:37 +00002739QualType ASTContext::getObjCObjectType(QualType BaseType,
2740 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00002741 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002742 // If the base type is an interface and there aren't any protocols
2743 // to add, then the interface type will do just fine.
2744 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2745 return BaseType;
2746
2747 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002748 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002749 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002750 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002751 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2752 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002753
John McCallc12c5bb2010-05-15 11:32:37 +00002754 // Build the canonical type, which has the canonical base type and
2755 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002756 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002757 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2758 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2759 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002760 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00002761 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002762 unsigned UniqueCount = NumProtocols;
2763
John McCall54e14c42009-10-22 22:37:11 +00002764 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002765 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2766 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002767 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002768 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2769 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002770 }
2771
2772 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002773 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2774 }
2775
2776 unsigned Size = sizeof(ObjCObjectTypeImpl);
2777 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2778 void *Mem = Allocate(Size, TypeAlignment);
2779 ObjCObjectTypeImpl *T =
2780 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2781
2782 Types.push_back(T);
2783 ObjCObjectTypes.InsertNode(T, InsertPos);
2784 return QualType(T, 0);
2785}
2786
2787/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2788/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002789QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002790 llvm::FoldingSetNodeID ID;
2791 ObjCObjectPointerType::Profile(ID, ObjectT);
2792
2793 void *InsertPos = 0;
2794 if (ObjCObjectPointerType *QT =
2795 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2796 return QualType(QT, 0);
2797
2798 // Find the canonical object type.
2799 QualType Canonical;
2800 if (!ObjectT.isCanonical()) {
2801 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2802
2803 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002804 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2805 }
2806
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002807 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002808 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2809 ObjCObjectPointerType *QType =
2810 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002811
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002812 Types.push_back(QType);
2813 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002814 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002815}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002816
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002817/// getObjCInterfaceType - Return the unique reference to the type for the
2818/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00002819QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
2820 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002821 if (Decl->TypeForDecl)
2822 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002823
Douglas Gregor0af55012011-12-16 03:12:41 +00002824 if (PrevDecl) {
2825 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
2826 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2827 return QualType(PrevDecl->TypeForDecl, 0);
2828 }
2829
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00002830 // Prefer the definition, if there is one.
2831 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
2832 Decl = Def;
2833
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002834 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2835 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2836 Decl->TypeForDecl = T;
2837 Types.push_back(T);
2838 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002839}
2840
Douglas Gregor72564e72009-02-26 23:50:07 +00002841/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2842/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002843/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002844/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002845/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002846QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002847 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002848 if (tofExpr->isTypeDependent()) {
2849 llvm::FoldingSetNodeID ID;
2850 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002851
Douglas Gregorb1975722009-07-30 23:18:24 +00002852 void *InsertPos = 0;
2853 DependentTypeOfExprType *Canon
2854 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2855 if (Canon) {
2856 // We already have a "canonical" version of an identical, dependent
2857 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002858 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002859 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00002860 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00002861 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002862 Canon
2863 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002864 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2865 toe = Canon;
2866 }
2867 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002868 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002869 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002870 }
Steve Naroff9752f252007-08-01 18:02:17 +00002871 Types.push_back(toe);
2872 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002873}
2874
Steve Naroff9752f252007-08-01 18:02:17 +00002875/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2876/// TypeOfType AST's. The only motivation to unique these nodes would be
2877/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002878/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002879/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002880QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002881 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002882 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002883 Types.push_back(tot);
2884 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002885}
2886
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002887/// getDecltypeForExpr - Given an expr, will return the decltype for that
2888/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad4ba2a172011-01-12 09:06:06 +00002889static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002890 if (e->isTypeDependent())
2891 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002892
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002893 // If e is an id expression or a class member access, decltype(e) is defined
2894 // as the type of the entity named by e.
2895 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2896 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2897 return VD->getType();
2898 }
2899 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2900 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2901 return FD->getType();
2902 }
2903 // If e is a function call or an invocation of an overloaded operator,
2904 // (parentheses around e are ignored), decltype(e) is defined as the
2905 // return type of that function.
2906 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2907 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002908
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002909 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002910
2911 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002912 // defined as T&, otherwise decltype(e) is defined as T.
John McCall7eb0a9e2010-11-24 05:12:34 +00002913 if (e->isLValue())
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002914 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002915
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002916 return T;
2917}
2918
Anders Carlsson395b4752009-06-24 19:06:50 +00002919/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2920/// DecltypeType AST's. The only motivation to unique these nodes would be
2921/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002922/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00002923/// on canonical types (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002924QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002925 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00002926
2927 // C++0x [temp.type]p2:
2928 // If an expression e involves a template parameter, decltype(e) denotes a
2929 // unique dependent type. Two such decltype-specifiers refer to the same
2930 // type only if their expressions are equivalent (14.5.6.1).
2931 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002932 llvm::FoldingSetNodeID ID;
2933 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002934
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002935 void *InsertPos = 0;
2936 DependentDecltypeType *Canon
2937 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2938 if (Canon) {
2939 // We already have a "canonical" version of an equivalent, dependent
2940 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002941 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002942 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00002943 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002944 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002945 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002946 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2947 dt = Canon;
2948 }
2949 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002950 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002951 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002952 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002953 Types.push_back(dt);
2954 return QualType(dt, 0);
2955}
2956
Sean Huntca63c202011-05-24 22:41:36 +00002957/// getUnaryTransformationType - We don't unique these, since the memory
2958/// savings are minimal and these are rare.
2959QualType ASTContext::getUnaryTransformType(QualType BaseType,
2960 QualType UnderlyingType,
2961 UnaryTransformType::UTTKind Kind)
2962 const {
2963 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00002964 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2965 Kind,
2966 UnderlyingType->isDependentType() ?
2967 QualType() : UnderlyingType);
Sean Huntca63c202011-05-24 22:41:36 +00002968 Types.push_back(Ty);
2969 return QualType(Ty, 0);
2970}
2971
Richard Smith483b9f32011-02-21 20:05:19 +00002972/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00002973QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00002974 void *InsertPos = 0;
2975 if (!DeducedType.isNull()) {
2976 // Look in the folding set for an existing type.
2977 llvm::FoldingSetNodeID ID;
2978 AutoType::Profile(ID, DeducedType);
2979 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2980 return QualType(AT, 0);
2981 }
2982
2983 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2984 Types.push_back(AT);
2985 if (InsertPos)
2986 AutoTypes.InsertNode(AT, InsertPos);
2987 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00002988}
2989
Eli Friedmanb001de72011-10-06 23:00:33 +00002990/// getAtomicType - Return the uniqued reference to the atomic type for
2991/// the given value type.
2992QualType ASTContext::getAtomicType(QualType T) const {
2993 // Unique pointers, to guarantee there is only one pointer of a particular
2994 // structure.
2995 llvm::FoldingSetNodeID ID;
2996 AtomicType::Profile(ID, T);
2997
2998 void *InsertPos = 0;
2999 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3000 return QualType(AT, 0);
3001
3002 // If the atomic value type isn't canonical, this won't be a canonical type
3003 // either, so fill in the canonical type field.
3004 QualType Canonical;
3005 if (!T.isCanonical()) {
3006 Canonical = getAtomicType(getCanonicalType(T));
3007
3008 // Get the new insert position for the node we care about.
3009 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3010 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3011 }
3012 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3013 Types.push_back(New);
3014 AtomicTypes.InsertNode(New, InsertPos);
3015 return QualType(New, 0);
3016}
3017
Richard Smithad762fc2011-04-14 22:09:26 +00003018/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3019QualType ASTContext::getAutoDeductType() const {
3020 if (AutoDeductTy.isNull())
3021 AutoDeductTy = getAutoType(QualType());
3022 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3023 return AutoDeductTy;
3024}
3025
3026/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3027QualType ASTContext::getAutoRRefDeductType() const {
3028 if (AutoRRefDeductTy.isNull())
3029 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3030 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3031 return AutoRRefDeductTy;
3032}
3033
Reid Spencer5f016e22007-07-11 17:01:13 +00003034/// getTagDeclType - Return the unique reference to the type for the
3035/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003036QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003037 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003038 // FIXME: What is the design on getTagDeclType when it requires casting
3039 // away const? mutable?
3040 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003041}
3042
Mike Stump1eb44332009-09-09 15:08:12 +00003043/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3044/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3045/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003046CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003047 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003048}
3049
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003050/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3051CanQualType ASTContext::getIntMaxType() const {
3052 return getFromTargetType(Target->getIntMaxType());
3053}
3054
3055/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3056CanQualType ASTContext::getUIntMaxType() const {
3057 return getFromTargetType(Target->getUIntMaxType());
3058}
3059
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003060/// getSignedWCharType - Return the type of "signed wchar_t".
3061/// Used when in C++, as a GCC extension.
3062QualType ASTContext::getSignedWCharType() const {
3063 // FIXME: derive from "Target" ?
3064 return WCharTy;
3065}
3066
3067/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3068/// Used when in C++, as a GCC extension.
3069QualType ASTContext::getUnsignedWCharType() const {
3070 // FIXME: derive from "Target" ?
3071 return UnsignedIntTy;
3072}
3073
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003074/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003075/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3076QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003077 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003078}
3079
Chris Lattnere6327742008-04-02 05:18:44 +00003080//===----------------------------------------------------------------------===//
3081// Type Operators
3082//===----------------------------------------------------------------------===//
3083
Jay Foad4ba2a172011-01-12 09:06:06 +00003084CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003085 // Push qualifiers into arrays, and then discard any remaining
3086 // qualifiers.
3087 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003088 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003089 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003090 QualType Result;
3091 if (isa<ArrayType>(Ty)) {
3092 Result = getArrayDecayedType(QualType(Ty,0));
3093 } else if (isa<FunctionType>(Ty)) {
3094 Result = getPointerType(QualType(Ty, 0));
3095 } else {
3096 Result = QualType(Ty, 0);
3097 }
3098
3099 return CanQualType::CreateUnsafe(Result);
3100}
3101
John McCall62c28c82011-01-18 07:41:22 +00003102QualType ASTContext::getUnqualifiedArrayType(QualType type,
3103 Qualifiers &quals) {
3104 SplitQualType splitType = type.getSplitUnqualifiedType();
3105
3106 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3107 // the unqualified desugared type and then drops it on the floor.
3108 // We then have to strip that sugar back off with
3109 // getUnqualifiedDesugaredType(), which is silly.
3110 const ArrayType *AT =
3111 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
3112
3113 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003114 if (!AT) {
John McCall62c28c82011-01-18 07:41:22 +00003115 quals = splitType.second;
3116 return QualType(splitType.first, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003117 }
3118
John McCall62c28c82011-01-18 07:41:22 +00003119 // Otherwise, recurse on the array's element type.
3120 QualType elementType = AT->getElementType();
3121 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3122
3123 // If that didn't change the element type, AT has no qualifiers, so we
3124 // can just use the results in splitType.
3125 if (elementType == unqualElementType) {
3126 assert(quals.empty()); // from the recursive call
3127 quals = splitType.second;
3128 return QualType(splitType.first, 0);
3129 }
3130
3131 // Otherwise, add in the qualifiers from the outermost type, then
3132 // build the type back up.
3133 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003134
Douglas Gregor9dadd942010-05-17 18:45:21 +00003135 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003136 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003137 CAT->getSizeModifier(), 0);
3138 }
3139
Douglas Gregor9dadd942010-05-17 18:45:21 +00003140 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003141 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003142 }
3143
Douglas Gregor9dadd942010-05-17 18:45:21 +00003144 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003145 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003146 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003147 VAT->getSizeModifier(),
3148 VAT->getIndexTypeCVRQualifiers(),
3149 VAT->getBracketsRange());
3150 }
3151
3152 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003153 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003154 DSAT->getSizeModifier(), 0,
3155 SourceRange());
3156}
3157
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003158/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3159/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3160/// they point to and return true. If T1 and T2 aren't pointer types
3161/// or pointer-to-member types, or if they are not similar at this
3162/// level, returns false and leaves T1 and T2 unchanged. Top-level
3163/// qualifiers on T1 and T2 are ignored. This function will typically
3164/// be called in a loop that successively "unwraps" pointer and
3165/// pointer-to-member types to compare them at each level.
3166bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3167 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3168 *T2PtrType = T2->getAs<PointerType>();
3169 if (T1PtrType && T2PtrType) {
3170 T1 = T1PtrType->getPointeeType();
3171 T2 = T2PtrType->getPointeeType();
3172 return true;
3173 }
3174
3175 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3176 *T2MPType = T2->getAs<MemberPointerType>();
3177 if (T1MPType && T2MPType &&
3178 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3179 QualType(T2MPType->getClass(), 0))) {
3180 T1 = T1MPType->getPointeeType();
3181 T2 = T2MPType->getPointeeType();
3182 return true;
3183 }
3184
3185 if (getLangOptions().ObjC1) {
3186 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3187 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3188 if (T1OPType && T2OPType) {
3189 T1 = T1OPType->getPointeeType();
3190 T2 = T2OPType->getPointeeType();
3191 return true;
3192 }
3193 }
3194
3195 // FIXME: Block pointers, too?
3196
3197 return false;
3198}
3199
Jay Foad4ba2a172011-01-12 09:06:06 +00003200DeclarationNameInfo
3201ASTContext::getNameForTemplate(TemplateName Name,
3202 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003203 switch (Name.getKind()) {
3204 case TemplateName::QualifiedTemplate:
3205 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003206 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003207 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3208 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003209
John McCall14606042011-06-30 08:33:18 +00003210 case TemplateName::OverloadedTemplate: {
3211 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3212 // DNInfo work in progress: CHECKME: what about DNLoc?
3213 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3214 }
3215
3216 case TemplateName::DependentTemplate: {
3217 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003218 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003219 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003220 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3221 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003222 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003223 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3224 // DNInfo work in progress: FIXME: source locations?
3225 DeclarationNameLoc DNLoc;
3226 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3227 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3228 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003229 }
3230 }
3231
John McCall14606042011-06-30 08:33:18 +00003232 case TemplateName::SubstTemplateTemplateParm: {
3233 SubstTemplateTemplateParmStorage *subst
3234 = Name.getAsSubstTemplateTemplateParm();
3235 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3236 NameLoc);
3237 }
3238
3239 case TemplateName::SubstTemplateTemplateParmPack: {
3240 SubstTemplateTemplateParmPackStorage *subst
3241 = Name.getAsSubstTemplateTemplateParmPack();
3242 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3243 NameLoc);
3244 }
3245 }
3246
3247 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003248}
3249
Jay Foad4ba2a172011-01-12 09:06:06 +00003250TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003251 switch (Name.getKind()) {
3252 case TemplateName::QualifiedTemplate:
3253 case TemplateName::Template: {
3254 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003255 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003256 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003257 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3258
3259 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003260 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003261 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003262
John McCall14606042011-06-30 08:33:18 +00003263 case TemplateName::OverloadedTemplate:
3264 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003265
John McCall14606042011-06-30 08:33:18 +00003266 case TemplateName::DependentTemplate: {
3267 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3268 assert(DTN && "Non-dependent template names must refer to template decls.");
3269 return DTN->CanonicalTemplateName;
3270 }
3271
3272 case TemplateName::SubstTemplateTemplateParm: {
3273 SubstTemplateTemplateParmStorage *subst
3274 = Name.getAsSubstTemplateTemplateParm();
3275 return getCanonicalTemplateName(subst->getReplacement());
3276 }
3277
3278 case TemplateName::SubstTemplateTemplateParmPack: {
3279 SubstTemplateTemplateParmPackStorage *subst
3280 = Name.getAsSubstTemplateTemplateParmPack();
3281 TemplateTemplateParmDecl *canonParameter
3282 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3283 TemplateArgument canonArgPack
3284 = getCanonicalTemplateArgument(subst->getArgumentPack());
3285 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3286 }
3287 }
3288
3289 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003290}
3291
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003292bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3293 X = getCanonicalTemplateName(X);
3294 Y = getCanonicalTemplateName(Y);
3295 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3296}
3297
Mike Stump1eb44332009-09-09 15:08:12 +00003298TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003299ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003300 switch (Arg.getKind()) {
3301 case TemplateArgument::Null:
3302 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003303
Douglas Gregor1275ae02009-07-28 23:00:59 +00003304 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003305 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003306
Douglas Gregor1275ae02009-07-28 23:00:59 +00003307 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00003308 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003309
Douglas Gregor788cd062009-11-11 01:00:40 +00003310 case TemplateArgument::Template:
3311 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003312
3313 case TemplateArgument::TemplateExpansion:
3314 return TemplateArgument(getCanonicalTemplateName(
3315 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003316 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003317
Douglas Gregor1275ae02009-07-28 23:00:59 +00003318 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00003319 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003320 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003321
Douglas Gregor1275ae02009-07-28 23:00:59 +00003322 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003323 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003324
Douglas Gregor1275ae02009-07-28 23:00:59 +00003325 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003326 if (Arg.pack_size() == 0)
3327 return Arg;
3328
Douglas Gregor910f8002010-11-07 23:05:16 +00003329 TemplateArgument *CanonArgs
3330 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003331 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003332 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003333 AEnd = Arg.pack_end();
3334 A != AEnd; (void)++A, ++Idx)
3335 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003336
Douglas Gregor910f8002010-11-07 23:05:16 +00003337 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003338 }
3339 }
3340
3341 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00003342 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00003343}
3344
Douglas Gregord57959a2009-03-27 23:10:48 +00003345NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003346ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003347 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003348 return 0;
3349
3350 switch (NNS->getKind()) {
3351 case NestedNameSpecifier::Identifier:
3352 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003353 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003354 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3355 NNS->getAsIdentifier());
3356
3357 case NestedNameSpecifier::Namespace:
3358 // A namespace is canonical; build a nested-name-specifier with
3359 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003360 return NestedNameSpecifier::Create(*this, 0,
3361 NNS->getAsNamespace()->getOriginalNamespace());
3362
3363 case NestedNameSpecifier::NamespaceAlias:
3364 // A namespace is canonical; build a nested-name-specifier with
3365 // this namespace and no prefix.
3366 return NestedNameSpecifier::Create(*this, 0,
3367 NNS->getAsNamespaceAlias()->getNamespace()
3368 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003369
3370 case NestedNameSpecifier::TypeSpec:
3371 case NestedNameSpecifier::TypeSpecWithTemplate: {
3372 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003373
3374 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3375 // break it apart into its prefix and identifier, then reconsititute those
3376 // as the canonical nested-name-specifier. This is required to canonicalize
3377 // a dependent nested-name-specifier involving typedefs of dependent-name
3378 // types, e.g.,
3379 // typedef typename T::type T1;
3380 // typedef typename T1::type T2;
3381 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3382 NestedNameSpecifier *Prefix
3383 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3384 return NestedNameSpecifier::Create(*this, Prefix,
3385 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3386 }
3387
Douglas Gregor643f8432010-11-04 00:14:23 +00003388 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor264bf662010-11-04 00:09:33 +00003389 if (const DependentTemplateSpecializationType *DTST
3390 = T->getAs<DependentTemplateSpecializationType>()) {
3391 NestedNameSpecifier *Prefix
3392 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003393
3394 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3395 Prefix, DTST->getIdentifier(),
3396 DTST->getNumArgs(),
3397 DTST->getArgs());
Douglas Gregor264bf662010-11-04 00:09:33 +00003398 T = getCanonicalType(T);
3399 }
3400
John McCall3b657512011-01-19 10:06:00 +00003401 return NestedNameSpecifier::Create(*this, 0, false,
3402 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003403 }
3404
3405 case NestedNameSpecifier::Global:
3406 // The global specifier is canonical and unique.
3407 return NNS;
3408 }
3409
3410 // Required to silence a GCC warning
3411 return 0;
3412}
3413
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003414
Jay Foad4ba2a172011-01-12 09:06:06 +00003415const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003416 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003417 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003418 // Handle the common positive case fast.
3419 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3420 return AT;
3421 }
Mike Stump1eb44332009-09-09 15:08:12 +00003422
John McCall0953e762009-09-24 19:53:00 +00003423 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003424 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003425 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003426
John McCall0953e762009-09-24 19:53:00 +00003427 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003428 // implements C99 6.7.3p8: "If the specification of an array type includes
3429 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003430
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003431 // If we get here, we either have type qualifiers on the type, or we have
3432 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003433 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003434
John McCall3b657512011-01-19 10:06:00 +00003435 SplitQualType split = T.getSplitDesugaredType();
3436 Qualifiers qs = split.second;
Mike Stump1eb44332009-09-09 15:08:12 +00003437
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003438 // If we have a simple case, just return now.
John McCall3b657512011-01-19 10:06:00 +00003439 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3440 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003441 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003442
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003443 // Otherwise, we have an array and we have qualifiers on it. Push the
3444 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003445 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003446
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003447 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3448 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3449 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003450 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003451 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3452 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3453 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003454 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003455
Mike Stump1eb44332009-09-09 15:08:12 +00003456 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003457 = dyn_cast<DependentSizedArrayType>(ATy))
3458 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003459 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003460 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003461 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003462 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003463 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003464
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003465 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003466 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003467 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003468 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003469 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003470 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003471}
3472
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003473QualType ASTContext::getAdjustedParameterType(QualType T) {
3474 // C99 6.7.5.3p7:
3475 // A declaration of a parameter as "array of type" shall be
3476 // adjusted to "qualified pointer to type", where the type
3477 // qualifiers (if any) are those specified within the [ and ] of
3478 // the array type derivation.
3479 if (T->isArrayType())
3480 return getArrayDecayedType(T);
3481
3482 // C99 6.7.5.3p8:
3483 // A declaration of a parameter as "function returning type"
3484 // shall be adjusted to "pointer to function returning type", as
3485 // in 6.3.2.1.
3486 if (T->isFunctionType())
3487 return getPointerType(T);
3488
3489 return T;
3490}
3491
3492QualType ASTContext::getSignatureParameterType(QualType T) {
3493 T = getVariableArrayDecayedType(T);
3494 T = getAdjustedParameterType(T);
3495 return T.getUnqualifiedType();
3496}
3497
Chris Lattnere6327742008-04-02 05:18:44 +00003498/// getArrayDecayedType - Return the properly qualified result of decaying the
3499/// specified array type to a pointer. This operation is non-trivial when
3500/// handling typedefs etc. The canonical type of "T" must be an array type,
3501/// this returns a pointer to a properly qualified element of the array.
3502///
3503/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003504QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003505 // Get the element type with 'getAsArrayType' so that we don't lose any
3506 // typedefs in the element type of the array. This also handles propagation
3507 // of type qualifiers from the array type into the element type if present
3508 // (C99 6.7.3p8).
3509 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3510 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003511
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003512 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003513
3514 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003515 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003516}
3517
John McCall3b657512011-01-19 10:06:00 +00003518QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3519 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003520}
3521
John McCall3b657512011-01-19 10:06:00 +00003522QualType ASTContext::getBaseElementType(QualType type) const {
3523 Qualifiers qs;
3524 while (true) {
3525 SplitQualType split = type.getSplitDesugaredType();
3526 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3527 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003528
John McCall3b657512011-01-19 10:06:00 +00003529 type = array->getElementType();
3530 qs.addConsistentQualifiers(split.second);
3531 }
Mike Stump1eb44332009-09-09 15:08:12 +00003532
John McCall3b657512011-01-19 10:06:00 +00003533 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003534}
3535
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003536/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003537uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003538ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3539 uint64_t ElementCount = 1;
3540 do {
3541 ElementCount *= CA->getSize().getZExtValue();
3542 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3543 } while (CA);
3544 return ElementCount;
3545}
3546
Reid Spencer5f016e22007-07-11 17:01:13 +00003547/// getFloatingRank - Return a relative rank for floating point types.
3548/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003549static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003550 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003551 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003552
John McCall183700f2009-09-21 23:43:11 +00003553 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3554 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003555 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00003556 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00003557 case BuiltinType::Float: return FloatRank;
3558 case BuiltinType::Double: return DoubleRank;
3559 case BuiltinType::LongDouble: return LongDoubleRank;
3560 }
3561}
3562
Mike Stump1eb44332009-09-09 15:08:12 +00003563/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3564/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003565/// 'typeDomain' is a real floating point or complex type.
3566/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003567QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3568 QualType Domain) const {
3569 FloatingRank EltRank = getFloatingRank(Size);
3570 if (Domain->isComplexType()) {
3571 switch (EltRank) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003572 default: llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00003573 case FloatRank: return FloatComplexTy;
3574 case DoubleRank: return DoubleComplexTy;
3575 case LongDoubleRank: return LongDoubleComplexTy;
3576 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003577 }
Chris Lattner1361b112008-04-06 23:58:54 +00003578
3579 assert(Domain->isRealFloatingType() && "Unknown domain!");
3580 switch (EltRank) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003581 default: llvm_unreachable("getFloatingRank(): illegal value for rank");
Chris Lattner1361b112008-04-06 23:58:54 +00003582 case FloatRank: return FloatTy;
3583 case DoubleRank: return DoubleTy;
3584 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003585 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003586}
3587
Chris Lattner7cfeb082008-04-06 23:55:33 +00003588/// getFloatingTypeOrder - Compare the rank of the two specified floating
3589/// point types, ignoring the domain of the type (i.e. 'double' ==
3590/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003591/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003592int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003593 FloatingRank LHSR = getFloatingRank(LHS);
3594 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003595
Chris Lattnera75cea32008-04-06 23:38:49 +00003596 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003597 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003598 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003599 return 1;
3600 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003601}
3602
Chris Lattnerf52ab252008-04-06 22:59:24 +00003603/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3604/// routine will assert if passed a built-in type that isn't an integer or enum,
3605/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003606unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003607 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003608
Chris Lattnerf52ab252008-04-06 22:59:24 +00003609 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003610 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00003611 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003612 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003613 case BuiltinType::Char_S:
3614 case BuiltinType::Char_U:
3615 case BuiltinType::SChar:
3616 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003617 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003618 case BuiltinType::Short:
3619 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003620 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003621 case BuiltinType::Int:
3622 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003623 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003624 case BuiltinType::Long:
3625 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003626 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003627 case BuiltinType::LongLong:
3628 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003629 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003630 case BuiltinType::Int128:
3631 case BuiltinType::UInt128:
3632 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003633 }
3634}
3635
Eli Friedman04e83572009-08-20 04:21:42 +00003636/// \brief Whether this is a promotable bitfield reference according
3637/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3638///
3639/// \returns the type this bit-field will promote to, or NULL if no
3640/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00003641QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003642 if (E->isTypeDependent() || E->isValueDependent())
3643 return QualType();
3644
Eli Friedman04e83572009-08-20 04:21:42 +00003645 FieldDecl *Field = E->getBitField();
3646 if (!Field)
3647 return QualType();
3648
3649 QualType FT = Field->getType();
3650
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003651 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00003652 uint64_t IntSize = getTypeSize(IntTy);
3653 // GCC extension compatibility: if the bit-field size is less than or equal
3654 // to the size of int, it gets promoted no matter what its type is.
3655 // For instance, unsigned long bf : 4 gets promoted to signed int.
3656 if (BitWidth < IntSize)
3657 return IntTy;
3658
3659 if (BitWidth == IntSize)
3660 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3661
3662 // Types bigger than int are not subject to promotions, and therefore act
3663 // like the base type.
3664 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3665 // is ridiculous.
3666 return QualType();
3667}
3668
Eli Friedmana95d7572009-08-19 07:44:53 +00003669/// getPromotedIntegerType - Returns the type that Promotable will
3670/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3671/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003672QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003673 assert(!Promotable.isNull());
3674 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003675 if (const EnumType *ET = Promotable->getAs<EnumType>())
3676 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00003677
3678 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3679 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3680 // (3.9.1) can be converted to a prvalue of the first of the following
3681 // types that can represent all the values of its underlying type:
3682 // int, unsigned int, long int, unsigned long int, long long int, or
3683 // unsigned long long int [...]
3684 // FIXME: Is there some better way to compute this?
3685 if (BT->getKind() == BuiltinType::WChar_S ||
3686 BT->getKind() == BuiltinType::WChar_U ||
3687 BT->getKind() == BuiltinType::Char16 ||
3688 BT->getKind() == BuiltinType::Char32) {
3689 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3690 uint64_t FromSize = getTypeSize(BT);
3691 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3692 LongLongTy, UnsignedLongLongTy };
3693 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3694 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3695 if (FromSize < ToSize ||
3696 (FromSize == ToSize &&
3697 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3698 return PromoteTypes[Idx];
3699 }
3700 llvm_unreachable("char type should fit into long long");
3701 }
3702 }
3703
3704 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00003705 if (Promotable->isSignedIntegerType())
3706 return IntTy;
3707 uint64_t PromotableSize = getTypeSize(Promotable);
3708 uint64_t IntSize = getTypeSize(IntTy);
3709 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3710 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3711}
3712
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003713/// \brief Recurses in pointer/array types until it finds an objc retainable
3714/// type and returns its ownership.
3715Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3716 while (!T.isNull()) {
3717 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3718 return T.getObjCLifetime();
3719 if (T->isArrayType())
3720 T = getBaseElementType(T);
3721 else if (const PointerType *PT = T->getAs<PointerType>())
3722 T = PT->getPointeeType();
3723 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00003724 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003725 else
3726 break;
3727 }
3728
3729 return Qualifiers::OCL_None;
3730}
3731
Mike Stump1eb44332009-09-09 15:08:12 +00003732/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003733/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003734/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003735int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00003736 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3737 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003738 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003739
Chris Lattnerf52ab252008-04-06 22:59:24 +00003740 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3741 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003742
Chris Lattner7cfeb082008-04-06 23:55:33 +00003743 unsigned LHSRank = getIntegerRank(LHSC);
3744 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003745
Chris Lattner7cfeb082008-04-06 23:55:33 +00003746 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3747 if (LHSRank == RHSRank) return 0;
3748 return LHSRank > RHSRank ? 1 : -1;
3749 }
Mike Stump1eb44332009-09-09 15:08:12 +00003750
Chris Lattner7cfeb082008-04-06 23:55:33 +00003751 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3752 if (LHSUnsigned) {
3753 // If the unsigned [LHS] type is larger, return it.
3754 if (LHSRank >= RHSRank)
3755 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003756
Chris Lattner7cfeb082008-04-06 23:55:33 +00003757 // If the signed type can represent all values of the unsigned type, it
3758 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003759 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003760 return -1;
3761 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003762
Chris Lattner7cfeb082008-04-06 23:55:33 +00003763 // If the unsigned [RHS] type is larger, return it.
3764 if (RHSRank >= LHSRank)
3765 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003766
Chris Lattner7cfeb082008-04-06 23:55:33 +00003767 // If the signed type can represent all values of the unsigned type, it
3768 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003769 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003770 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003771}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003772
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003773static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003774CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3775 DeclContext *DC, IdentifierInfo *Id) {
3776 SourceLocation Loc;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003777 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003778 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003779 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003780 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003781}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003782
Mike Stump1eb44332009-09-09 15:08:12 +00003783// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003784QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003785 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003786 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003787 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003788 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003789 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003790
Anders Carlssonf06273f2007-11-19 00:25:30 +00003791 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003792
Anders Carlsson71993dd2007-08-17 05:31:46 +00003793 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003794 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003795 // int flags;
3796 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003797 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003798 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003799 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003800 FieldTypes[3] = LongTy;
3801
Anders Carlsson71993dd2007-08-17 05:31:46 +00003802 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003803 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003804 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003805 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00003806 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003807 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003808 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003809 /*Mutable=*/false,
3810 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003811 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003812 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003813 }
3814
Douglas Gregor838db382010-02-11 01:19:42 +00003815 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003816 }
Mike Stump1eb44332009-09-09 15:08:12 +00003817
Anders Carlsson71993dd2007-08-17 05:31:46 +00003818 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003819}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003820
Douglas Gregor319ac892009-04-23 22:29:11 +00003821void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003822 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003823 assert(Rec && "Invalid CFConstantStringType");
3824 CFConstantStringTypeDecl = Rec->getDecl();
3825}
3826
Jay Foad4ba2a172011-01-12 09:06:06 +00003827QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00003828 if (BlockDescriptorType)
3829 return getTagDeclType(BlockDescriptorType);
3830
3831 RecordDecl *T;
3832 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003833 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003834 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003835 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003836
3837 QualType FieldTypes[] = {
3838 UnsignedLongTy,
3839 UnsignedLongTy,
3840 };
3841
3842 const char *FieldNames[] = {
3843 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003844 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003845 };
3846
3847 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003848 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003849 SourceLocation(),
3850 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003851 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003852 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003853 /*Mutable=*/false,
3854 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003855 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003856 T->addDecl(Field);
3857 }
3858
Douglas Gregor838db382010-02-11 01:19:42 +00003859 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003860
3861 BlockDescriptorType = T;
3862
3863 return getTagDeclType(BlockDescriptorType);
3864}
3865
Jay Foad4ba2a172011-01-12 09:06:06 +00003866QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00003867 if (BlockDescriptorExtendedType)
3868 return getTagDeclType(BlockDescriptorExtendedType);
3869
3870 RecordDecl *T;
3871 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003872 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003873 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003874 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003875
3876 QualType FieldTypes[] = {
3877 UnsignedLongTy,
3878 UnsignedLongTy,
3879 getPointerType(VoidPtrTy),
3880 getPointerType(VoidPtrTy)
3881 };
3882
3883 const char *FieldNames[] = {
3884 "reserved",
3885 "Size",
3886 "CopyFuncPtr",
3887 "DestroyFuncPtr"
3888 };
3889
3890 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003891 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00003892 SourceLocation(),
3893 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003894 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003895 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003896 /*Mutable=*/false,
3897 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003898 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003899 T->addDecl(Field);
3900 }
3901
Douglas Gregor838db382010-02-11 01:19:42 +00003902 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003903
3904 BlockDescriptorExtendedType = T;
3905
3906 return getTagDeclType(BlockDescriptorExtendedType);
3907}
3908
Jay Foad4ba2a172011-01-12 09:06:06 +00003909bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCallf85e1932011-06-15 23:02:42 +00003910 if (Ty->isObjCRetainableType())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003911 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003912 if (getLangOptions().CPlusPlus) {
3913 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3914 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Huntffe37fd2011-05-25 20:50:04 +00003915 return RD->hasConstCopyConstructor();
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003916
3917 }
3918 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003919 return false;
3920}
3921
Jay Foad4ba2a172011-01-12 09:06:06 +00003922QualType
Chris Lattner5f9e2722011-07-23 10:55:15 +00003923ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003924 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003925 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003926 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003927 // unsigned int __flags;
3928 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003929 // void *__copy_helper; // as needed
3930 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003931 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003932 // } *
3933
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003934 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3935
3936 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003937 llvm::SmallString<36> Name;
3938 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3939 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003940 RecordDecl *T;
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003941 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003942 T->startDefinition();
3943 QualType Int32Ty = IntTy;
3944 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3945 QualType FieldTypes[] = {
3946 getPointerType(VoidPtrTy),
3947 getPointerType(getTagDeclType(T)),
3948 Int32Ty,
3949 Int32Ty,
3950 getPointerType(VoidPtrTy),
3951 getPointerType(VoidPtrTy),
3952 Ty
3953 };
3954
Chris Lattner5f9e2722011-07-23 10:55:15 +00003955 StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003956 "__isa",
3957 "__forwarding",
3958 "__flags",
3959 "__size",
3960 "__copy_helper",
3961 "__destroy_helper",
3962 DeclName,
3963 };
3964
3965 for (size_t i = 0; i < 7; ++i) {
3966 if (!HasCopyAndDispose && i >=4 && i <= 5)
3967 continue;
3968 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003969 SourceLocation(),
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003970 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003971 FieldTypes[i], /*TInfo=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003972 /*BitWidth=*/0, /*Mutable=*/false,
3973 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003974 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003975 T->addDecl(Field);
3976 }
3977
Douglas Gregor838db382010-02-11 01:19:42 +00003978 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003979
3980 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003981}
3982
Douglas Gregore97179c2011-09-08 01:46:34 +00003983TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
3984 if (!ObjCInstanceTypeDecl)
3985 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
3986 getTranslationUnitDecl(),
3987 SourceLocation(),
3988 SourceLocation(),
3989 &Idents.get("instancetype"),
3990 getTrivialTypeSourceInfo(getObjCIdType()));
3991 return ObjCInstanceTypeDecl;
3992}
3993
Anders Carlssone8c49532007-10-29 06:33:42 +00003994// This returns true if a type has been typedefed to BOOL:
3995// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003996static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003997 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003998 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3999 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004000
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004001 return false;
4002}
4003
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004004/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004005/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004006CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004007 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4008 return CharUnits::Zero();
4009
Ken Dyck199c3d62010-01-11 17:06:35 +00004010 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004011
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004012 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004013 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004014 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004015 // Treat arrays as pointers, since that's how they're passed in.
4016 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004017 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004018 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004019}
4020
4021static inline
4022std::string charUnitsToString(const CharUnits &CU) {
4023 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004024}
4025
John McCall6b5a61b2011-02-07 10:33:21 +00004026/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004027/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004028std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4029 std::string S;
4030
David Chisnall5e530af2009-11-17 19:33:30 +00004031 const BlockDecl *Decl = Expr->getBlockDecl();
4032 QualType BlockTy =
4033 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4034 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00004035 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00004036 // Compute size of all parameters.
4037 // Start with computing size of a pointer in number of bytes.
4038 // FIXME: There might(should) be a better way of doing this computation!
4039 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004040 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4041 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004042 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004043 E = Decl->param_end(); PI != E; ++PI) {
4044 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004045 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00004046 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004047 ParmOffset += sz;
4048 }
4049 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004050 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004051 // Block pointer and offset.
4052 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004053
4054 // Argument types.
4055 ParmOffset = PtrSize;
4056 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4057 Decl->param_end(); PI != E; ++PI) {
4058 ParmVarDecl *PVDecl = *PI;
4059 QualType PType = PVDecl->getOriginalType();
4060 if (const ArrayType *AT =
4061 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4062 // Use array's original type only if it has known number of
4063 // elements.
4064 if (!isa<ConstantArrayType>(AT))
4065 PType = PVDecl->getType();
4066 } else if (PType->isFunctionType())
4067 PType = PVDecl->getType();
4068 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004069 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004070 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004071 }
John McCall6b5a61b2011-02-07 10:33:21 +00004072
4073 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004074}
4075
Douglas Gregorf968d832011-05-27 01:19:52 +00004076bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004077 std::string& S) {
4078 // Encode result type.
4079 getObjCEncodingForType(Decl->getResultType(), S);
4080 CharUnits ParmOffset;
4081 // Compute size of all parameters.
4082 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4083 E = Decl->param_end(); PI != E; ++PI) {
4084 QualType PType = (*PI)->getType();
4085 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004086 if (sz.isZero())
4087 return true;
4088
David Chisnall5389f482010-12-30 14:05:53 +00004089 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004090 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004091 ParmOffset += sz;
4092 }
4093 S += charUnitsToString(ParmOffset);
4094 ParmOffset = CharUnits::Zero();
4095
4096 // Argument types.
4097 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4098 E = Decl->param_end(); PI != E; ++PI) {
4099 ParmVarDecl *PVDecl = *PI;
4100 QualType PType = PVDecl->getOriginalType();
4101 if (const ArrayType *AT =
4102 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4103 // Use array's original type only if it has known number of
4104 // elements.
4105 if (!isa<ConstantArrayType>(AT))
4106 PType = PVDecl->getType();
4107 } else if (PType->isFunctionType())
4108 PType = PVDecl->getType();
4109 getObjCEncodingForType(PType, S);
4110 S += charUnitsToString(ParmOffset);
4111 ParmOffset += getObjCEncodingTypeSize(PType);
4112 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004113
4114 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004115}
4116
Bob Wilsondc8dab62011-11-30 01:57:58 +00004117/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4118/// method parameter or return type. If Extended, include class names and
4119/// block object types.
4120void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4121 QualType T, std::string& S,
4122 bool Extended) const {
4123 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4124 getObjCEncodingForTypeQualifier(QT, S);
4125 // Encode parameter type.
4126 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4127 true /*OutermostType*/,
4128 false /*EncodingProperty*/,
4129 false /*StructField*/,
4130 Extended /*EncodeBlockParameters*/,
4131 Extended /*EncodeClassNames*/);
4132}
4133
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004134/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004135/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004136bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004137 std::string& S,
4138 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004139 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004140 // Encode return type.
4141 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4142 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004143 // Compute size of all parameters.
4144 // Start with computing size of a pointer in number of bytes.
4145 // FIXME: There might(should) be a better way of doing this computation!
4146 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004147 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004148 // The first two arguments (self and _cmd) are pointers; account for
4149 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004150 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004151 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004152 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004153 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004154 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004155 if (sz.isZero())
4156 return true;
4157
Ken Dyck199c3d62010-01-11 17:06:35 +00004158 assert (sz.isPositive() &&
4159 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004160 ParmOffset += sz;
4161 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004162 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004163 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004164 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004165
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004166 // Argument types.
4167 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004168 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004169 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004170 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004171 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004172 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004173 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4174 // Use array's original type only if it has known number of
4175 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004176 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004177 PType = PVDecl->getType();
4178 } else if (PType->isFunctionType())
4179 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004180 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4181 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004182 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004183 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004184 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004185
4186 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004187}
4188
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004189/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004190/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004191/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4192/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004193/// Property attributes are stored as a comma-delimited C string. The simple
4194/// attributes readonly and bycopy are encoded as single characters. The
4195/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4196/// encoded as single characters, followed by an identifier. Property types
4197/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004198/// these attributes are defined by the following enumeration:
4199/// @code
4200/// enum PropertyAttributes {
4201/// kPropertyReadOnly = 'R', // property is read-only.
4202/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4203/// kPropertyByref = '&', // property is a reference to the value last assigned
4204/// kPropertyDynamic = 'D', // property is dynamic
4205/// kPropertyGetter = 'G', // followed by getter selector name
4206/// kPropertySetter = 'S', // followed by setter selector name
4207/// kPropertyInstanceVariable = 'V' // followed by instance variable name
4208/// kPropertyType = 't' // followed by old-style type encoding.
4209/// kPropertyWeak = 'W' // 'weak' property
4210/// kPropertyStrong = 'P' // property GC'able
4211/// kPropertyNonAtomic = 'N' // property non-atomic
4212/// };
4213/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004214void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004215 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004216 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004217 // Collect information from the property implementation decl(s).
4218 bool Dynamic = false;
4219 ObjCPropertyImplDecl *SynthesizePID = 0;
4220
4221 // FIXME: Duplicated code due to poor abstraction.
4222 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004223 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004224 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4225 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004226 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004227 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004228 ObjCPropertyImplDecl *PID = *i;
4229 if (PID->getPropertyDecl() == PD) {
4230 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4231 Dynamic = true;
4232 } else {
4233 SynthesizePID = PID;
4234 }
4235 }
4236 }
4237 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004238 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004239 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004240 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004241 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004242 ObjCPropertyImplDecl *PID = *i;
4243 if (PID->getPropertyDecl() == PD) {
4244 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4245 Dynamic = true;
4246 } else {
4247 SynthesizePID = PID;
4248 }
4249 }
Mike Stump1eb44332009-09-09 15:08:12 +00004250 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004251 }
4252 }
4253
4254 // FIXME: This is not very efficient.
4255 S = "T";
4256
4257 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004258 // GCC has some special rules regarding encoding of properties which
4259 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004260 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004261 true /* outermost type */,
4262 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004263
4264 if (PD->isReadOnly()) {
4265 S += ",R";
4266 } else {
4267 switch (PD->getSetterKind()) {
4268 case ObjCPropertyDecl::Assign: break;
4269 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004270 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004271 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004272 }
4273 }
4274
4275 // It really isn't clear at all what this means, since properties
4276 // are "dynamic by default".
4277 if (Dynamic)
4278 S += ",D";
4279
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004280 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4281 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004282
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004283 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4284 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004285 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004286 }
4287
4288 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4289 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004290 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004291 }
4292
4293 if (SynthesizePID) {
4294 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4295 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004296 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004297 }
4298
4299 // FIXME: OBJCGC: weak & strong
4300}
4301
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004302/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004303/// Another legacy compatibility encoding: 32-bit longs are encoded as
4304/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004305/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4306///
4307void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004308 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004309 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004310 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004311 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004312 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004313 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004314 PointeeTy = IntTy;
4315 }
4316 }
4317}
4318
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004319void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004320 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004321 // We follow the behavior of gcc, expanding structures which are
4322 // directly pointed to, and expanding embedded structures. Note that
4323 // these rules are sufficient to prevent recursive encoding of the
4324 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004325 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004326 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004327}
4328
David Chisnall64fd7e82010-06-04 01:10:52 +00004329static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4330 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004331 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnall64fd7e82010-06-04 01:10:52 +00004332 case BuiltinType::Void: return 'v';
4333 case BuiltinType::Bool: return 'B';
4334 case BuiltinType::Char_U:
4335 case BuiltinType::UChar: return 'C';
4336 case BuiltinType::UShort: return 'S';
4337 case BuiltinType::UInt: return 'I';
4338 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00004339 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004340 case BuiltinType::UInt128: return 'T';
4341 case BuiltinType::ULongLong: return 'Q';
4342 case BuiltinType::Char_S:
4343 case BuiltinType::SChar: return 'c';
4344 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004345 case BuiltinType::WChar_S:
4346 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004347 case BuiltinType::Int: return 'i';
4348 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00004349 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004350 case BuiltinType::LongLong: return 'q';
4351 case BuiltinType::Int128: return 't';
4352 case BuiltinType::Float: return 'f';
4353 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004354 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004355 }
4356}
4357
Douglas Gregor5471bc82011-09-08 17:18:35 +00004358static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4359 EnumDecl *Enum = ET->getDecl();
4360
4361 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4362 if (!Enum->isFixed())
4363 return 'i';
4364
4365 // The encoding of a fixed enum type matches its fixed underlying type.
4366 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4367}
4368
Jay Foad4ba2a172011-01-12 09:06:06 +00004369static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004370 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004371 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004372 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004373 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4374 // The GNU runtime requires more information; bitfields are encoded as b,
4375 // then the offset (in bits) of the first element, then the type of the
4376 // bitfield, then the size in bits. For example, in this structure:
4377 //
4378 // struct
4379 // {
4380 // int integer;
4381 // int flags:2;
4382 // };
4383 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4384 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4385 // information is not especially sensible, but we're stuck with it for
4386 // compatibility with GCC, although providing it breaks anything that
4387 // actually uses runtime introspection and wants to work on both runtimes...
4388 if (!Ctx->getLangOptions().NeXTRuntime) {
4389 const RecordDecl *RD = FD->getParent();
4390 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004391 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00004392 if (const EnumType *ET = T->getAs<EnumType>())
4393 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnallc7ff82c2010-12-26 20:12:30 +00004394 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004395 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004396 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004397 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004398}
4399
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004400// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004401void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4402 bool ExpandPointedToStructures,
4403 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004404 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004405 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004406 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004407 bool StructField,
4408 bool EncodeBlockParameters,
4409 bool EncodeClassNames) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004410 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004411 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004412 return EncodeBitField(this, S, T, FD);
4413 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004414 return;
4415 }
Mike Stump1eb44332009-09-09 15:08:12 +00004416
John McCall183700f2009-09-21 23:43:11 +00004417 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004418 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004419 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004420 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004421 return;
4422 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004423
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004424 // encoding for pointer or r3eference types.
4425 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004426 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004427 if (PT->isObjCSelType()) {
4428 S += ':';
4429 return;
4430 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004431 PointeeTy = PT->getPointeeType();
4432 }
4433 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4434 PointeeTy = RT->getPointeeType();
4435 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004436 bool isReadOnly = false;
4437 // For historical/compatibility reasons, the read-only qualifier of the
4438 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4439 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004440 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004441 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004442 if (OutermostType && T.isConstQualified()) {
4443 isReadOnly = true;
4444 S += 'r';
4445 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004446 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004447 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004448 while (P->getAs<PointerType>())
4449 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004450 if (P.isConstQualified()) {
4451 isReadOnly = true;
4452 S += 'r';
4453 }
4454 }
4455 if (isReadOnly) {
4456 // Another legacy compatibility encoding. Some ObjC qualifier and type
4457 // combinations need to be rearranged.
4458 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00004459 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00004460 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004461 }
Mike Stump1eb44332009-09-09 15:08:12 +00004462
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004463 if (PointeeTy->isCharType()) {
4464 // char pointer types should be encoded as '*' unless it is a
4465 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004466 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004467 S += '*';
4468 return;
4469 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004470 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004471 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4472 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4473 S += '#';
4474 return;
4475 }
4476 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4477 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4478 S += '@';
4479 return;
4480 }
4481 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004482 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004483 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004484 getLegacyIntegralTypeEncoding(PointeeTy);
4485
Mike Stump1eb44332009-09-09 15:08:12 +00004486 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004487 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004488 return;
4489 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004490
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004491 if (const ArrayType *AT =
4492 // Ignore type qualifiers etc.
4493 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004494 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004495 // Incomplete arrays are encoded as a pointer to the array element.
4496 S += '^';
4497
Mike Stump1eb44332009-09-09 15:08:12 +00004498 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004499 false, ExpandStructures, FD);
4500 } else {
4501 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004502
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004503 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4504 if (getTypeSize(CAT->getElementType()) == 0)
4505 S += '0';
4506 else
4507 S += llvm::utostr(CAT->getSize().getZExtValue());
4508 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00004509 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004510 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4511 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00004512 S += '0';
4513 }
Mike Stump1eb44332009-09-09 15:08:12 +00004514
4515 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004516 false, ExpandStructures, FD);
4517 S += ']';
4518 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004519 return;
4520 }
Mike Stump1eb44332009-09-09 15:08:12 +00004521
John McCall183700f2009-09-21 23:43:11 +00004522 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004523 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004524 return;
4525 }
Mike Stump1eb44332009-09-09 15:08:12 +00004526
Ted Kremenek6217b802009-07-29 21:53:49 +00004527 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004528 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004529 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004530 // Anonymous structures print as '?'
4531 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4532 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004533 if (ClassTemplateSpecializationDecl *Spec
4534 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4535 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4536 std::string TemplateArgsStr
4537 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004538 TemplateArgs.data(),
4539 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00004540 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004541
4542 S += TemplateArgsStr;
4543 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004544 } else {
4545 S += '?';
4546 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004547 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004548 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004549 if (!RDecl->isUnion()) {
4550 getObjCEncodingForStructureImpl(RDecl, S, FD);
4551 } else {
4552 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4553 FieldEnd = RDecl->field_end();
4554 Field != FieldEnd; ++Field) {
4555 if (FD) {
4556 S += '"';
4557 S += Field->getNameAsString();
4558 S += '"';
4559 }
Mike Stump1eb44332009-09-09 15:08:12 +00004560
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004561 // Special case bit-fields.
4562 if (Field->isBitField()) {
4563 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4564 (*Field));
4565 } else {
4566 QualType qt = Field->getType();
4567 getLegacyIntegralTypeEncoding(qt);
4568 getObjCEncodingForTypeImpl(qt, S, false, true,
4569 FD, /*OutermostType*/false,
4570 /*EncodingProperty*/false,
4571 /*StructField*/true);
4572 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004573 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004574 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004575 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004576 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004577 return;
4578 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004579
Douglas Gregor5471bc82011-09-08 17:18:35 +00004580 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004581 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004582 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004583 else
Douglas Gregor5471bc82011-09-08 17:18:35 +00004584 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004585 return;
4586 }
Mike Stump1eb44332009-09-09 15:08:12 +00004587
Bob Wilsondc8dab62011-11-30 01:57:58 +00004588 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004589 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00004590 if (EncodeBlockParameters) {
4591 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4592
4593 S += '<';
4594 // Block return type
4595 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4596 ExpandPointedToStructures, ExpandStructures,
4597 FD,
4598 false /* OutermostType */,
4599 EncodingProperty,
4600 false /* StructField */,
4601 EncodeBlockParameters,
4602 EncodeClassNames);
4603 // Block self
4604 S += "@?";
4605 // Block parameters
4606 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4607 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4608 E = FPT->arg_type_end(); I && (I != E); ++I) {
4609 getObjCEncodingForTypeImpl(*I, S,
4610 ExpandPointedToStructures,
4611 ExpandStructures,
4612 FD,
4613 false /* OutermostType */,
4614 EncodingProperty,
4615 false /* StructField */,
4616 EncodeBlockParameters,
4617 EncodeClassNames);
4618 }
4619 }
4620 S += '>';
4621 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004622 return;
4623 }
Mike Stump1eb44332009-09-09 15:08:12 +00004624
John McCallc12c5bb2010-05-15 11:32:37 +00004625 // Ignore protocol qualifiers when mangling at this level.
4626 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4627 T = OT->getBaseType();
4628
John McCall0953e762009-09-24 19:53:00 +00004629 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004630 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004631 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004632 S += '{';
4633 const IdentifierInfo *II = OI->getIdentifier();
4634 S += II->getName();
4635 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00004636 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004637 DeepCollectObjCIvars(OI, true, Ivars);
4638 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00004639 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004640 if (Field->isBitField())
4641 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004642 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004643 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004644 }
4645 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004646 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004647 }
Mike Stump1eb44332009-09-09 15:08:12 +00004648
John McCall183700f2009-09-21 23:43:11 +00004649 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004650 if (OPT->isObjCIdType()) {
4651 S += '@';
4652 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004653 }
Mike Stump1eb44332009-09-09 15:08:12 +00004654
Steve Naroff27d20a22009-10-28 22:03:49 +00004655 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4656 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4657 // Since this is a binary compatibility issue, need to consult with runtime
4658 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004659 S += '#';
4660 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004661 }
Mike Stump1eb44332009-09-09 15:08:12 +00004662
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004663 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004664 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004665 ExpandPointedToStructures,
4666 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00004667 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00004668 // Note that we do extended encoding of protocol qualifer list
4669 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004670 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004671 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4672 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004673 S += '<';
4674 S += (*I)->getNameAsString();
4675 S += '>';
4676 }
4677 S += '"';
4678 }
4679 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004680 }
Mike Stump1eb44332009-09-09 15:08:12 +00004681
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004682 QualType PointeeTy = OPT->getPointeeType();
4683 if (!EncodingProperty &&
4684 isa<TypedefType>(PointeeTy.getTypePtr())) {
4685 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004686 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004687 // {...};
4688 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004689 getObjCEncodingForTypeImpl(PointeeTy, S,
4690 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004691 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004692 return;
4693 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004694
4695 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00004696 if (OPT->getInterfaceDecl() &&
4697 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004698 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004699 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004700 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4701 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004702 S += '<';
4703 S += (*I)->getNameAsString();
4704 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004705 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004706 S += '"';
4707 }
4708 return;
4709 }
Mike Stump1eb44332009-09-09 15:08:12 +00004710
John McCall532ec7b2010-05-17 23:56:34 +00004711 // gcc just blithely ignores member pointers.
4712 // TODO: maybe there should be a mangling for these
4713 if (T->getAs<MemberPointerType>())
4714 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004715
4716 if (T->isVectorType()) {
4717 // This matches gcc's encoding, even though technically it is
4718 // insufficient.
4719 // FIXME. We should do a better job than gcc.
4720 return;
4721 }
4722
David Blaikieb219cfc2011-09-23 05:06:16 +00004723 llvm_unreachable("@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004724}
4725
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004726void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4727 std::string &S,
4728 const FieldDecl *FD,
4729 bool includeVBases) const {
4730 assert(RDecl && "Expected non-null RecordDecl");
4731 assert(!RDecl->isUnion() && "Should not be called for unions");
4732 if (!RDecl->getDefinition())
4733 return;
4734
4735 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4736 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4737 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4738
4739 if (CXXRec) {
4740 for (CXXRecordDecl::base_class_iterator
4741 BI = CXXRec->bases_begin(),
4742 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4743 if (!BI->isVirtual()) {
4744 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004745 if (base->isEmpty())
4746 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004747 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4748 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4749 std::make_pair(offs, base));
4750 }
4751 }
4752 }
4753
4754 unsigned i = 0;
4755 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4756 FieldEnd = RDecl->field_end();
4757 Field != FieldEnd; ++Field, ++i) {
4758 uint64_t offs = layout.getFieldOffset(i);
4759 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4760 std::make_pair(offs, *Field));
4761 }
4762
4763 if (CXXRec && includeVBases) {
4764 for (CXXRecordDecl::base_class_iterator
4765 BI = CXXRec->vbases_begin(),
4766 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4767 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004768 if (base->isEmpty())
4769 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004770 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00004771 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4772 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4773 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004774 }
4775 }
4776
4777 CharUnits size;
4778 if (CXXRec) {
4779 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4780 } else {
4781 size = layout.getSize();
4782 }
4783
4784 uint64_t CurOffs = 0;
4785 std::multimap<uint64_t, NamedDecl *>::iterator
4786 CurLayObj = FieldOrBaseOffsets.begin();
4787
Argyrios Kyrtzidiscb8061e2011-08-22 16:03:14 +00004788 if ((CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) ||
4789 (CurLayObj == FieldOrBaseOffsets.end() &&
4790 CXXRec && CXXRec->isDynamicClass())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004791 assert(CXXRec && CXXRec->isDynamicClass() &&
4792 "Offset 0 was empty but no VTable ?");
4793 if (FD) {
4794 S += "\"_vptr$";
4795 std::string recname = CXXRec->getNameAsString();
4796 if (recname.empty()) recname = "?";
4797 S += recname;
4798 S += '"';
4799 }
4800 S += "^^?";
4801 CurOffs += getTypeSize(VoidPtrTy);
4802 }
4803
4804 if (!RDecl->hasFlexibleArrayMember()) {
4805 // Mark the end of the structure.
4806 uint64_t offs = toBits(size);
4807 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4808 std::make_pair(offs, (NamedDecl*)0));
4809 }
4810
4811 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4812 assert(CurOffs <= CurLayObj->first);
4813
4814 if (CurOffs < CurLayObj->first) {
4815 uint64_t padding = CurLayObj->first - CurOffs;
4816 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4817 // packing/alignment of members is different that normal, in which case
4818 // the encoding will be out-of-sync with the real layout.
4819 // If the runtime switches to just consider the size of types without
4820 // taking into account alignment, we could make padding explicit in the
4821 // encoding (e.g. using arrays of chars). The encoding strings would be
4822 // longer then though.
4823 CurOffs += padding;
4824 }
4825
4826 NamedDecl *dcl = CurLayObj->second;
4827 if (dcl == 0)
4828 break; // reached end of structure.
4829
4830 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4831 // We expand the bases without their virtual bases since those are going
4832 // in the initial structure. Note that this differs from gcc which
4833 // expands virtual bases each time one is encountered in the hierarchy,
4834 // making the encoding type bigger than it really is.
4835 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004836 assert(!base->isEmpty());
4837 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004838 } else {
4839 FieldDecl *field = cast<FieldDecl>(dcl);
4840 if (FD) {
4841 S += '"';
4842 S += field->getNameAsString();
4843 S += '"';
4844 }
4845
4846 if (field->isBitField()) {
4847 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004848 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004849 } else {
4850 QualType qt = field->getType();
4851 getLegacyIntegralTypeEncoding(qt);
4852 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4853 /*OutermostType*/false,
4854 /*EncodingProperty*/false,
4855 /*StructField*/true);
4856 CurOffs += getTypeSize(field->getType());
4857 }
4858 }
4859 }
4860}
4861
Mike Stump1eb44332009-09-09 15:08:12 +00004862void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004863 std::string& S) const {
4864 if (QT & Decl::OBJC_TQ_In)
4865 S += 'n';
4866 if (QT & Decl::OBJC_TQ_Inout)
4867 S += 'N';
4868 if (QT & Decl::OBJC_TQ_Out)
4869 S += 'o';
4870 if (QT & Decl::OBJC_TQ_Bycopy)
4871 S += 'O';
4872 if (QT & Decl::OBJC_TQ_Byref)
4873 S += 'R';
4874 if (QT & Decl::OBJC_TQ_Oneway)
4875 S += 'V';
4876}
4877
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004878void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004879 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004880
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004881 BuiltinVaListType = T;
4882}
4883
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00004884TypedefDecl *ASTContext::getObjCIdDecl() const {
4885 if (!ObjCIdDecl) {
4886 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4887 T = getObjCObjectPointerType(T);
4888 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4889 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4890 getTranslationUnitDecl(),
4891 SourceLocation(), SourceLocation(),
4892 &Idents.get("id"), IdInfo);
4893 }
4894
4895 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00004896}
4897
Douglas Gregor7a27ea52011-08-12 06:17:30 +00004898TypedefDecl *ASTContext::getObjCSelDecl() const {
4899 if (!ObjCSelDecl) {
4900 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4901 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4902 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4903 getTranslationUnitDecl(),
4904 SourceLocation(), SourceLocation(),
4905 &Idents.get("SEL"), SelInfo);
4906 }
4907 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004908}
4909
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004910void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004911 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00004912}
4913
Douglas Gregor79d67262011-08-12 05:59:41 +00004914TypedefDecl *ASTContext::getObjCClassDecl() const {
4915 if (!ObjCClassDecl) {
4916 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4917 T = getObjCObjectPointerType(T);
4918 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4919 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4920 getTranslationUnitDecl(),
4921 SourceLocation(), SourceLocation(),
4922 &Idents.get("Class"), ClassInfo);
4923 }
4924
4925 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004926}
4927
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004928void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004929 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004930 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004931
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004932 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004933}
4934
John McCall0bd6feb2009-12-02 08:04:21 +00004935/// \brief Retrieve the template name that corresponds to a non-empty
4936/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00004937TemplateName
4938ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4939 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00004940 unsigned size = End - Begin;
4941 assert(size > 1 && "set is not overloaded!");
4942
4943 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4944 size * sizeof(FunctionTemplateDecl*));
4945 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4946
4947 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004948 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004949 NamedDecl *D = *I;
4950 assert(isa<FunctionTemplateDecl>(D) ||
4951 (isa<UsingShadowDecl>(D) &&
4952 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4953 *Storage++ = D;
4954 }
4955
4956 return TemplateName(OT);
4957}
4958
Douglas Gregor7532dc62009-03-30 22:58:21 +00004959/// \brief Retrieve the template name that represents a qualified
4960/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00004961TemplateName
4962ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4963 bool TemplateKeyword,
4964 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00004965 assert(NNS && "Missing nested-name-specifier in qualified template name");
4966
Douglas Gregor789b1f62010-02-04 18:10:26 +00004967 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004968 llvm::FoldingSetNodeID ID;
4969 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4970
4971 void *InsertPos = 0;
4972 QualifiedTemplateName *QTN =
4973 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4974 if (!QTN) {
4975 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4976 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4977 }
4978
4979 return TemplateName(QTN);
4980}
4981
4982/// \brief Retrieve the template name that represents a dependent
4983/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00004984TemplateName
4985ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4986 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004987 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004988 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004989
4990 llvm::FoldingSetNodeID ID;
4991 DependentTemplateName::Profile(ID, NNS, Name);
4992
4993 void *InsertPos = 0;
4994 DependentTemplateName *QTN =
4995 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4996
4997 if (QTN)
4998 return TemplateName(QTN);
4999
5000 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5001 if (CanonNNS == NNS) {
5002 QTN = new (*this,4) DependentTemplateName(NNS, Name);
5003 } else {
5004 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5005 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005006 DependentTemplateName *CheckQTN =
5007 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5008 assert(!CheckQTN && "Dependent type name canonicalization broken");
5009 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00005010 }
5011
5012 DependentTemplateNames.InsertNode(QTN, InsertPos);
5013 return TemplateName(QTN);
5014}
5015
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005016/// \brief Retrieve the template name that represents a dependent
5017/// template name such as \c MetaFun::template operator+.
5018TemplateName
5019ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00005020 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005021 assert((!NNS || NNS->isDependent()) &&
5022 "Nested name specifier must be dependent");
5023
5024 llvm::FoldingSetNodeID ID;
5025 DependentTemplateName::Profile(ID, NNS, Operator);
5026
5027 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00005028 DependentTemplateName *QTN
5029 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005030
5031 if (QTN)
5032 return TemplateName(QTN);
5033
5034 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5035 if (CanonNNS == NNS) {
5036 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5037 } else {
5038 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5039 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005040
5041 DependentTemplateName *CheckQTN
5042 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5043 assert(!CheckQTN && "Dependent template name canonicalization broken");
5044 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005045 }
5046
5047 DependentTemplateNames.InsertNode(QTN, InsertPos);
5048 return TemplateName(QTN);
5049}
5050
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005051TemplateName
John McCall14606042011-06-30 08:33:18 +00005052ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5053 TemplateName replacement) const {
5054 llvm::FoldingSetNodeID ID;
5055 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5056
5057 void *insertPos = 0;
5058 SubstTemplateTemplateParmStorage *subst
5059 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5060
5061 if (!subst) {
5062 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5063 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5064 }
5065
5066 return TemplateName(subst);
5067}
5068
5069TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005070ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5071 const TemplateArgument &ArgPack) const {
5072 ASTContext &Self = const_cast<ASTContext &>(*this);
5073 llvm::FoldingSetNodeID ID;
5074 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5075
5076 void *InsertPos = 0;
5077 SubstTemplateTemplateParmPackStorage *Subst
5078 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5079
5080 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00005081 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005082 ArgPack.pack_size(),
5083 ArgPack.pack_begin());
5084 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5085 }
5086
5087 return TemplateName(Subst);
5088}
5089
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005090/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00005091/// TargetInfo, produce the corresponding type. The unsigned @p Type
5092/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00005093CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005094 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00005095 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005096 case TargetInfo::SignedShort: return ShortTy;
5097 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5098 case TargetInfo::SignedInt: return IntTy;
5099 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5100 case TargetInfo::SignedLong: return LongTy;
5101 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5102 case TargetInfo::SignedLongLong: return LongLongTy;
5103 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5104 }
5105
David Blaikieb219cfc2011-09-23 05:06:16 +00005106 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005107}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00005108
5109//===----------------------------------------------------------------------===//
5110// Type Predicates.
5111//===----------------------------------------------------------------------===//
5112
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005113/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5114/// garbage collection attribute.
5115///
John McCallae278a32011-01-12 00:34:59 +00005116Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
Douglas Gregore289d812011-09-13 17:21:33 +00005117 if (getLangOptions().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00005118 return Qualifiers::GCNone;
5119
5120 assert(getLangOptions().ObjC1);
5121 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5122
5123 // Default behaviour under objective-C's gc is for ObjC pointers
5124 // (or pointers to them) be treated as though they were declared
5125 // as __strong.
5126 if (GCAttrs == Qualifiers::GCNone) {
5127 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5128 return Qualifiers::Strong;
5129 else if (Ty->isPointerType())
5130 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5131 } else {
5132 // It's not valid to set GC attributes on anything that isn't a
5133 // pointer.
5134#ifndef NDEBUG
5135 QualType CT = Ty->getCanonicalTypeInternal();
5136 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5137 CT = AT->getElementType();
5138 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5139#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005140 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00005141 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005142}
5143
Chris Lattner6ac46a42008-04-07 06:51:04 +00005144//===----------------------------------------------------------------------===//
5145// Type Compatibility Testing
5146//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00005147
Mike Stump1eb44332009-09-09 15:08:12 +00005148/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005149/// compatible.
5150static bool areCompatVectorTypes(const VectorType *LHS,
5151 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00005152 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00005153 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00005154 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00005155}
5156
Douglas Gregor255210e2010-08-06 10:14:59 +00005157bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5158 QualType SecondVec) {
5159 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5160 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5161
5162 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5163 return true;
5164
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005165 // Treat Neon vector types and most AltiVec vector types as if they are the
5166 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00005167 const VectorType *First = FirstVec->getAs<VectorType>();
5168 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005169 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00005170 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005171 First->getVectorKind() != VectorType::AltiVecPixel &&
5172 First->getVectorKind() != VectorType::AltiVecBool &&
5173 Second->getVectorKind() != VectorType::AltiVecPixel &&
5174 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00005175 return true;
5176
5177 return false;
5178}
5179
Steve Naroff4084c302009-07-23 01:01:38 +00005180//===----------------------------------------------------------------------===//
5181// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5182//===----------------------------------------------------------------------===//
5183
5184/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5185/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00005186bool
5187ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5188 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005189 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00005190 return true;
5191 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5192 E = rProto->protocol_end(); PI != E; ++PI)
5193 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5194 return true;
5195 return false;
5196}
5197
Steve Naroff4084c302009-07-23 01:01:38 +00005198/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5199/// return true if lhs's protocols conform to rhs's protocol; false
5200/// otherwise.
5201bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5202 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5203 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5204 return false;
5205}
5206
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005207/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5208/// Class<p1, ...>.
5209bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5210 QualType rhs) {
5211 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5212 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5213 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5214
5215 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5216 E = lhsQID->qual_end(); I != E; ++I) {
5217 bool match = false;
5218 ObjCProtocolDecl *lhsProto = *I;
5219 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5220 E = rhsOPT->qual_end(); J != E; ++J) {
5221 ObjCProtocolDecl *rhsProto = *J;
5222 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5223 match = true;
5224 break;
5225 }
5226 }
5227 if (!match)
5228 return false;
5229 }
5230 return true;
5231}
5232
Steve Naroff4084c302009-07-23 01:01:38 +00005233/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5234/// ObjCQualifiedIDType.
5235bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5236 bool compare) {
5237 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00005238 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005239 lhs->isObjCIdType() || lhs->isObjCClassType())
5240 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005241 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005242 rhs->isObjCIdType() || rhs->isObjCClassType())
5243 return true;
5244
5245 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00005246 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005247
Steve Naroff4084c302009-07-23 01:01:38 +00005248 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005249
Steve Naroff4084c302009-07-23 01:01:38 +00005250 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005251 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00005252 // make sure we check the class hierarchy.
5253 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5254 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5255 E = lhsQID->qual_end(); I != E; ++I) {
5256 // when comparing an id<P> on lhs with a static type on rhs,
5257 // see if static class implements all of id's protocols, directly or
5258 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005259 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00005260 return false;
5261 }
5262 }
5263 // If there are no qualifiers and no interface, we have an 'id'.
5264 return true;
5265 }
Mike Stump1eb44332009-09-09 15:08:12 +00005266 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005267 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5268 E = lhsQID->qual_end(); I != E; ++I) {
5269 ObjCProtocolDecl *lhsProto = *I;
5270 bool match = false;
5271
5272 // when comparing an id<P> on lhs with a static type on rhs,
5273 // see if static class implements all of id's protocols, directly or
5274 // through its super class and categories.
5275 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5276 E = rhsOPT->qual_end(); J != E; ++J) {
5277 ObjCProtocolDecl *rhsProto = *J;
5278 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5279 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5280 match = true;
5281 break;
5282 }
5283 }
Mike Stump1eb44332009-09-09 15:08:12 +00005284 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00005285 // make sure we check the class hierarchy.
5286 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5287 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5288 E = lhsQID->qual_end(); I != E; ++I) {
5289 // when comparing an id<P> on lhs with a static type on rhs,
5290 // see if static class implements all of id's protocols, directly or
5291 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005292 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00005293 match = true;
5294 break;
5295 }
5296 }
5297 }
5298 if (!match)
5299 return false;
5300 }
Mike Stump1eb44332009-09-09 15:08:12 +00005301
Steve Naroff4084c302009-07-23 01:01:38 +00005302 return true;
5303 }
Mike Stump1eb44332009-09-09 15:08:12 +00005304
Steve Naroff4084c302009-07-23 01:01:38 +00005305 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5306 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5307
Mike Stump1eb44332009-09-09 15:08:12 +00005308 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00005309 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005310 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005311 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5312 E = lhsOPT->qual_end(); I != E; ++I) {
5313 ObjCProtocolDecl *lhsProto = *I;
5314 bool match = false;
5315
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005316 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00005317 // see if static class implements all of id's protocols, directly or
5318 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005319 // First, lhs protocols in the qualifier list must be found, direct
5320 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00005321 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5322 E = rhsQID->qual_end(); J != E; ++J) {
5323 ObjCProtocolDecl *rhsProto = *J;
5324 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5325 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5326 match = true;
5327 break;
5328 }
5329 }
5330 if (!match)
5331 return false;
5332 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005333
5334 // Static class's protocols, or its super class or category protocols
5335 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5336 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5337 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5338 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5339 // This is rather dubious but matches gcc's behavior. If lhs has
5340 // no type qualifier and its class has no static protocol(s)
5341 // assume that it is mismatch.
5342 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5343 return false;
5344 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5345 LHSInheritedProtocols.begin(),
5346 E = LHSInheritedProtocols.end(); I != E; ++I) {
5347 bool match = false;
5348 ObjCProtocolDecl *lhsProto = (*I);
5349 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5350 E = rhsQID->qual_end(); J != E; ++J) {
5351 ObjCProtocolDecl *rhsProto = *J;
5352 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5353 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5354 match = true;
5355 break;
5356 }
5357 }
5358 if (!match)
5359 return false;
5360 }
5361 }
Steve Naroff4084c302009-07-23 01:01:38 +00005362 return true;
5363 }
5364 return false;
5365}
5366
Eli Friedman3d815e72008-08-22 00:56:42 +00005367/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005368/// compatible for assignment from RHS to LHS. This handles validation of any
5369/// protocol qualifiers on the LHS or RHS.
5370///
Steve Naroff14108da2009-07-10 23:34:53 +00005371bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5372 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00005373 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5374 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5375
Steve Naroffde2e22d2009-07-15 18:40:39 +00005376 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00005377 if (LHS->isObjCUnqualifiedIdOrClass() ||
5378 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00005379 return true;
5380
John McCallc12c5bb2010-05-15 11:32:37 +00005381 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00005382 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5383 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00005384 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005385
5386 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5387 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5388 QualType(RHSOPT,0));
5389
John McCallc12c5bb2010-05-15 11:32:37 +00005390 // If we have 2 user-defined types, fall into that path.
5391 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00005392 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00005393
Steve Naroff4084c302009-07-23 01:01:38 +00005394 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005395}
5396
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005397/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00005398/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005399/// arguments in block literals. When passed as arguments, passing 'A*' where
5400/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5401/// not OK. For the return type, the opposite is not OK.
5402bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5403 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005404 const ObjCObjectPointerType *RHSOPT,
5405 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005406 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005407 return true;
5408
5409 if (LHSOPT->isObjCBuiltinType()) {
5410 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5411 }
5412
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005413 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005414 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5415 QualType(RHSOPT,0),
5416 false);
5417
5418 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5419 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5420 if (LHS && RHS) { // We have 2 user-defined types.
5421 if (LHS != RHS) {
5422 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005423 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005424 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005425 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005426 }
5427 else
5428 return true;
5429 }
5430 return false;
5431}
5432
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005433/// getIntersectionOfProtocols - This routine finds the intersection of set
5434/// of protocols inherited from two distinct objective-c pointer objects.
5435/// It is used to build composite qualifier list of the composite type of
5436/// the conditional expression involving two objective-c pointer objects.
5437static
5438void getIntersectionOfProtocols(ASTContext &Context,
5439 const ObjCObjectPointerType *LHSOPT,
5440 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005441 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005442
John McCallc12c5bb2010-05-15 11:32:37 +00005443 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5444 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5445 assert(LHS->getInterface() && "LHS must have an interface base");
5446 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005447
5448 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5449 unsigned LHSNumProtocols = LHS->getNumProtocols();
5450 if (LHSNumProtocols > 0)
5451 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5452 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005453 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005454 Context.CollectInheritedProtocols(LHS->getInterface(),
5455 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005456 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5457 LHSInheritedProtocols.end());
5458 }
5459
5460 unsigned RHSNumProtocols = RHS->getNumProtocols();
5461 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00005462 ObjCProtocolDecl **RHSProtocols =
5463 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005464 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5465 if (InheritedProtocolSet.count(RHSProtocols[i]))
5466 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00005467 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005468 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005469 Context.CollectInheritedProtocols(RHS->getInterface(),
5470 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005471 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5472 RHSInheritedProtocols.begin(),
5473 E = RHSInheritedProtocols.end(); I != E; ++I)
5474 if (InheritedProtocolSet.count((*I)))
5475 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005476 }
5477}
5478
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005479/// areCommonBaseCompatible - Returns common base class of the two classes if
5480/// one found. Note that this is O'2 algorithm. But it will be called as the
5481/// last type comparison in a ?-exp of ObjC pointer types before a
5482/// warning is issued. So, its invokation is extremely rare.
5483QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00005484 const ObjCObjectPointerType *Lptr,
5485 const ObjCObjectPointerType *Rptr) {
5486 const ObjCObjectType *LHS = Lptr->getObjectType();
5487 const ObjCObjectType *RHS = Rptr->getObjectType();
5488 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5489 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00005490 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005491 return QualType();
5492
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005493 do {
John McCallc12c5bb2010-05-15 11:32:37 +00005494 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005495 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005496 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005497 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5498
5499 QualType Result = QualType(LHS, 0);
5500 if (!Protocols.empty())
5501 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5502 Result = getObjCObjectPointerType(Result);
5503 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005504 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005505 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005506
5507 return QualType();
5508}
5509
John McCallc12c5bb2010-05-15 11:32:37 +00005510bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5511 const ObjCObjectType *RHS) {
5512 assert(LHS->getInterface() && "LHS is not an interface type");
5513 assert(RHS->getInterface() && "RHS is not an interface type");
5514
Chris Lattner6ac46a42008-04-07 06:51:04 +00005515 // Verify that the base decls are compatible: the RHS must be a subclass of
5516 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00005517 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00005518 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005519
Chris Lattner6ac46a42008-04-07 06:51:04 +00005520 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5521 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00005522 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00005523 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005524
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005525 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5526 // more detailed analysis is required.
5527 if (RHS->getNumProtocols() == 0) {
5528 // OK, if LHS is a superclass of RHS *and*
5529 // this superclass is assignment compatible with LHS.
5530 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005531 bool IsSuperClass =
5532 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5533 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005534 // OK if conversion of LHS to SuperClass results in narrowing of types
5535 // ; i.e., SuperClass may implement at least one of the protocols
5536 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5537 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5538 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005539 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005540 // If super class has no protocols, it is not a match.
5541 if (SuperClassInheritedProtocols.empty())
5542 return false;
5543
5544 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5545 LHSPE = LHS->qual_end();
5546 LHSPI != LHSPE; LHSPI++) {
5547 bool SuperImplementsProtocol = false;
5548 ObjCProtocolDecl *LHSProto = (*LHSPI);
5549
5550 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5551 SuperClassInheritedProtocols.begin(),
5552 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5553 ObjCProtocolDecl *SuperClassProto = (*I);
5554 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5555 SuperImplementsProtocol = true;
5556 break;
5557 }
5558 }
5559 if (!SuperImplementsProtocol)
5560 return false;
5561 }
5562 return true;
5563 }
5564 return false;
5565 }
Mike Stump1eb44332009-09-09 15:08:12 +00005566
John McCallc12c5bb2010-05-15 11:32:37 +00005567 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5568 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005569 LHSPI != LHSPE; LHSPI++) {
5570 bool RHSImplementsProtocol = false;
5571
5572 // If the RHS doesn't implement the protocol on the left, the types
5573 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00005574 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5575 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00005576 RHSPI != RHSPE; RHSPI++) {
5577 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005578 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00005579 break;
5580 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005581 }
5582 // FIXME: For better diagnostics, consider passing back the protocol name.
5583 if (!RHSImplementsProtocol)
5584 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005585 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005586 // The RHS implements all protocols listed on the LHS.
5587 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005588}
5589
Steve Naroff389bf462009-02-12 17:52:19 +00005590bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5591 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00005592 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5593 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005594
Steve Naroff14108da2009-07-10 23:34:53 +00005595 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00005596 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005597
5598 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5599 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00005600}
5601
Douglas Gregor569c3162010-08-07 11:51:51 +00005602bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5603 return canAssignObjCInterfaces(
5604 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5605 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5606}
5607
Mike Stump1eb44332009-09-09 15:08:12 +00005608/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00005609/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00005610/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00005611/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00005612bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5613 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005614 if (getLangOptions().CPlusPlus)
5615 return hasSameType(LHS, RHS);
5616
Douglas Gregor447234d2010-07-29 15:18:02 +00005617 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00005618}
5619
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005620bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00005621 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005622}
5623
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005624bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5625 return !mergeTypes(LHS, RHS, true).isNull();
5626}
5627
Peter Collingbourne48466752010-10-24 18:30:18 +00005628/// mergeTransparentUnionType - if T is a transparent union type and a member
5629/// of T is compatible with SubType, return the merged type, else return
5630/// QualType()
5631QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5632 bool OfBlockPointer,
5633 bool Unqualified) {
5634 if (const RecordType *UT = T->getAsUnionType()) {
5635 RecordDecl *UD = UT->getDecl();
5636 if (UD->hasAttr<TransparentUnionAttr>()) {
5637 for (RecordDecl::field_iterator it = UD->field_begin(),
5638 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00005639 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005640 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5641 if (!MT.isNull())
5642 return MT;
5643 }
5644 }
5645 }
5646
5647 return QualType();
5648}
5649
5650/// mergeFunctionArgumentTypes - merge two types which appear as function
5651/// argument types
5652QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5653 bool OfBlockPointer,
5654 bool Unqualified) {
5655 // GNU extension: two types are compatible if they appear as a function
5656 // argument, one of the types is a transparent union type and the other
5657 // type is compatible with a union member
5658 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5659 Unqualified);
5660 if (!lmerge.isNull())
5661 return lmerge;
5662
5663 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5664 Unqualified);
5665 if (!rmerge.isNull())
5666 return rmerge;
5667
5668 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5669}
5670
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005671QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00005672 bool OfBlockPointer,
5673 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00005674 const FunctionType *lbase = lhs->getAs<FunctionType>();
5675 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00005676 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5677 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00005678 bool allLTypes = true;
5679 bool allRTypes = true;
5680
5681 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005682 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005683 if (OfBlockPointer) {
5684 QualType RHS = rbase->getResultType();
5685 QualType LHS = lbase->getResultType();
5686 bool UnqualifiedResult = Unqualified;
5687 if (!UnqualifiedResult)
5688 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005689 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005690 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005691 else
John McCall8cc246c2010-12-15 01:06:38 +00005692 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5693 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005694 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005695
5696 if (Unqualified)
5697 retType = retType.getUnqualifiedType();
5698
5699 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5700 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5701 if (Unqualified) {
5702 LRetType = LRetType.getUnqualifiedType();
5703 RRetType = RRetType.getUnqualifiedType();
5704 }
5705
5706 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005707 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00005708 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005709 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005710
Daniel Dunbar6a15c852010-04-28 16:20:58 +00005711 // FIXME: double check this
5712 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5713 // rbase->getRegParmAttr() != 0 &&
5714 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00005715 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5716 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00005717
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005718 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00005719 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005720 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005721
John McCall8cc246c2010-12-15 01:06:38 +00005722 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00005723 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5724 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00005725 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5726 return QualType();
5727
John McCallf85e1932011-06-15 23:02:42 +00005728 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5729 return QualType();
5730
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005731 // functypes which return are preferred over those that do not.
5732 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5733 allLTypes = false;
5734 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5735 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005736 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5737 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00005738
John McCallf85e1932011-06-15 23:02:42 +00005739 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00005740
Eli Friedman3d815e72008-08-22 00:56:42 +00005741 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00005742 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5743 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005744 unsigned lproto_nargs = lproto->getNumArgs();
5745 unsigned rproto_nargs = rproto->getNumArgs();
5746
5747 // Compatible functions must have the same number of arguments
5748 if (lproto_nargs != rproto_nargs)
5749 return QualType();
5750
5751 // Variadic and non-variadic functions aren't compatible
5752 if (lproto->isVariadic() != rproto->isVariadic())
5753 return QualType();
5754
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00005755 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5756 return QualType();
5757
Fariborz Jahanian78213e42011-09-28 21:52:05 +00005758 if (LangOpts.ObjCAutoRefCount &&
5759 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5760 return QualType();
5761
Eli Friedman3d815e72008-08-22 00:56:42 +00005762 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00005763 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00005764 for (unsigned i = 0; i < lproto_nargs; i++) {
5765 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5766 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005767 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5768 OfBlockPointer,
5769 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005770 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005771
5772 if (Unqualified)
5773 argtype = argtype.getUnqualifiedType();
5774
Eli Friedman3d815e72008-08-22 00:56:42 +00005775 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00005776 if (Unqualified) {
5777 largtype = largtype.getUnqualifiedType();
5778 rargtype = rargtype.getUnqualifiedType();
5779 }
5780
Chris Lattner61710852008-10-05 17:34:18 +00005781 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5782 allLTypes = false;
5783 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5784 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00005785 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00005786
Eli Friedman3d815e72008-08-22 00:56:42 +00005787 if (allLTypes) return lhs;
5788 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005789
5790 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5791 EPI.ExtInfo = einfo;
5792 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005793 }
5794
5795 if (lproto) allRTypes = false;
5796 if (rproto) allLTypes = false;
5797
Douglas Gregor72564e72009-02-26 23:50:07 +00005798 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00005799 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00005800 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005801 if (proto->isVariadic()) return QualType();
5802 // Check that the types are compatible with the types that
5803 // would result from default argument promotions (C99 6.7.5.3p15).
5804 // The only types actually affected are promotable integer
5805 // types and floats, which would be passed as a different
5806 // type depending on whether the prototype is visible.
5807 unsigned proto_nargs = proto->getNumArgs();
5808 for (unsigned i = 0; i < proto_nargs; ++i) {
5809 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00005810
5811 // Look at the promotion type of enum types, since that is the type used
5812 // to pass enum values.
5813 if (const EnumType *Enum = argTy->getAs<EnumType>())
5814 argTy = Enum->getDecl()->getPromotionType();
5815
Eli Friedman3d815e72008-08-22 00:56:42 +00005816 if (argTy->isPromotableIntegerType() ||
5817 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5818 return QualType();
5819 }
5820
5821 if (allLTypes) return lhs;
5822 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005823
5824 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5825 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00005826 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005827 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005828 }
5829
5830 if (allLTypes) return lhs;
5831 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00005832 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00005833}
5834
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005835QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00005836 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005837 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00005838 // C++ [expr]: If an expression initially has the type "reference to T", the
5839 // type is adjusted to "T" prior to any further analysis, the expression
5840 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005841 // expression is an lvalue unless the reference is an rvalue reference and
5842 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005843 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5844 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00005845
5846 if (Unqualified) {
5847 LHS = LHS.getUnqualifiedType();
5848 RHS = RHS.getUnqualifiedType();
5849 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005850
Eli Friedman3d815e72008-08-22 00:56:42 +00005851 QualType LHSCan = getCanonicalType(LHS),
5852 RHSCan = getCanonicalType(RHS);
5853
5854 // If two types are identical, they are compatible.
5855 if (LHSCan == RHSCan)
5856 return LHS;
5857
John McCall0953e762009-09-24 19:53:00 +00005858 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005859 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5860 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00005861 if (LQuals != RQuals) {
5862 // If any of these qualifiers are different, we have a type
5863 // mismatch.
5864 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00005865 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5866 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00005867 return QualType();
5868
5869 // Exactly one GC qualifier difference is allowed: __strong is
5870 // okay if the other type has no GC qualifier but is an Objective
5871 // C object pointer (i.e. implicitly strong by default). We fix
5872 // this by pretending that the unqualified type was actually
5873 // qualified __strong.
5874 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5875 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5876 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5877
5878 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5879 return QualType();
5880
5881 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5882 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5883 }
5884 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5885 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5886 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005887 return QualType();
John McCall0953e762009-09-24 19:53:00 +00005888 }
5889
5890 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00005891
Eli Friedman852d63b2009-06-01 01:22:52 +00005892 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5893 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00005894
Chris Lattner1adb8832008-01-14 05:45:46 +00005895 // We want to consider the two function types to be the same for these
5896 // comparisons, just force one to the other.
5897 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5898 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00005899
5900 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00005901 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5902 LHSClass = Type::ConstantArray;
5903 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5904 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00005905
John McCallc12c5bb2010-05-15 11:32:37 +00005906 // ObjCInterfaces are just specialized ObjCObjects.
5907 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5908 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5909
Nate Begeman213541a2008-04-18 23:10:10 +00005910 // Canonicalize ExtVector -> Vector.
5911 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5912 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00005913
Chris Lattnera36a61f2008-04-07 05:43:21 +00005914 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005915 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00005916 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00005917 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00005918 // Compatibility is based on the underlying type, not the promotion
5919 // type.
John McCall183700f2009-09-21 23:43:11 +00005920 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005921 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5922 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005923 }
John McCall183700f2009-09-21 23:43:11 +00005924 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005925 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5926 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005927 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005928
Eli Friedman3d815e72008-08-22 00:56:42 +00005929 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005930 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005931
Steve Naroff4a746782008-01-09 22:43:08 +00005932 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005933 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00005934#define TYPE(Class, Base)
5935#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00005936#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00005937#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5938#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5939#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00005940 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00005941
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005942 case Type::LValueReference:
5943 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00005944 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00005945 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00005946
John McCallc12c5bb2010-05-15 11:32:37 +00005947 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00005948 case Type::IncompleteArray:
5949 case Type::VariableArray:
5950 case Type::FunctionProto:
5951 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00005952 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00005953
Chris Lattner1adb8832008-01-14 05:45:46 +00005954 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00005955 {
5956 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005957 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5958 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005959 if (Unqualified) {
5960 LHSPointee = LHSPointee.getUnqualifiedType();
5961 RHSPointee = RHSPointee.getUnqualifiedType();
5962 }
5963 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5964 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005965 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00005966 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005967 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00005968 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005969 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005970 return getPointerType(ResultType);
5971 }
Steve Naroffc0febd52008-12-10 17:49:55 +00005972 case Type::BlockPointer:
5973 {
5974 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005975 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5976 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005977 if (Unqualified) {
5978 LHSPointee = LHSPointee.getUnqualifiedType();
5979 RHSPointee = RHSPointee.getUnqualifiedType();
5980 }
5981 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5982 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00005983 if (ResultType.isNull()) return QualType();
5984 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5985 return LHS;
5986 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5987 return RHS;
5988 return getBlockPointerType(ResultType);
5989 }
Eli Friedmanb001de72011-10-06 23:00:33 +00005990 case Type::Atomic:
5991 {
5992 // Merge two pointer types, while trying to preserve typedef info
5993 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
5994 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
5995 if (Unqualified) {
5996 LHSValue = LHSValue.getUnqualifiedType();
5997 RHSValue = RHSValue.getUnqualifiedType();
5998 }
5999 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6000 Unqualified);
6001 if (ResultType.isNull()) return QualType();
6002 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6003 return LHS;
6004 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6005 return RHS;
6006 return getAtomicType(ResultType);
6007 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006008 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00006009 {
6010 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6011 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6012 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6013 return QualType();
6014
6015 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6016 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006017 if (Unqualified) {
6018 LHSElem = LHSElem.getUnqualifiedType();
6019 RHSElem = RHSElem.getUnqualifiedType();
6020 }
6021
6022 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006023 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00006024 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6025 return LHS;
6026 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6027 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00006028 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6029 ArrayType::ArraySizeModifier(), 0);
6030 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6031 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006032 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6033 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00006034 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6035 return LHS;
6036 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6037 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006038 if (LVAT) {
6039 // FIXME: This isn't correct! But tricky to implement because
6040 // the array's size has to be the size of LHS, but the type
6041 // has to be different.
6042 return LHS;
6043 }
6044 if (RVAT) {
6045 // FIXME: This isn't correct! But tricky to implement because
6046 // the array's size has to be the size of RHS, but the type
6047 // has to be different.
6048 return RHS;
6049 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00006050 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6051 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00006052 return getIncompleteArrayType(ResultType,
6053 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006054 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006055 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00006056 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00006057 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00006058 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00006059 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00006060 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006061 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00006062 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00006063 case Type::Complex:
6064 // Distinct complex types are incompatible.
6065 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006066 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006067 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00006068 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6069 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006070 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00006071 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00006072 case Type::ObjCObject: {
6073 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006074 // FIXME: This should be type compatibility, e.g. whether
6075 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00006076 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6077 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6078 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00006079 return LHS;
6080
Eli Friedman3d815e72008-08-22 00:56:42 +00006081 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00006082 }
Steve Naroff14108da2009-07-10 23:34:53 +00006083 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006084 if (OfBlockPointer) {
6085 if (canAssignObjCInterfacesInBlockPointer(
6086 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006087 RHS->getAs<ObjCObjectPointerType>(),
6088 BlockReturnType))
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006089 return LHS;
6090 return QualType();
6091 }
John McCall183700f2009-09-21 23:43:11 +00006092 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6093 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00006094 return LHS;
6095
Steve Naroffbc76dd02008-12-10 22:14:21 +00006096 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006097 }
Steve Naroffec0550f2007-10-15 20:41:53 +00006098 }
Douglas Gregor72564e72009-02-26 23:50:07 +00006099
6100 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00006101}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00006102
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006103bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6104 const FunctionProtoType *FromFunctionType,
6105 const FunctionProtoType *ToFunctionType) {
6106 if (FromFunctionType->hasAnyConsumedArgs() !=
6107 ToFunctionType->hasAnyConsumedArgs())
6108 return false;
6109 FunctionProtoType::ExtProtoInfo FromEPI =
6110 FromFunctionType->getExtProtoInfo();
6111 FunctionProtoType::ExtProtoInfo ToEPI =
6112 ToFunctionType->getExtProtoInfo();
6113 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6114 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6115 ArgIdx != NumArgs; ++ArgIdx) {
6116 if (FromEPI.ConsumedArguments[ArgIdx] !=
6117 ToEPI.ConsumedArguments[ArgIdx])
6118 return false;
6119 }
6120 return true;
6121}
6122
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006123/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6124/// 'RHS' attributes and returns the merged version; including for function
6125/// return types.
6126QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6127 QualType LHSCan = getCanonicalType(LHS),
6128 RHSCan = getCanonicalType(RHS);
6129 // If two types are identical, they are compatible.
6130 if (LHSCan == RHSCan)
6131 return LHS;
6132 if (RHSCan->isFunctionType()) {
6133 if (!LHSCan->isFunctionType())
6134 return QualType();
6135 QualType OldReturnType =
6136 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6137 QualType NewReturnType =
6138 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6139 QualType ResReturnType =
6140 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6141 if (ResReturnType.isNull())
6142 return QualType();
6143 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6144 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6145 // In either case, use OldReturnType to build the new function type.
6146 const FunctionType *F = LHS->getAs<FunctionType>();
6147 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00006148 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6149 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006150 QualType ResultType
6151 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006152 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006153 return ResultType;
6154 }
6155 }
6156 return QualType();
6157 }
6158
6159 // If the qualifiers are different, the types can still be merged.
6160 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6161 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6162 if (LQuals != RQuals) {
6163 // If any of these qualifiers are different, we have a type mismatch.
6164 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6165 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6166 return QualType();
6167
6168 // Exactly one GC qualifier difference is allowed: __strong is
6169 // okay if the other type has no GC qualifier but is an Objective
6170 // C object pointer (i.e. implicitly strong by default). We fix
6171 // this by pretending that the unqualified type was actually
6172 // qualified __strong.
6173 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6174 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6175 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6176
6177 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6178 return QualType();
6179
6180 if (GC_L == Qualifiers::Strong)
6181 return LHS;
6182 if (GC_R == Qualifiers::Strong)
6183 return RHS;
6184 return QualType();
6185 }
6186
6187 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6188 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6189 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6190 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6191 if (ResQT == LHSBaseQT)
6192 return LHS;
6193 if (ResQT == RHSBaseQT)
6194 return RHS;
6195 }
6196 return QualType();
6197}
6198
Chris Lattner5426bf62008-04-07 07:01:58 +00006199//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00006200// Integer Predicates
6201//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00006202
Jay Foad4ba2a172011-01-12 09:06:06 +00006203unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00006204 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00006205 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006206 if (T->isBooleanType())
6207 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00006208 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00006209 return (unsigned)getTypeSize(T);
6210}
6211
6212QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00006213 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00006214
6215 // Turn <4 x signed int> -> <4 x unsigned int>
6216 if (const VectorType *VTy = T->getAs<VectorType>())
6217 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00006218 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00006219
6220 // For enums, we return the unsigned version of the base type.
6221 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00006222 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00006223
6224 const BuiltinType *BTy = T->getAs<BuiltinType>();
6225 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006226 switch (BTy->getKind()) {
6227 case BuiltinType::Char_S:
6228 case BuiltinType::SChar:
6229 return UnsignedCharTy;
6230 case BuiltinType::Short:
6231 return UnsignedShortTy;
6232 case BuiltinType::Int:
6233 return UnsignedIntTy;
6234 case BuiltinType::Long:
6235 return UnsignedLongTy;
6236 case BuiltinType::LongLong:
6237 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00006238 case BuiltinType::Int128:
6239 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00006240 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00006241 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006242 }
6243}
6244
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00006245ASTMutationListener::~ASTMutationListener() { }
6246
Chris Lattner86df27b2009-06-14 00:45:47 +00006247
6248//===----------------------------------------------------------------------===//
6249// Builtin Type Computation
6250//===----------------------------------------------------------------------===//
6251
6252/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00006253/// pointer over the consumed characters. This returns the resultant type. If
6254/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6255/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6256/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00006257///
6258/// RequiresICE is filled in on return to indicate whether the value is required
6259/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00006260static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00006261 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00006262 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00006263 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00006264 // Modifiers.
6265 int HowLong = 0;
6266 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00006267 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006268
Chris Lattner33daae62010-10-01 22:42:38 +00006269 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00006270 bool Done = false;
6271 while (!Done) {
6272 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00006273 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006274 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00006275 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006276 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006277 case 'S':
6278 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6279 assert(!Signed && "Can't use 'S' modifier multiple times!");
6280 Signed = true;
6281 break;
6282 case 'U':
6283 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6284 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6285 Unsigned = true;
6286 break;
6287 case 'L':
6288 assert(HowLong <= 2 && "Can't have LLLL modifier");
6289 ++HowLong;
6290 break;
6291 }
6292 }
6293
6294 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00006295
Chris Lattner86df27b2009-06-14 00:45:47 +00006296 // Read the base type.
6297 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00006298 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00006299 case 'v':
6300 assert(HowLong == 0 && !Signed && !Unsigned &&
6301 "Bad modifiers used with 'v'!");
6302 Type = Context.VoidTy;
6303 break;
6304 case 'f':
6305 assert(HowLong == 0 && !Signed && !Unsigned &&
6306 "Bad modifiers used with 'f'!");
6307 Type = Context.FloatTy;
6308 break;
6309 case 'd':
6310 assert(HowLong < 2 && !Signed && !Unsigned &&
6311 "Bad modifiers used with 'd'!");
6312 if (HowLong)
6313 Type = Context.LongDoubleTy;
6314 else
6315 Type = Context.DoubleTy;
6316 break;
6317 case 's':
6318 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6319 if (Unsigned)
6320 Type = Context.UnsignedShortTy;
6321 else
6322 Type = Context.ShortTy;
6323 break;
6324 case 'i':
6325 if (HowLong == 3)
6326 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6327 else if (HowLong == 2)
6328 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6329 else if (HowLong == 1)
6330 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6331 else
6332 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6333 break;
6334 case 'c':
6335 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6336 if (Signed)
6337 Type = Context.SignedCharTy;
6338 else if (Unsigned)
6339 Type = Context.UnsignedCharTy;
6340 else
6341 Type = Context.CharTy;
6342 break;
6343 case 'b': // boolean
6344 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6345 Type = Context.BoolTy;
6346 break;
6347 case 'z': // size_t.
6348 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6349 Type = Context.getSizeType();
6350 break;
6351 case 'F':
6352 Type = Context.getCFConstantStringType();
6353 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00006354 case 'G':
6355 Type = Context.getObjCIdType();
6356 break;
6357 case 'H':
6358 Type = Context.getObjCSelType();
6359 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006360 case 'a':
6361 Type = Context.getBuiltinVaListType();
6362 assert(!Type.isNull() && "builtin va list type not initialized!");
6363 break;
6364 case 'A':
6365 // This is a "reference" to a va_list; however, what exactly
6366 // this means depends on how va_list is defined. There are two
6367 // different kinds of va_list: ones passed by value, and ones
6368 // passed by reference. An example of a by-value va_list is
6369 // x86, where va_list is a char*. An example of by-ref va_list
6370 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6371 // we want this argument to be a char*&; for x86-64, we want
6372 // it to be a __va_list_tag*.
6373 Type = Context.getBuiltinVaListType();
6374 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00006375 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00006376 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00006377 else
Chris Lattner86df27b2009-06-14 00:45:47 +00006378 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00006379 break;
6380 case 'V': {
6381 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00006382 unsigned NumElements = strtoul(Str, &End, 10);
6383 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00006384 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00006385
Chris Lattner14e0e742010-10-01 22:53:11 +00006386 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6387 RequiresICE, false);
6388 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00006389
6390 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00006391 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00006392 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00006393 break;
6394 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00006395 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00006396 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6397 false);
6398 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00006399 Type = Context.getComplexType(ElementType);
6400 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00006401 }
6402 case 'Y' : {
6403 Type = Context.getPointerDiffType();
6404 break;
6405 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006406 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00006407 Type = Context.getFILEType();
6408 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006409 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00006410 return QualType();
6411 }
Mike Stumpfd612db2009-07-28 23:47:15 +00006412 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006413 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00006414 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00006415 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00006416 else
6417 Type = Context.getjmp_bufType();
6418
Mike Stumpfd612db2009-07-28 23:47:15 +00006419 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006420 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00006421 return QualType();
6422 }
6423 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00006424 case 'K':
6425 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6426 Type = Context.getucontext_tType();
6427
6428 if (Type.isNull()) {
6429 Error = ASTContext::GE_Missing_ucontext;
6430 return QualType();
6431 }
6432 break;
Mike Stump782fa302009-07-28 02:25:19 +00006433 }
Mike Stump1eb44332009-09-09 15:08:12 +00006434
Chris Lattner33daae62010-10-01 22:42:38 +00006435 // If there are modifiers and if we're allowed to parse them, go for it.
6436 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00006437 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00006438 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00006439 default: Done = true; --Str; break;
6440 case '*':
6441 case '&': {
6442 // Both pointers and references can have their pointee types
6443 // qualified with an address space.
6444 char *End;
6445 unsigned AddrSpace = strtoul(Str, &End, 10);
6446 if (End != Str && AddrSpace != 0) {
6447 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6448 Str = End;
6449 }
6450 if (c == '*')
6451 Type = Context.getPointerType(Type);
6452 else
6453 Type = Context.getLValueReferenceType(Type);
6454 break;
6455 }
6456 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6457 case 'C':
6458 Type = Type.withConst();
6459 break;
6460 case 'D':
6461 Type = Context.getVolatileType(Type);
6462 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006463 }
6464 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00006465
Chris Lattner14e0e742010-10-01 22:53:11 +00006466 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00006467 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00006468
Chris Lattner86df27b2009-06-14 00:45:47 +00006469 return Type;
6470}
6471
6472/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00006473QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00006474 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00006475 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00006476 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00006477
Chris Lattner5f9e2722011-07-23 10:55:15 +00006478 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00006479
Chris Lattner14e0e742010-10-01 22:53:11 +00006480 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00006481 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00006482 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6483 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006484 if (Error != GE_None)
6485 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00006486
6487 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6488
Chris Lattner86df27b2009-06-14 00:45:47 +00006489 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00006490 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006491 if (Error != GE_None)
6492 return QualType();
6493
Chris Lattner14e0e742010-10-01 22:53:11 +00006494 // If this argument is required to be an IntegerConstantExpression and the
6495 // caller cares, fill in the bitmask we return.
6496 if (RequiresICE && IntegerConstantArgs)
6497 *IntegerConstantArgs |= 1 << ArgTypes.size();
6498
Chris Lattner86df27b2009-06-14 00:45:47 +00006499 // Do array -> pointer decay. The builtin should use the decayed type.
6500 if (Ty->isArrayType())
6501 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00006502
Chris Lattner86df27b2009-06-14 00:45:47 +00006503 ArgTypes.push_back(Ty);
6504 }
6505
6506 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6507 "'.' should only occur at end of builtin type list!");
6508
John McCall00ccbef2010-12-21 00:44:39 +00006509 FunctionType::ExtInfo EI;
6510 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6511
6512 bool Variadic = (TypeStr[0] == '.');
6513
6514 // We really shouldn't be making a no-proto type here, especially in C++.
6515 if (ArgTypes.empty() && Variadic)
6516 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00006517
John McCalle23cf432010-12-14 08:05:40 +00006518 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00006519 EPI.ExtInfo = EI;
6520 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00006521
6522 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00006523}
Eli Friedmana95d7572009-08-19 07:44:53 +00006524
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006525GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6526 GVALinkage External = GVA_StrongExternal;
6527
6528 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006529 switch (L) {
6530 case NoLinkage:
6531 case InternalLinkage:
6532 case UniqueExternalLinkage:
6533 return GVA_Internal;
6534
6535 case ExternalLinkage:
6536 switch (FD->getTemplateSpecializationKind()) {
6537 case TSK_Undeclared:
6538 case TSK_ExplicitSpecialization:
6539 External = GVA_StrongExternal;
6540 break;
6541
6542 case TSK_ExplicitInstantiationDefinition:
6543 return GVA_ExplicitTemplateInstantiation;
6544
6545 case TSK_ExplicitInstantiationDeclaration:
6546 case TSK_ImplicitInstantiation:
6547 External = GVA_TemplateInstantiation;
6548 break;
6549 }
6550 }
6551
6552 if (!FD->isInlined())
6553 return External;
6554
6555 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6556 // GNU or C99 inline semantics. Determine whether this symbol should be
6557 // externally visible.
6558 if (FD->isInlineDefinitionExternallyVisible())
6559 return External;
6560
6561 // C99 inline semantics, where the symbol is not externally visible.
6562 return GVA_C99Inline;
6563 }
6564
6565 // C++0x [temp.explicit]p9:
6566 // [ Note: The intent is that an inline function that is the subject of
6567 // an explicit instantiation declaration will still be implicitly
6568 // instantiated when used so that the body can be considered for
6569 // inlining, but that no out-of-line copy of the inline function would be
6570 // generated in the translation unit. -- end note ]
6571 if (FD->getTemplateSpecializationKind()
6572 == TSK_ExplicitInstantiationDeclaration)
6573 return GVA_C99Inline;
6574
6575 return GVA_CXXInline;
6576}
6577
6578GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6579 // If this is a static data member, compute the kind of template
6580 // specialization. Otherwise, this variable is not part of a
6581 // template.
6582 TemplateSpecializationKind TSK = TSK_Undeclared;
6583 if (VD->isStaticDataMember())
6584 TSK = VD->getTemplateSpecializationKind();
6585
6586 Linkage L = VD->getLinkage();
6587 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6588 VD->getType()->getLinkage() == UniqueExternalLinkage)
6589 L = UniqueExternalLinkage;
6590
6591 switch (L) {
6592 case NoLinkage:
6593 case InternalLinkage:
6594 case UniqueExternalLinkage:
6595 return GVA_Internal;
6596
6597 case ExternalLinkage:
6598 switch (TSK) {
6599 case TSK_Undeclared:
6600 case TSK_ExplicitSpecialization:
6601 return GVA_StrongExternal;
6602
6603 case TSK_ExplicitInstantiationDeclaration:
6604 llvm_unreachable("Variable should not be instantiated");
6605 // Fall through to treat this like any other instantiation.
6606
6607 case TSK_ExplicitInstantiationDefinition:
6608 return GVA_ExplicitTemplateInstantiation;
6609
6610 case TSK_ImplicitInstantiation:
6611 return GVA_TemplateInstantiation;
6612 }
6613 }
6614
6615 return GVA_StrongExternal;
6616}
6617
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00006618bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006619 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6620 if (!VD->isFileVarDecl())
6621 return false;
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00006622 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006623 return false;
6624
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006625 // Weak references don't produce any output by themselves.
6626 if (D->hasAttr<WeakRefAttr>())
6627 return false;
6628
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006629 // Aliases and used decls are required.
6630 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6631 return true;
6632
6633 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6634 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00006635 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00006636 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006637
6638 // Constructors and destructors are required.
6639 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6640 return true;
6641
6642 // The key function for a class is required.
6643 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6644 const CXXRecordDecl *RD = MD->getParent();
6645 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6646 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6647 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6648 return true;
6649 }
6650 }
6651
6652 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6653
6654 // static, static inline, always_inline, and extern inline functions can
6655 // always be deferred. Normal inline functions can be deferred in C99/C++.
6656 // Implicit template instantiations can also be deferred in C++.
6657 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6658 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6659 return false;
6660 return true;
6661 }
Douglas Gregor94da1582011-09-10 00:22:34 +00006662
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006663 const VarDecl *VD = cast<VarDecl>(D);
6664 assert(VD->isFileVarDecl() && "Expected file scoped var");
6665
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006666 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6667 return false;
6668
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006669 // Structs that have non-trivial constructors or destructors are required.
6670
6671 // FIXME: Handle references.
Sean Hunt023df372011-05-09 18:22:59 +00006672 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006673 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6674 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Sean Hunt023df372011-05-09 18:22:59 +00006675 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6676 RD->hasTrivialCopyConstructor() &&
6677 RD->hasTrivialMoveConstructor() &&
6678 RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006679 return true;
6680 }
6681 }
6682
6683 GVALinkage L = GetGVALinkageForVariable(VD);
6684 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6685 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6686 return false;
6687 }
6688
6689 return true;
6690}
Charles Davis071cc7d2010-08-16 03:33:14 +00006691
Charles Davisee743f92010-11-09 18:04:24 +00006692CallingConv ASTContext::getDefaultMethodCallConv() {
6693 // Pass through to the C++ ABI object
6694 return ABI->getDefaultMethodCallConv();
6695}
6696
Jay Foad4ba2a172011-01-12 09:06:06 +00006697bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00006698 // Pass through to the C++ ABI object
6699 return ABI->isNearlyEmpty(RD);
6700}
6701
Peter Collingbourne14110472011-01-13 18:57:25 +00006702MangleContext *ASTContext::createMangleContext() {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00006703 switch (Target->getCXXABI()) {
Peter Collingbourne14110472011-01-13 18:57:25 +00006704 case CXXABI_ARM:
6705 case CXXABI_Itanium:
6706 return createItaniumMangleContext(*this, getDiagnostics());
6707 case CXXABI_Microsoft:
6708 return createMicrosoftMangleContext(*this, getDiagnostics());
6709 }
David Blaikieb219cfc2011-09-23 05:06:16 +00006710 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00006711}
6712
Charles Davis071cc7d2010-08-16 03:33:14 +00006713CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00006714
6715size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00006716 return ASTRecordLayouts.getMemorySize()
6717 + llvm::capacity_in_bytes(ObjCLayouts)
6718 + llvm::capacity_in_bytes(KeyFunctions)
6719 + llvm::capacity_in_bytes(ObjCImpls)
6720 + llvm::capacity_in_bytes(BlockVarCopyInits)
6721 + llvm::capacity_in_bytes(DeclAttrs)
6722 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6723 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6724 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6725 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6726 + llvm::capacity_in_bytes(OverriddenMethods)
6727 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00006728 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00006729 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00006730}
Ted Kremenekd211cb72011-10-06 05:00:56 +00006731
6732void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6733 ParamIndices[D] = index;
6734}
6735
6736unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6737 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6738 assert(I != ParamIndices.end() &&
6739 "ParmIndices lacks entry set by ParmVarDecl");
6740 return I->second;
6741}