blob: 20c5d486c03ca4a639872c47551c06a21d6ba89b [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"
Benjamin Kramer00bd44d2012-02-04 12:31:12 +000027#include "clang/Basic/PartialDiagnostic.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000028#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000030#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000031#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000032#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000033#include "llvm/Support/raw_ostream.h"
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +000034#include "llvm/Support/Capacity.h"
Charles Davis071cc7d2010-08-16 03:33:14 +000035#include "CXXABI.h"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000036#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000037
Reid Spencer5f016e22007-07-11 17:01:13 +000038using namespace clang;
39
Douglas Gregor18274032010-07-03 00:47:00 +000040unsigned ASTContext::NumImplicitDefaultConstructors;
41unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000042unsigned ASTContext::NumImplicitCopyConstructors;
43unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000044unsigned ASTContext::NumImplicitMoveConstructors;
45unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000046unsigned ASTContext::NumImplicitCopyAssignmentOperators;
47unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000048unsigned ASTContext::NumImplicitMoveAssignmentOperators;
49unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000050unsigned ASTContext::NumImplicitDestructors;
51unsigned ASTContext::NumImplicitDestructorsDeclared;
52
Reid Spencer5f016e22007-07-11 17:01:13 +000053enum FloatingRank {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +000054 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Reid Spencer5f016e22007-07-11 17:01:13 +000055};
56
Douglas Gregor3e1274f2010-06-16 21:09:37 +000057void
58ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
59 TemplateTemplateParmDecl *Parm) {
60 ID.AddInteger(Parm->getDepth());
61 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +000062 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000063
64 TemplateParameterList *Params = Parm->getTemplateParameters();
65 ID.AddInteger(Params->size());
66 for (TemplateParameterList::const_iterator P = Params->begin(),
67 PEnd = Params->end();
68 P != PEnd; ++P) {
69 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
70 ID.AddInteger(0);
71 ID.AddBoolean(TTP->isParameterPack());
72 continue;
73 }
74
75 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
76 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +000077 ID.AddBoolean(NTTP->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000078 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +000079 if (NTTP->isExpandedParameterPack()) {
80 ID.AddBoolean(true);
81 ID.AddInteger(NTTP->getNumExpansionTypes());
82 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
83 ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
84 } else
85 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +000086 continue;
87 }
88
89 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
90 ID.AddInteger(2);
91 Profile(ID, TTP);
92 }
93}
94
95TemplateTemplateParmDecl *
96ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +000097 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +000098 // Check if we already have a canonical template template parameter.
99 llvm::FoldingSetNodeID ID;
100 CanonicalTemplateTemplateParm::Profile(ID, TTP);
101 void *InsertPos = 0;
102 CanonicalTemplateTemplateParm *Canonical
103 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
104 if (Canonical)
105 return Canonical->getParam();
106
107 // Build a canonical template parameter list.
108 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000109 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000110 CanonParams.reserve(Params->size());
111 for (TemplateParameterList::const_iterator P = Params->begin(),
112 PEnd = Params->end();
113 P != PEnd; ++P) {
114 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
115 CanonParams.push_back(
116 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000117 SourceLocation(),
118 SourceLocation(),
119 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000120 TTP->getIndex(), 0, false,
121 TTP->isParameterPack()));
122 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000123 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
124 QualType T = getCanonicalType(NTTP->getType());
125 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
126 NonTypeTemplateParmDecl *Param;
127 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000128 SmallVector<QualType, 2> ExpandedTypes;
129 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000130 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
131 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
132 ExpandedTInfos.push_back(
133 getTrivialTypeSourceInfo(ExpandedTypes.back()));
134 }
135
136 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000137 SourceLocation(),
138 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000139 NTTP->getDepth(),
140 NTTP->getPosition(), 0,
141 T,
142 TInfo,
143 ExpandedTypes.data(),
144 ExpandedTypes.size(),
145 ExpandedTInfos.data());
146 } else {
147 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000148 SourceLocation(),
149 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000150 NTTP->getDepth(),
151 NTTP->getPosition(), 0,
152 T,
153 NTTP->isParameterPack(),
154 TInfo);
155 }
156 CanonParams.push_back(Param);
157
158 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000159 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
160 cast<TemplateTemplateParmDecl>(*P)));
161 }
162
163 TemplateTemplateParmDecl *CanonTTP
164 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
165 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000166 TTP->getPosition(),
167 TTP->isParameterPack(),
168 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000169 TemplateParameterList::Create(*this, SourceLocation(),
170 SourceLocation(),
171 CanonParams.data(),
172 CanonParams.size(),
173 SourceLocation()));
174
175 // Get the new insert position for the node we care about.
176 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
177 assert(Canonical == 0 && "Shouldn't be in the map!");
178 (void)Canonical;
179
180 // Create the canonical template template parameter entry.
181 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
182 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
183 return CanonTTP;
184}
185
Charles Davis071cc7d2010-08-16 03:33:14 +0000186CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000187 if (!LangOpts.CPlusPlus) return 0;
188
Charles Davis20cf7172010-08-19 02:18:14 +0000189 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000190 case CXXABI_ARM:
191 return CreateARMCXXABI(*this);
192 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000193 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000194 case CXXABI_Microsoft:
195 return CreateMicrosoftCXXABI(*this);
196 }
David Blaikie7530c032012-01-17 06:56:22 +0000197 llvm_unreachable("Invalid CXXABI type!");
Charles Davis071cc7d2010-08-16 03:33:14 +0000198}
199
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000200static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000201 const LangOptions &LOpts) {
202 if (LOpts.FakeAddressSpaceMap) {
203 // The fake address space map must have a distinct entry for each
204 // language-specific address space.
205 static const unsigned FakeAddrSpaceMap[] = {
206 1, // opencl_global
207 2, // opencl_local
208 3 // opencl_constant
209 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000210 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000211 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000212 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000213 }
214}
215
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000216ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000217 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000218 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000219 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000220 unsigned size_reserve,
221 bool DelayInitialization)
222 : FunctionProtoTypes(this_()),
223 TemplateSpecializationTypes(this_()),
224 DependentTemplateSpecializationTypes(this_()),
225 SubstTemplateTemplateParmPacks(this_()),
226 GlobalNestedNameSpecifier(0),
227 Int128Decl(0), UInt128Decl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000228 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000229 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000230 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000231 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
232 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
233 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000234 NullTypeSourceInfo(QualType()),
235 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000236 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000237 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000238 Idents(idents), Selectors(sels),
239 BuiltinInfo(builtins),
240 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000241 ExternalSource(0), Listener(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000242 LastSDM(0, 0),
243 UniqueBlockByRefTypeID(0)
244{
Benjamin Krameref9b60f2012-02-04 12:30:46 +0000245 // Create a new allocator for partial diagnostics.
246 DiagAllocator = new (BumpAlloc) PartialDiagnosticStorageAllocator;
247
Mike Stump1eb44332009-09-09 15:08:12 +0000248 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000249 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000250
251 if (!DelayInitialization) {
252 assert(t && "No target supplied for ASTContext initialization");
253 InitBuiltinTypes(*t);
254 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000255}
256
Reid Spencer5f016e22007-07-11 17:01:13 +0000257ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000258 // Release the DenseMaps associated with DeclContext objects.
259 // FIXME: Is this the ideal solution?
260 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000261
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000262 // Call all of the deallocation functions.
263 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
264 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000265
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000266 // Release all of the memory associated with overridden C++ methods.
267 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
268 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
269 OM != OMEnd; ++OM)
270 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +0000271
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000272 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000273 // because they can contain DenseMaps.
274 for (llvm::DenseMap<const ObjCContainerDecl*,
275 const ASTRecordLayout*>::iterator
276 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
277 // Increment in loop to prevent using deallocated memory.
278 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
279 R->Destroy(*this);
280
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000281 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
282 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
283 // Increment in loop to prevent using deallocated memory.
284 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
285 R->Destroy(*this);
286 }
Douglas Gregor63200642010-08-30 16:49:28 +0000287
288 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
289 AEnd = DeclAttrs.end();
290 A != AEnd; ++A)
291 A->second->~AttrVec();
Benjamin Krameref9b60f2012-02-04 12:30:46 +0000292
293 // Destroy the partial diagnostic allocator.
294 DiagAllocator->~PartialDiagnosticStorageAllocator();
Douglas Gregor63200642010-08-30 16:49:28 +0000295}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000296
Douglas Gregor00545312010-05-23 18:26:36 +0000297void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
298 Deallocations.push_back(std::make_pair(Callback, Data));
299}
300
Mike Stump1eb44332009-09-09 15:08:12 +0000301void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000302ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000303 ExternalSource.reset(Source.take());
304}
305
Reid Spencer5f016e22007-07-11 17:01:13 +0000306void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000307 llvm::errs() << "\n*** AST Context Stats:\n";
308 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000309
Douglas Gregordbe833d2009-05-26 14:40:08 +0000310 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000311#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000312#define ABSTRACT_TYPE(Name, Parent)
313#include "clang/AST/TypeNodes.def"
314 0 // Extra
315 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000316
Reid Spencer5f016e22007-07-11 17:01:13 +0000317 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
318 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000319 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000320 }
321
Douglas Gregordbe833d2009-05-26 14:40:08 +0000322 unsigned Idx = 0;
323 unsigned TotalBytes = 0;
324#define TYPE(Name, Parent) \
325 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000326 llvm::errs() << " " << counts[Idx] << " " << #Name \
327 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000328 TotalBytes += counts[Idx] * sizeof(Name##Type); \
329 ++Idx;
330#define ABSTRACT_TYPE(Name, Parent)
331#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Chandler Carruthcd92a652011-07-04 05:32:14 +0000333 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
334
Douglas Gregor4923aa22010-07-02 20:37:36 +0000335 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000336 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
337 << NumImplicitDefaultConstructors
338 << " implicit default constructors created\n";
339 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
340 << NumImplicitCopyConstructors
341 << " implicit copy constructors created\n";
Sean Huntffe37fd2011-05-25 20:50:04 +0000342 if (getLangOptions().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000343 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
344 << NumImplicitMoveConstructors
345 << " implicit move constructors created\n";
346 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
347 << NumImplicitCopyAssignmentOperators
348 << " implicit copy assignment operators created\n";
Sean Huntffe37fd2011-05-25 20:50:04 +0000349 if (getLangOptions().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000350 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
351 << NumImplicitMoveAssignmentOperators
352 << " implicit move assignment operators created\n";
353 llvm::errs() << NumImplicitDestructorsDeclared << "/"
354 << NumImplicitDestructors
355 << " implicit destructors created\n";
356
Douglas Gregor2cf26342009-04-09 22:27:44 +0000357 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000358 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000359 ExternalSource->PrintStats();
360 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000361
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000362 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000363}
364
Douglas Gregor772eeae2011-08-12 06:49:56 +0000365TypedefDecl *ASTContext::getInt128Decl() const {
366 if (!Int128Decl) {
367 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
368 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
369 getTranslationUnitDecl(),
370 SourceLocation(),
371 SourceLocation(),
372 &Idents.get("__int128_t"),
373 TInfo);
374 }
375
376 return Int128Decl;
377}
378
379TypedefDecl *ASTContext::getUInt128Decl() const {
380 if (!UInt128Decl) {
381 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
382 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
383 getTranslationUnitDecl(),
384 SourceLocation(),
385 SourceLocation(),
386 &Idents.get("__uint128_t"),
387 TInfo);
388 }
389
390 return UInt128Decl;
391}
Reid Spencer5f016e22007-07-11 17:01:13 +0000392
John McCalle27ec8a2009-10-23 23:03:21 +0000393void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000394 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000395 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000396 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000397}
398
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000399void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
400 assert((!this->Target || this->Target == &Target) &&
401 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000402 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000404 this->Target = &Target;
405
406 ABI.reset(createCXXABI(Target));
407 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
408
Reid Spencer5f016e22007-07-11 17:01:13 +0000409 // C99 6.2.5p19.
410 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000411
Reid Spencer5f016e22007-07-11 17:01:13 +0000412 // C99 6.2.5p2.
413 InitBuiltinType(BoolTy, BuiltinType::Bool);
414 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000415 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000416 InitBuiltinType(CharTy, BuiltinType::Char_S);
417 else
418 InitBuiltinType(CharTy, BuiltinType::Char_U);
419 // C99 6.2.5p4.
420 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
421 InitBuiltinType(ShortTy, BuiltinType::Short);
422 InitBuiltinType(IntTy, BuiltinType::Int);
423 InitBuiltinType(LongTy, BuiltinType::Long);
424 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000425
Reid Spencer5f016e22007-07-11 17:01:13 +0000426 // C99 6.2.5p6.
427 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
428 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
429 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
430 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
431 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Reid Spencer5f016e22007-07-11 17:01:13 +0000433 // C99 6.2.5p10.
434 InitBuiltinType(FloatTy, BuiltinType::Float);
435 InitBuiltinType(DoubleTy, BuiltinType::Double);
436 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000437
Chris Lattner2df9ced2009-04-30 02:43:43 +0000438 // GNU extension, 128-bit integers.
439 InitBuiltinType(Int128Ty, BuiltinType::Int128);
440 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
441
Chris Lattner3f59c972010-12-25 23:25:43 +0000442 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedmand3d77cd2011-04-30 19:24:24 +0000443 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattner3f59c972010-12-25 23:25:43 +0000444 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
445 else // -fshort-wchar makes wchar_t be unsigned.
446 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
447 } else // C99
Chris Lattner3a250322009-02-26 23:43:47 +0000448 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000449
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000450 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
451 InitBuiltinType(Char16Ty, BuiltinType::Char16);
452 else // C99
453 Char16Ty = getFromTargetType(Target.getChar16Type());
454
455 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
456 InitBuiltinType(Char32Ty, BuiltinType::Char32);
457 else // C99
458 Char32Ty = getFromTargetType(Target.getChar32Type());
459
Douglas Gregor898574e2008-12-05 23:32:09 +0000460 // Placeholder type for type-dependent expressions whose type is
461 // completely unknown. No code should ever check a type against
462 // DependentTy and users should never see it; however, it is here to
463 // help diagnose failures to properly check for type-dependent
464 // expressions.
465 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000466
John McCall2a984ca2010-10-12 00:20:44 +0000467 // Placeholder type for functions.
468 InitBuiltinType(OverloadTy, BuiltinType::Overload);
469
John McCall864c0412011-04-26 20:42:42 +0000470 // Placeholder type for bound members.
471 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
472
John McCall3c3b7f92011-10-25 17:37:35 +0000473 // Placeholder type for pseudo-objects.
474 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
475
John McCall1de4d4e2011-04-07 08:22:57 +0000476 // "any" type; useful for debugger-like clients.
477 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
478
John McCall0ddaeb92011-10-17 18:09:15 +0000479 // Placeholder type for unbridged ARC casts.
480 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
481
Reid Spencer5f016e22007-07-11 17:01:13 +0000482 // C99 6.2.5p11.
483 FloatComplexTy = getComplexType(FloatTy);
484 DoubleComplexTy = getComplexType(DoubleTy);
485 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000486
Steve Naroff7e219e42007-10-15 14:41:52 +0000487 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000489 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000490 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
491 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000492 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000493
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000494 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000496 // void * type
497 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000498
499 // nullptr type (C++0x 2.14.7)
500 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000501
502 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
503 InitBuiltinType(HalfTy, BuiltinType::Half);
Reid Spencer5f016e22007-07-11 17:01:13 +0000504}
505
David Blaikied6471f72011-09-25 23:23:43 +0000506DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000507 return SourceMgr.getDiagnostics();
508}
509
Douglas Gregor63200642010-08-30 16:49:28 +0000510AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
511 AttrVec *&Result = DeclAttrs[D];
512 if (!Result) {
513 void *Mem = Allocate(sizeof(AttrVec));
514 Result = new (Mem) AttrVec;
515 }
516
517 return *Result;
518}
519
520/// \brief Erase the attributes corresponding to the given declaration.
521void ASTContext::eraseDeclAttrs(const Decl *D) {
522 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
523 if (Pos != DeclAttrs.end()) {
524 Pos->second->~AttrVec();
525 DeclAttrs.erase(Pos);
526 }
527}
528
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000529MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000530ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000531 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000532 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000533 = InstantiatedFromStaticDataMember.find(Var);
534 if (Pos == InstantiatedFromStaticDataMember.end())
535 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Douglas Gregor7caa6822009-07-24 20:34:43 +0000537 return Pos->second;
538}
539
Mike Stump1eb44332009-09-09 15:08:12 +0000540void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000541ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000542 TemplateSpecializationKind TSK,
543 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000544 assert(Inst->isStaticDataMember() && "Not a static data member");
545 assert(Tmpl->isStaticDataMember() && "Not a static data member");
546 assert(!InstantiatedFromStaticDataMember[Inst] &&
547 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000548 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000549 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000550}
551
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000552FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
553 const FunctionDecl *FD){
554 assert(FD && "Specialization is 0");
555 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000556 = ClassScopeSpecializationPattern.find(FD);
557 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000558 return 0;
559
560 return Pos->second;
561}
562
563void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
564 FunctionDecl *Pattern) {
565 assert(FD && "Specialization is 0");
566 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000567 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000568}
569
John McCall7ba107a2009-11-18 02:36:19 +0000570NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000571ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000572 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000573 = InstantiatedFromUsingDecl.find(UUD);
574 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000575 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000576
Anders Carlsson0d8df782009-08-29 19:37:28 +0000577 return Pos->second;
578}
579
580void
John McCalled976492009-12-04 22:46:56 +0000581ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
582 assert((isa<UsingDecl>(Pattern) ||
583 isa<UnresolvedUsingValueDecl>(Pattern) ||
584 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
585 "pattern decl is not a using decl");
586 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
587 InstantiatedFromUsingDecl[Inst] = Pattern;
588}
589
590UsingShadowDecl *
591ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
592 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
593 = InstantiatedFromUsingShadowDecl.find(Inst);
594 if (Pos == InstantiatedFromUsingShadowDecl.end())
595 return 0;
596
597 return Pos->second;
598}
599
600void
601ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
602 UsingShadowDecl *Pattern) {
603 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
604 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000605}
606
Anders Carlssond8b285f2009-09-01 04:26:58 +0000607FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
608 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
609 = InstantiatedFromUnnamedFieldDecl.find(Field);
610 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
611 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000612
Anders Carlssond8b285f2009-09-01 04:26:58 +0000613 return Pos->second;
614}
615
616void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
617 FieldDecl *Tmpl) {
618 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
619 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
620 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
621 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000622
Anders Carlssond8b285f2009-09-01 04:26:58 +0000623 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
624}
625
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000626bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
627 const FieldDecl *LastFD) const {
628 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000629 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000630}
631
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000632bool ASTContext::ZeroBitfieldFollowsBitfield(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) == 0 &&
636 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000637}
638
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000639bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
640 const FieldDecl *LastFD) const {
641 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000642 FD->getBitWidthValue(*this) &&
643 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000644}
645
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000646bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000647 const FieldDecl *LastFD) const {
648 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000649 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000650}
651
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000652bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000653 const FieldDecl *LastFD) const {
654 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000655 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000656}
657
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000658ASTContext::overridden_cxx_method_iterator
659ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
660 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
661 = OverriddenMethods.find(Method);
662 if (Pos == OverriddenMethods.end())
663 return 0;
664
665 return Pos->second.begin();
666}
667
668ASTContext::overridden_cxx_method_iterator
669ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
670 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
671 = OverriddenMethods.find(Method);
672 if (Pos == OverriddenMethods.end())
673 return 0;
674
675 return Pos->second.end();
676}
677
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000678unsigned
679ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
680 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
681 = OverriddenMethods.find(Method);
682 if (Pos == OverriddenMethods.end())
683 return 0;
684
685 return Pos->second.size();
686}
687
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000688void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
689 const CXXMethodDecl *Overridden) {
690 OverriddenMethods[Method].push_back(Overridden);
691}
692
Douglas Gregore6649772011-12-03 00:30:27 +0000693void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
694 assert(!Import->NextLocalImport && "Import declaration already in the chain");
695 assert(!Import->isFromASTFile() && "Non-local import declaration");
696 if (!FirstLocalImport) {
697 FirstLocalImport = Import;
698 LastLocalImport = Import;
699 return;
700 }
701
702 LastLocalImport->NextLocalImport = Import;
703 LastLocalImport = Import;
704}
705
Chris Lattner464175b2007-07-18 17:52:12 +0000706//===----------------------------------------------------------------------===//
707// Type Sizing and Analysis
708//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000709
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000710/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
711/// scalar floating point type.
712const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000713 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000714 assert(BT && "Not a floating point type!");
715 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000716 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000717 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000718 case BuiltinType::Float: return Target->getFloatFormat();
719 case BuiltinType::Double: return Target->getDoubleFormat();
720 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000721 }
722}
723
Ken Dyck8b752f12010-01-27 17:10:57 +0000724/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000725/// specified decl. Note that bitfields do not have a valid alignment, so
726/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000727/// If @p RefAsPointee, references are treated like their underlying type
728/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +0000729CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000730 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +0000731
John McCall4081a5c2010-10-08 18:24:19 +0000732 bool UseAlignAttrOnly = false;
733 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
734 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +0000735
John McCall4081a5c2010-10-08 18:24:19 +0000736 // __attribute__((aligned)) can increase or decrease alignment
737 // *except* on a struct or struct member, where it only increases
738 // alignment unless 'packed' is also specified.
739 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +0000740 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +0000741 // ignore that possibility; Sema should diagnose it.
742 if (isa<FieldDecl>(D)) {
743 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
744 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
745 } else {
746 UseAlignAttrOnly = true;
747 }
748 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +0000749 else if (isa<FieldDecl>(D))
750 UseAlignAttrOnly =
751 D->hasAttr<PackedAttr>() ||
752 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +0000753
John McCallba4f5d52011-01-20 07:57:12 +0000754 // If we're using the align attribute only, just ignore everything
755 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +0000756 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +0000757 // do nothing
758
John McCall4081a5c2010-10-08 18:24:19 +0000759 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +0000760 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000761 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000762 if (RefAsPointee)
763 T = RT->getPointeeType();
764 else
765 T = getPointerType(RT->getPointeeType());
766 }
767 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +0000768 // Adjust alignments of declarations with array type by the
769 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000770 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +0000771 const ArrayType *arrayType;
772 if (MinWidth && (arrayType = getAsArrayType(T))) {
773 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000774 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +0000775 else if (isa<ConstantArrayType>(arrayType) &&
776 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000777 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000778
John McCall3b657512011-01-19 10:06:00 +0000779 // Walk through any array types while we're at it.
780 T = getBaseElementType(arrayType);
781 }
Chad Rosier9f1210c2011-07-26 07:03:04 +0000782 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedmandcdafb62009-02-22 02:56:25 +0000783 }
John McCallba4f5d52011-01-20 07:57:12 +0000784
785 // Fields can be subject to extra alignment constraints, like if
786 // the field is packed, the struct is packed, or the struct has a
787 // a max-field-alignment constraint (#pragma pack). So calculate
788 // the actual alignment of the field within the struct, and then
789 // (as we're expected to) constrain that by the alignment of the type.
790 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
791 // So calculate the alignment of the field.
792 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
793
794 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +0000795 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +0000796
797 // Use the GCD of that and the offset within the record.
798 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
799 if (offset > 0) {
800 // Alignment is always a power of 2, so the GCD will be a power of 2,
801 // which means we get to do this crazy thing instead of Euclid's.
802 uint64_t lowBitOfOffset = offset & (~offset + 1);
803 if (lowBitOfOffset < fieldAlign)
804 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
805 }
806
807 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +0000808 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000809 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000810
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000811 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +0000812}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000813
John McCallea1471e2010-05-20 01:18:31 +0000814std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000815ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +0000816 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000817 return std::make_pair(toCharUnitsFromBits(Info.first),
818 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +0000819}
820
821std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000822ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +0000823 return getTypeInfoInChars(T.getTypePtr());
824}
825
Chris Lattnera7674d82007-07-13 22:13:22 +0000826/// getTypeSize - Return the size of the specified type, in bits. This method
827/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000828///
829/// FIXME: Pointers into different addr spaces could have different sizes and
830/// alignment requirements: getPointerInfo should take an AddrSpace, this
831/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000832std::pair<uint64_t, unsigned>
Jay Foad4ba2a172011-01-12 09:06:06 +0000833ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +0000834 uint64_t Width=0;
835 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000836 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000837#define TYPE(Class, Base)
838#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000839#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000840#define DEPENDENT_TYPE(Class, Base) case Type::Class:
841#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +0000842 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000843
Chris Lattner692233e2007-07-13 22:27:08 +0000844 case Type::FunctionNoProto:
845 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000846 // GCC extension: alignof(function) = 32 bits
847 Width = 0;
848 Align = 32;
849 break;
850
Douglas Gregor72564e72009-02-26 23:50:07 +0000851 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000852 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000853 Width = 0;
854 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
855 break;
856
Steve Narofffb22d962007-08-30 01:06:46 +0000857 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000858 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000859
Chris Lattner98be4942008-03-05 18:54:05 +0000860 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +0000861 uint64_t Size = CAT->getSize().getZExtValue();
862 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) && "Overflow in array type bit size evaluation");
863 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +0000864 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +0000865 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000866 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000867 }
Nate Begeman213541a2008-04-18 23:10:10 +0000868 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000869 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000870 const VectorType *VT = cast<VectorType>(T);
871 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
872 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000873 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000874 // If the alignment is not a power of 2, round up to the next power of 2.
875 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000876 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000877 Align = llvm::NextPowerOf2(Align);
878 Width = llvm::RoundUpToAlignment(Width, Align);
879 }
Chris Lattner030d8842007-07-19 22:06:24 +0000880 break;
881 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000882
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000883 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000884 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000885 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000886 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000887 // GCC extension: alignof(void) = 8 bits.
888 Width = 0;
889 Align = 8;
890 break;
891
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000892 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000893 Width = Target->getBoolWidth();
894 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000895 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000896 case BuiltinType::Char_S:
897 case BuiltinType::Char_U:
898 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000899 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000900 Width = Target->getCharWidth();
901 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000902 break;
Chris Lattner3f59c972010-12-25 23:25:43 +0000903 case BuiltinType::WChar_S:
904 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000905 Width = Target->getWCharWidth();
906 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000907 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000908 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000909 Width = Target->getChar16Width();
910 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000911 break;
912 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000913 Width = Target->getChar32Width();
914 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000915 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000916 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000917 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000918 Width = Target->getShortWidth();
919 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000920 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000921 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000922 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000923 Width = Target->getIntWidth();
924 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000925 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000926 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000927 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000928 Width = Target->getLongWidth();
929 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000930 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000931 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000932 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000933 Width = Target->getLongLongWidth();
934 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000935 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000936 case BuiltinType::Int128:
937 case BuiltinType::UInt128:
938 Width = 128;
939 Align = 128; // int128_t is 128-bit aligned on all targets.
940 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000941 case BuiltinType::Half:
942 Width = Target->getHalfWidth();
943 Align = Target->getHalfAlign();
944 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000945 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000946 Width = Target->getFloatWidth();
947 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000948 break;
949 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000950 Width = Target->getDoubleWidth();
951 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000952 break;
953 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000954 Width = Target->getLongDoubleWidth();
955 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000956 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000957 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000958 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
959 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000960 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000961 case BuiltinType::ObjCId:
962 case BuiltinType::ObjCClass:
963 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000964 Width = Target->getPointerWidth(0);
965 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000966 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000967 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000968 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000969 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000970 Width = Target->getPointerWidth(0);
971 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000972 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000973 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000974 unsigned AS = getTargetAddressSpace(
975 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000976 Width = Target->getPointerWidth(AS);
977 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +0000978 break;
979 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000980 case Type::LValueReference:
981 case Type::RValueReference: {
982 // alignof and sizeof should never enter this code path here, so we go
983 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000984 unsigned AS = getTargetAddressSpace(
985 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000986 Width = Target->getPointerWidth(AS);
987 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +0000988 break;
989 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000990 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000991 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000992 Width = Target->getPointerWidth(AS);
993 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000994 break;
995 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000996 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +0000997 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000998 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000999 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +00001000 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001001 Align = PtrDiffInfo.second;
1002 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001003 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001004 case Type::Complex: {
1005 // Complex types have the same alignment as their elements, but twice the
1006 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001007 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001008 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001009 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001010 Align = EltInfo.second;
1011 break;
1012 }
John McCallc12c5bb2010-05-15 11:32:37 +00001013 case Type::ObjCObject:
1014 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001015 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001016 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001017 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001018 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001019 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001020 break;
1021 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001022 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001023 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001024 const TagType *TT = cast<TagType>(T);
1025
1026 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001027 Width = 8;
1028 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001029 break;
1030 }
Mike Stump1eb44332009-09-09 15:08:12 +00001031
Daniel Dunbar1d751182008-11-08 05:48:37 +00001032 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001033 return getTypeInfo(ET->getDecl()->getIntegerType());
1034
Daniel Dunbar1d751182008-11-08 05:48:37 +00001035 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001036 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001037 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001038 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001039 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001040 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001041
Chris Lattner9fcfe922009-10-22 05:17:15 +00001042 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001043 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1044 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001045
Richard Smith34b41d92011-02-20 03:19:35 +00001046 case Type::Auto: {
1047 const AutoType *A = cast<AutoType>(T);
1048 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001049 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001050 }
1051
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001052 case Type::Paren:
1053 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1054
Douglas Gregor18857642009-04-30 17:32:17 +00001055 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001056 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001057 std::pair<uint64_t, unsigned> Info
1058 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001059 // If the typedef has an aligned attribute on it, it overrides any computed
1060 // alignment we have. This violates the GCC documentation (which says that
1061 // attribute(aligned) can only round up) but matches its implementation.
1062 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1063 Align = AttrAlign;
1064 else
1065 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001066 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001067 break;
Chris Lattner71763312008-04-06 22:05:18 +00001068 }
Douglas Gregor18857642009-04-30 17:32:17 +00001069
1070 case Type::TypeOfExpr:
1071 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1072 .getTypePtr());
1073
1074 case Type::TypeOf:
1075 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1076
Anders Carlsson395b4752009-06-24 19:06:50 +00001077 case Type::Decltype:
1078 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1079 .getTypePtr());
1080
Sean Huntca63c202011-05-24 22:41:36 +00001081 case Type::UnaryTransform:
1082 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1083
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001084 case Type::Elaborated:
1085 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001086
John McCall9d156a72011-01-06 01:58:22 +00001087 case Type::Attributed:
1088 return getTypeInfo(
1089 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1090
Richard Smith3e4c6c42011-05-05 21:57:07 +00001091 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001092 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001093 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001094 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1095 // A type alias template specialization may refer to a typedef with the
1096 // aligned attribute on it.
1097 if (TST->isTypeAlias())
1098 return getTypeInfo(TST->getAliasedType().getTypePtr());
1099 else
1100 return getTypeInfo(getCanonicalType(T));
1101 }
1102
Eli Friedmanb001de72011-10-06 23:00:33 +00001103 case Type::Atomic: {
Eli Friedman2be46072011-10-14 20:59:01 +00001104 std::pair<uint64_t, unsigned> Info
1105 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1106 Width = Info.first;
1107 Align = Info.second;
1108 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1109 llvm::isPowerOf2_64(Width)) {
1110 // We can potentially perform lock-free atomic operations for this
1111 // type; promote the alignment appropriately.
1112 // FIXME: We could potentially promote the width here as well...
1113 // is that worthwhile? (Non-struct atomic types generally have
1114 // power-of-two size anyway, but structs might not. Requires a bit
1115 // of implementation work to make sure we zero out the extra bits.)
1116 Align = static_cast<unsigned>(Width);
1117 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001118 }
1119
Douglas Gregor18857642009-04-30 17:32:17 +00001120 }
Mike Stump1eb44332009-09-09 15:08:12 +00001121
Eli Friedman2be46072011-10-14 20:59:01 +00001122 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001123 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001124}
1125
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001126/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1127CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1128 return CharUnits::fromQuantity(BitSize / getCharWidth());
1129}
1130
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001131/// toBits - Convert a size in characters to a size in characters.
1132int64_t ASTContext::toBits(CharUnits CharSize) const {
1133 return CharSize.getQuantity() * getCharWidth();
1134}
1135
Ken Dyckbdc601b2009-12-22 14:23:30 +00001136/// getTypeSizeInChars - Return the size of the specified type, in characters.
1137/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001138CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001139 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001140}
Jay Foad4ba2a172011-01-12 09:06:06 +00001141CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001142 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001143}
1144
Ken Dyck16e20cc2010-01-26 17:25:18 +00001145/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001146/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001147CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001148 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001149}
Jay Foad4ba2a172011-01-12 09:06:06 +00001150CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001151 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001152}
1153
Chris Lattner34ebde42009-01-27 18:08:34 +00001154/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1155/// type for the current target in bits. This can be different than the ABI
1156/// alignment in cases where it is beneficial for performance to overalign
1157/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001158unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001159 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001160
1161 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001162 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001163 T = CT->getElementType().getTypePtr();
1164 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1165 T->isSpecificBuiltinType(BuiltinType::LongLong))
1166 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1167
Chris Lattner34ebde42009-01-27 18:08:34 +00001168 return ABIAlign;
1169}
1170
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001171/// DeepCollectObjCIvars -
1172/// This routine first collects all declared, but not synthesized, ivars in
1173/// super class and then collects all ivars, including those synthesized for
1174/// current class. This routine is used for implementation of current class
1175/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001176///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001177void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1178 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001179 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001180 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1181 DeepCollectObjCIvars(SuperClass, false, Ivars);
1182 if (!leafClass) {
1183 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1184 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanian11062e12010-02-19 00:31:17 +00001185 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001186 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001187 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001188 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001189 Iv= Iv->getNextIvar())
1190 Ivars.push_back(Iv);
1191 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001192}
1193
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001194/// CollectInheritedProtocols - Collect all protocols in current class and
1195/// those inherited by it.
1196void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001197 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001198 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001199 // We can use protocol_iterator here instead of
1200 // all_referenced_protocol_iterator since we are walking all categories.
1201 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1202 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001203 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001204 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001205 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001206 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001207 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001208 CollectInheritedProtocols(*P, Protocols);
1209 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001210 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001211
1212 // Categories of this Interface.
1213 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1214 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1215 CollectInheritedProtocols(CDeclChain, Protocols);
1216 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1217 while (SD) {
1218 CollectInheritedProtocols(SD, Protocols);
1219 SD = SD->getSuperClass();
1220 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001221 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001222 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001223 PE = OC->protocol_end(); P != PE; ++P) {
1224 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001225 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001226 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1227 PE = Proto->protocol_end(); P != PE; ++P)
1228 CollectInheritedProtocols(*P, Protocols);
1229 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001230 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001231 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1232 PE = OP->protocol_end(); P != PE; ++P) {
1233 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001234 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001235 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1236 PE = Proto->protocol_end(); P != PE; ++P)
1237 CollectInheritedProtocols(*P, Protocols);
1238 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001239 }
1240}
1241
Jay Foad4ba2a172011-01-12 09:06:06 +00001242unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001243 unsigned count = 0;
1244 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001245 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1246 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001247 count += CDecl->ivar_size();
1248
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001249 // Count ivar defined in this class's implementation. This
1250 // includes synthesized ivars.
1251 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001252 count += ImplDecl->ivar_size();
1253
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001254 return count;
1255}
1256
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001257bool ASTContext::isSentinelNullExpr(const Expr *E) {
1258 if (!E)
1259 return false;
1260
1261 // nullptr_t is always treated as null.
1262 if (E->getType()->isNullPtrType()) return true;
1263
1264 if (E->getType()->isAnyPointerType() &&
1265 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1266 Expr::NPC_ValueDependentIsNull))
1267 return true;
1268
1269 // Unfortunately, __null has type 'int'.
1270 if (isa<GNUNullExpr>(E)) return true;
1271
1272 return false;
1273}
1274
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001275/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1276ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1277 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1278 I = ObjCImpls.find(D);
1279 if (I != ObjCImpls.end())
1280 return cast<ObjCImplementationDecl>(I->second);
1281 return 0;
1282}
1283/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1284ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1285 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1286 I = ObjCImpls.find(D);
1287 if (I != ObjCImpls.end())
1288 return cast<ObjCCategoryImplDecl>(I->second);
1289 return 0;
1290}
1291
1292/// \brief Set the implementation of ObjCInterfaceDecl.
1293void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1294 ObjCImplementationDecl *ImplD) {
1295 assert(IFaceD && ImplD && "Passed null params");
1296 ObjCImpls[IFaceD] = ImplD;
1297}
1298/// \brief Set the implementation of ObjCCategoryDecl.
1299void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1300 ObjCCategoryImplDecl *ImplD) {
1301 assert(CatD && ImplD && "Passed null params");
1302 ObjCImpls[CatD] = ImplD;
1303}
1304
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001305ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1306 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1307 return ID;
1308 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1309 return CD->getClassInterface();
1310 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1311 return IMD->getClassInterface();
1312
1313 return 0;
1314}
1315
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001316/// \brief Get the copy initialization expression of VarDecl,or NULL if
1317/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001318Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001319 assert(VD && "Passed null params");
1320 assert(VD->hasAttr<BlocksAttr>() &&
1321 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001322 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001323 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001324 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1325}
1326
1327/// \brief Set the copy inialization expression of a block var decl.
1328void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1329 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001330 assert(VD->hasAttr<BlocksAttr>() &&
1331 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001332 BlockVarCopyInits[VD] = Init;
1333}
1334
John McCalla93c9342009-12-07 02:54:59 +00001335/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001336///
John McCalla93c9342009-12-07 02:54:59 +00001337/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001338/// the TypeLoc wrappers.
1339///
1340/// \param T the type that will be the basis for type source info. This type
1341/// should refer to how the declarator was written in source code, not to
1342/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001343TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001344 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001345 if (!DataSize)
1346 DataSize = TypeLoc::getFullDataSizeForType(T);
1347 else
1348 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001349 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001350
John McCalla93c9342009-12-07 02:54:59 +00001351 TypeSourceInfo *TInfo =
1352 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1353 new (TInfo) TypeSourceInfo(T);
1354 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001355}
1356
John McCalla93c9342009-12-07 02:54:59 +00001357TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001358 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001359 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001360 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001361 return DI;
1362}
1363
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001364const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001365ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001366 return getObjCLayout(D, 0);
1367}
1368
1369const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001370ASTContext::getASTObjCImplementationLayout(
1371 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001372 return getObjCLayout(D->getClassInterface(), D);
1373}
1374
Chris Lattnera7674d82007-07-13 22:13:22 +00001375//===----------------------------------------------------------------------===//
1376// Type creation/memoization methods
1377//===----------------------------------------------------------------------===//
1378
Jay Foad4ba2a172011-01-12 09:06:06 +00001379QualType
John McCall3b657512011-01-19 10:06:00 +00001380ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1381 unsigned fastQuals = quals.getFastQualifiers();
1382 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001383
1384 // Check if we've already instantiated this type.
1385 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001386 ExtQuals::Profile(ID, baseType, quals);
1387 void *insertPos = 0;
1388 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1389 assert(eq->getQualifiers() == quals);
1390 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001391 }
1392
John McCall3b657512011-01-19 10:06:00 +00001393 // If the base type is not canonical, make the appropriate canonical type.
1394 QualType canon;
1395 if (!baseType->isCanonicalUnqualified()) {
1396 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1397 canonSplit.second.addConsistentQualifiers(quals);
1398 canon = getExtQualType(canonSplit.first, canonSplit.second);
1399
1400 // Re-find the insert position.
1401 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1402 }
1403
1404 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1405 ExtQualNodes.InsertNode(eq, insertPos);
1406 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001407}
1408
Jay Foad4ba2a172011-01-12 09:06:06 +00001409QualType
1410ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001411 QualType CanT = getCanonicalType(T);
1412 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001413 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001414
John McCall0953e762009-09-24 19:53:00 +00001415 // If we are composing extended qualifiers together, merge together
1416 // into one ExtQuals node.
1417 QualifierCollector Quals;
1418 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001419
John McCall0953e762009-09-24 19:53:00 +00001420 // If this type already has an address space specified, it cannot get
1421 // another one.
1422 assert(!Quals.hasAddressSpace() &&
1423 "Type cannot be in multiple addr spaces!");
1424 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001425
John McCall0953e762009-09-24 19:53:00 +00001426 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001427}
1428
Chris Lattnerb7d25532009-02-18 22:53:11 +00001429QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001430 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001431 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001432 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001433 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001434
John McCall7f040a92010-12-24 02:08:15 +00001435 if (const PointerType *ptr = T->getAs<PointerType>()) {
1436 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001437 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001438 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1439 return getPointerType(ResultType);
1440 }
1441 }
Mike Stump1eb44332009-09-09 15:08:12 +00001442
John McCall0953e762009-09-24 19:53:00 +00001443 // If we are composing extended qualifiers together, merge together
1444 // into one ExtQuals node.
1445 QualifierCollector Quals;
1446 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001447
John McCall0953e762009-09-24 19:53:00 +00001448 // If this type already has an ObjCGC specified, it cannot get
1449 // another one.
1450 assert(!Quals.hasObjCGCAttr() &&
1451 "Type cannot have multiple ObjCGCs!");
1452 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001453
John McCall0953e762009-09-24 19:53:00 +00001454 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001455}
Chris Lattnera7674d82007-07-13 22:13:22 +00001456
John McCalle6a365d2010-12-19 02:44:49 +00001457const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1458 FunctionType::ExtInfo Info) {
1459 if (T->getExtInfo() == Info)
1460 return T;
1461
1462 QualType Result;
1463 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1464 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1465 } else {
1466 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1467 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1468 EPI.ExtInfo = Info;
1469 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1470 FPT->getNumArgs(), EPI);
1471 }
1472
1473 return cast<FunctionType>(Result.getTypePtr());
1474}
1475
Reid Spencer5f016e22007-07-11 17:01:13 +00001476/// getComplexType - Return the uniqued reference to the type for a complex
1477/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001478QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001479 // Unique pointers, to guarantee there is only one pointer of a particular
1480 // structure.
1481 llvm::FoldingSetNodeID ID;
1482 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001483
Reid Spencer5f016e22007-07-11 17:01:13 +00001484 void *InsertPos = 0;
1485 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1486 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001487
Reid Spencer5f016e22007-07-11 17:01:13 +00001488 // If the pointee type isn't canonical, this won't be a canonical type either,
1489 // so fill in the canonical type field.
1490 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001491 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001492 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001493
Reid Spencer5f016e22007-07-11 17:01:13 +00001494 // Get the new insert position for the node we care about.
1495 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001496 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001497 }
John McCall6b304a02009-09-24 23:30:46 +00001498 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001499 Types.push_back(New);
1500 ComplexTypes.InsertNode(New, InsertPos);
1501 return QualType(New, 0);
1502}
1503
Reid Spencer5f016e22007-07-11 17:01:13 +00001504/// getPointerType - Return the uniqued reference to the type for a pointer to
1505/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001506QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001507 // Unique pointers, to guarantee there is only one pointer of a particular
1508 // structure.
1509 llvm::FoldingSetNodeID ID;
1510 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001511
Reid Spencer5f016e22007-07-11 17:01:13 +00001512 void *InsertPos = 0;
1513 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1514 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001515
Reid Spencer5f016e22007-07-11 17:01:13 +00001516 // If the pointee type isn't canonical, this won't be a canonical type either,
1517 // so fill in the canonical type field.
1518 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001519 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001520 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001521
Reid Spencer5f016e22007-07-11 17:01:13 +00001522 // Get the new insert position for the node we care about.
1523 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001524 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001525 }
John McCall6b304a02009-09-24 23:30:46 +00001526 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001527 Types.push_back(New);
1528 PointerTypes.InsertNode(New, InsertPos);
1529 return QualType(New, 0);
1530}
1531
Mike Stump1eb44332009-09-09 15:08:12 +00001532/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001533/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001534QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001535 assert(T->isFunctionType() && "block of function types only");
1536 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001537 // structure.
1538 llvm::FoldingSetNodeID ID;
1539 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001540
Steve Naroff5618bd42008-08-27 16:04:49 +00001541 void *InsertPos = 0;
1542 if (BlockPointerType *PT =
1543 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1544 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001545
1546 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001547 // type either so fill in the canonical type field.
1548 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001549 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001550 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001551
Steve Naroff5618bd42008-08-27 16:04:49 +00001552 // Get the new insert position for the node we care about.
1553 BlockPointerType *NewIP =
1554 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001555 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001556 }
John McCall6b304a02009-09-24 23:30:46 +00001557 BlockPointerType *New
1558 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001559 Types.push_back(New);
1560 BlockPointerTypes.InsertNode(New, InsertPos);
1561 return QualType(New, 0);
1562}
1563
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001564/// getLValueReferenceType - Return the uniqued reference to the type for an
1565/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001566QualType
1567ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00001568 assert(getCanonicalType(T) != OverloadTy &&
1569 "Unresolved overloaded function type");
1570
Reid Spencer5f016e22007-07-11 17:01:13 +00001571 // Unique pointers, to guarantee there is only one pointer of a particular
1572 // structure.
1573 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001574 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001575
1576 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001577 if (LValueReferenceType *RT =
1578 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001579 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001580
John McCall54e14c42009-10-22 22:37:11 +00001581 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1582
Reid Spencer5f016e22007-07-11 17:01:13 +00001583 // If the referencee type isn't canonical, this won't be a canonical type
1584 // either, so fill in the canonical type field.
1585 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001586 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1587 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1588 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001589
Reid Spencer5f016e22007-07-11 17:01:13 +00001590 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001591 LValueReferenceType *NewIP =
1592 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001593 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001594 }
1595
John McCall6b304a02009-09-24 23:30:46 +00001596 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001597 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1598 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001599 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001600 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001601
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001602 return QualType(New, 0);
1603}
1604
1605/// getRValueReferenceType - Return the uniqued reference to the type for an
1606/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001607QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001608 // Unique pointers, to guarantee there is only one pointer of a particular
1609 // structure.
1610 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001611 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001612
1613 void *InsertPos = 0;
1614 if (RValueReferenceType *RT =
1615 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1616 return QualType(RT, 0);
1617
John McCall54e14c42009-10-22 22:37:11 +00001618 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1619
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001620 // If the referencee type isn't canonical, this won't be a canonical type
1621 // either, so fill in the canonical type field.
1622 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001623 if (InnerRef || !T.isCanonical()) {
1624 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1625 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001626
1627 // Get the new insert position for the node we care about.
1628 RValueReferenceType *NewIP =
1629 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001630 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001631 }
1632
John McCall6b304a02009-09-24 23:30:46 +00001633 RValueReferenceType *New
1634 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001635 Types.push_back(New);
1636 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001637 return QualType(New, 0);
1638}
1639
Sebastian Redlf30208a2009-01-24 21:16:55 +00001640/// getMemberPointerType - Return the uniqued reference to the type for a
1641/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00001642QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001643 // Unique pointers, to guarantee there is only one pointer of a particular
1644 // structure.
1645 llvm::FoldingSetNodeID ID;
1646 MemberPointerType::Profile(ID, T, Cls);
1647
1648 void *InsertPos = 0;
1649 if (MemberPointerType *PT =
1650 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1651 return QualType(PT, 0);
1652
1653 // If the pointee or class type isn't canonical, this won't be a canonical
1654 // type either, so fill in the canonical type field.
1655 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001656 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001657 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1658
1659 // Get the new insert position for the node we care about.
1660 MemberPointerType *NewIP =
1661 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001662 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001663 }
John McCall6b304a02009-09-24 23:30:46 +00001664 MemberPointerType *New
1665 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001666 Types.push_back(New);
1667 MemberPointerTypes.InsertNode(New, InsertPos);
1668 return QualType(New, 0);
1669}
1670
Mike Stump1eb44332009-09-09 15:08:12 +00001671/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001672/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001673QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001674 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001675 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001676 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001677 assert((EltTy->isDependentType() ||
1678 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001679 "Constant array of VLAs is illegal!");
1680
Chris Lattner38aeec72009-05-13 04:12:56 +00001681 // Convert the array size into a canonical width matching the pointer size for
1682 // the target.
1683 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001684 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001685 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00001686
Reid Spencer5f016e22007-07-11 17:01:13 +00001687 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001688 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001689
Reid Spencer5f016e22007-07-11 17:01:13 +00001690 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001691 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001692 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001693 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001694
John McCall3b657512011-01-19 10:06:00 +00001695 // If the element type isn't canonical or has qualifiers, this won't
1696 // be a canonical type either, so fill in the canonical type field.
1697 QualType Canon;
1698 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1699 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1700 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001701 ASM, IndexTypeQuals);
John McCall3b657512011-01-19 10:06:00 +00001702 Canon = getQualifiedType(Canon, canonSplit.second);
1703
Reid Spencer5f016e22007-07-11 17:01:13 +00001704 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001705 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001706 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001707 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001708 }
Mike Stump1eb44332009-09-09 15:08:12 +00001709
John McCall6b304a02009-09-24 23:30:46 +00001710 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001711 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001712 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001713 Types.push_back(New);
1714 return QualType(New, 0);
1715}
1716
John McCallce889032011-01-18 08:40:38 +00001717/// getVariableArrayDecayedType - Turns the given type, which may be
1718/// variably-modified, into the corresponding type with all the known
1719/// sizes replaced with [*].
1720QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1721 // Vastly most common case.
1722 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001723
John McCallce889032011-01-18 08:40:38 +00001724 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001725
John McCallce889032011-01-18 08:40:38 +00001726 SplitQualType split = type.getSplitDesugaredType();
1727 const Type *ty = split.first;
1728 switch (ty->getTypeClass()) {
1729#define TYPE(Class, Base)
1730#define ABSTRACT_TYPE(Class, Base)
1731#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1732#include "clang/AST/TypeNodes.def"
1733 llvm_unreachable("didn't desugar past all non-canonical types?");
1734
1735 // These types should never be variably-modified.
1736 case Type::Builtin:
1737 case Type::Complex:
1738 case Type::Vector:
1739 case Type::ExtVector:
1740 case Type::DependentSizedExtVector:
1741 case Type::ObjCObject:
1742 case Type::ObjCInterface:
1743 case Type::ObjCObjectPointer:
1744 case Type::Record:
1745 case Type::Enum:
1746 case Type::UnresolvedUsing:
1747 case Type::TypeOfExpr:
1748 case Type::TypeOf:
1749 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00001750 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00001751 case Type::DependentName:
1752 case Type::InjectedClassName:
1753 case Type::TemplateSpecialization:
1754 case Type::DependentTemplateSpecialization:
1755 case Type::TemplateTypeParm:
1756 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00001757 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00001758 case Type::PackExpansion:
1759 llvm_unreachable("type should never be variably-modified");
1760
1761 // These types can be variably-modified but should never need to
1762 // further decay.
1763 case Type::FunctionNoProto:
1764 case Type::FunctionProto:
1765 case Type::BlockPointer:
1766 case Type::MemberPointer:
1767 return type;
1768
1769 // These types can be variably-modified. All these modifications
1770 // preserve structure except as noted by comments.
1771 // TODO: if we ever care about optimizing VLAs, there are no-op
1772 // optimizations available here.
1773 case Type::Pointer:
1774 result = getPointerType(getVariableArrayDecayedType(
1775 cast<PointerType>(ty)->getPointeeType()));
1776 break;
1777
1778 case Type::LValueReference: {
1779 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1780 result = getLValueReferenceType(
1781 getVariableArrayDecayedType(lv->getPointeeType()),
1782 lv->isSpelledAsLValue());
1783 break;
1784 }
1785
1786 case Type::RValueReference: {
1787 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1788 result = getRValueReferenceType(
1789 getVariableArrayDecayedType(lv->getPointeeType()));
1790 break;
1791 }
1792
Eli Friedmanb001de72011-10-06 23:00:33 +00001793 case Type::Atomic: {
1794 const AtomicType *at = cast<AtomicType>(ty);
1795 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1796 break;
1797 }
1798
John McCallce889032011-01-18 08:40:38 +00001799 case Type::ConstantArray: {
1800 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1801 result = getConstantArrayType(
1802 getVariableArrayDecayedType(cat->getElementType()),
1803 cat->getSize(),
1804 cat->getSizeModifier(),
1805 cat->getIndexTypeCVRQualifiers());
1806 break;
1807 }
1808
1809 case Type::DependentSizedArray: {
1810 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1811 result = getDependentSizedArrayType(
1812 getVariableArrayDecayedType(dat->getElementType()),
1813 dat->getSizeExpr(),
1814 dat->getSizeModifier(),
1815 dat->getIndexTypeCVRQualifiers(),
1816 dat->getBracketsRange());
1817 break;
1818 }
1819
1820 // Turn incomplete types into [*] types.
1821 case Type::IncompleteArray: {
1822 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1823 result = getVariableArrayType(
1824 getVariableArrayDecayedType(iat->getElementType()),
1825 /*size*/ 0,
1826 ArrayType::Normal,
1827 iat->getIndexTypeCVRQualifiers(),
1828 SourceRange());
1829 break;
1830 }
1831
1832 // Turn VLA types into [*] types.
1833 case Type::VariableArray: {
1834 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1835 result = getVariableArrayType(
1836 getVariableArrayDecayedType(vat->getElementType()),
1837 /*size*/ 0,
1838 ArrayType::Star,
1839 vat->getIndexTypeCVRQualifiers(),
1840 vat->getBracketsRange());
1841 break;
1842 }
1843 }
1844
1845 // Apply the top-level qualifiers from the original.
1846 return getQualifiedType(result, split.second);
1847}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001848
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001849/// getVariableArrayType - Returns a non-unique reference to the type for a
1850/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001851QualType ASTContext::getVariableArrayType(QualType EltTy,
1852 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001853 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001854 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00001855 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001856 // Since we don't unique expressions, it isn't possible to unique VLA's
1857 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00001858 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00001859
John McCall3b657512011-01-19 10:06:00 +00001860 // Be sure to pull qualifiers off the element type.
1861 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1862 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1863 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001864 IndexTypeQuals, Brackets);
John McCall3b657512011-01-19 10:06:00 +00001865 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor715e9c82010-05-23 16:10:32 +00001866 }
1867
John McCall6b304a02009-09-24 23:30:46 +00001868 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001869 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001870
1871 VariableArrayTypes.push_back(New);
1872 Types.push_back(New);
1873 return QualType(New, 0);
1874}
1875
Douglas Gregor898574e2008-12-05 23:32:09 +00001876/// getDependentSizedArrayType - Returns a non-unique reference to
1877/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001878/// type.
John McCall3b657512011-01-19 10:06:00 +00001879QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1880 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00001881 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001882 unsigned elementTypeQuals,
1883 SourceRange brackets) const {
1884 assert((!numElements || numElements->isTypeDependent() ||
1885 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001886 "Size must be type- or value-dependent!");
1887
John McCall3b657512011-01-19 10:06:00 +00001888 // Dependently-sized array types that do not have a specified number
1889 // of elements will have their sizes deduced from a dependent
1890 // initializer. We do no canonicalization here at all, which is okay
1891 // because they can't be used in most locations.
1892 if (!numElements) {
1893 DependentSizedArrayType *newType
1894 = new (*this, TypeAlignment)
1895 DependentSizedArrayType(*this, elementType, QualType(),
1896 numElements, ASM, elementTypeQuals,
1897 brackets);
1898 Types.push_back(newType);
1899 return QualType(newType, 0);
1900 }
1901
1902 // Otherwise, we actually build a new type every time, but we
1903 // also build a canonical type.
1904
1905 SplitQualType canonElementType = getCanonicalType(elementType).split();
1906
1907 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001908 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001909 DependentSizedArrayType::Profile(ID, *this,
1910 QualType(canonElementType.first, 0),
1911 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001912
John McCall3b657512011-01-19 10:06:00 +00001913 // Look for an existing type with these properties.
1914 DependentSizedArrayType *canonTy =
1915 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001916
John McCall3b657512011-01-19 10:06:00 +00001917 // If we don't have one, build one.
1918 if (!canonTy) {
1919 canonTy = new (*this, TypeAlignment)
1920 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1921 QualType(), numElements, ASM, elementTypeQuals,
1922 brackets);
1923 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1924 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001925 }
1926
John McCall3b657512011-01-19 10:06:00 +00001927 // Apply qualifiers from the element type to the array.
1928 QualType canon = getQualifiedType(QualType(canonTy,0),
1929 canonElementType.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001930
John McCall3b657512011-01-19 10:06:00 +00001931 // If we didn't need extra canonicalization for the element type,
1932 // then just use that as our result.
1933 if (QualType(canonElementType.first, 0) == elementType)
1934 return canon;
1935
1936 // Otherwise, we need to build a type which follows the spelling
1937 // of the element type.
1938 DependentSizedArrayType *sugaredType
1939 = new (*this, TypeAlignment)
1940 DependentSizedArrayType(*this, elementType, canon, numElements,
1941 ASM, elementTypeQuals, brackets);
1942 Types.push_back(sugaredType);
1943 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00001944}
1945
John McCall3b657512011-01-19 10:06:00 +00001946QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00001947 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001948 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001949 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001950 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001951
John McCall3b657512011-01-19 10:06:00 +00001952 void *insertPos = 0;
1953 if (IncompleteArrayType *iat =
1954 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1955 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001956
1957 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00001958 // either, so fill in the canonical type field. We also have to pull
1959 // qualifiers off the element type.
1960 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00001961
John McCall3b657512011-01-19 10:06:00 +00001962 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1963 SplitQualType canonSplit = getCanonicalType(elementType).split();
1964 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1965 ASM, elementTypeQuals);
1966 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001967
1968 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00001969 IncompleteArrayType *existing =
1970 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1971 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001972 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001973
John McCall3b657512011-01-19 10:06:00 +00001974 IncompleteArrayType *newType = new (*this, TypeAlignment)
1975 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001976
John McCall3b657512011-01-19 10:06:00 +00001977 IncompleteArrayTypes.InsertNode(newType, insertPos);
1978 Types.push_back(newType);
1979 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001980}
1981
Steve Naroff73322922007-07-18 18:00:27 +00001982/// getVectorType - Return the unique reference to a vector type of
1983/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001984QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00001985 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00001986 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001987
Reid Spencer5f016e22007-07-11 17:01:13 +00001988 // Check if we've already instantiated a vector of this type.
1989 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00001990 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00001991
Reid Spencer5f016e22007-07-11 17:01:13 +00001992 void *InsertPos = 0;
1993 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1994 return QualType(VTP, 0);
1995
1996 // If the element type isn't canonical, this won't be a canonical type either,
1997 // so fill in the canonical type field.
1998 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00001999 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002000 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002001
Reid Spencer5f016e22007-07-11 17:01:13 +00002002 // Get the new insert position for the node we care about.
2003 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002004 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002005 }
John McCall6b304a02009-09-24 23:30:46 +00002006 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002007 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002008 VectorTypes.InsertNode(New, InsertPos);
2009 Types.push_back(New);
2010 return QualType(New, 0);
2011}
2012
Nate Begeman213541a2008-04-18 23:10:10 +00002013/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002014/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002015QualType
2016ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002017 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002018
Steve Naroff73322922007-07-18 18:00:27 +00002019 // Check if we've already instantiated a vector of this type.
2020 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002021 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002022 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002023 void *InsertPos = 0;
2024 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2025 return QualType(VTP, 0);
2026
2027 // If the element type isn't canonical, this won't be a canonical type either,
2028 // so fill in the canonical type field.
2029 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002030 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002031 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002032
Steve Naroff73322922007-07-18 18:00:27 +00002033 // Get the new insert position for the node we care about.
2034 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002035 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002036 }
John McCall6b304a02009-09-24 23:30:46 +00002037 ExtVectorType *New = new (*this, TypeAlignment)
2038 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002039 VectorTypes.InsertNode(New, InsertPos);
2040 Types.push_back(New);
2041 return QualType(New, 0);
2042}
2043
Jay Foad4ba2a172011-01-12 09:06:06 +00002044QualType
2045ASTContext::getDependentSizedExtVectorType(QualType vecType,
2046 Expr *SizeExpr,
2047 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002048 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002049 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002050 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002051
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002052 void *InsertPos = 0;
2053 DependentSizedExtVectorType *Canon
2054 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2055 DependentSizedExtVectorType *New;
2056 if (Canon) {
2057 // We already have a canonical version of this array type; use it as
2058 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002059 New = new (*this, TypeAlignment)
2060 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2061 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002062 } else {
2063 QualType CanonVecTy = getCanonicalType(vecType);
2064 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002065 New = new (*this, TypeAlignment)
2066 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2067 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002068
2069 DependentSizedExtVectorType *CanonCheck
2070 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2071 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2072 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002073 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2074 } else {
2075 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2076 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002077 New = new (*this, TypeAlignment)
2078 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002079 }
2080 }
Mike Stump1eb44332009-09-09 15:08:12 +00002081
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002082 Types.push_back(New);
2083 return QualType(New, 0);
2084}
2085
Douglas Gregor72564e72009-02-26 23:50:07 +00002086/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002087///
Jay Foad4ba2a172011-01-12 09:06:06 +00002088QualType
2089ASTContext::getFunctionNoProtoType(QualType ResultTy,
2090 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002091 const CallingConv DefaultCC = Info.getCC();
2092 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2093 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002094 // Unique functions, to guarantee there is only one function of a particular
2095 // structure.
2096 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002097 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002098
Reid Spencer5f016e22007-07-11 17:01:13 +00002099 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002100 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002101 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002102 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002103
Reid Spencer5f016e22007-07-11 17:01:13 +00002104 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002105 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002106 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002107 Canonical =
2108 getFunctionNoProtoType(getCanonicalType(ResultTy),
2109 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002110
Reid Spencer5f016e22007-07-11 17:01:13 +00002111 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002112 FunctionNoProtoType *NewIP =
2113 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002114 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002115 }
Mike Stump1eb44332009-09-09 15:08:12 +00002116
Roman Divackycfe9af22011-03-01 17:40:53 +00002117 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002118 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002119 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002120 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002121 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002122 return QualType(New, 0);
2123}
2124
2125/// getFunctionType - Return a normal function type with a typed argument
2126/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002127QualType
2128ASTContext::getFunctionType(QualType ResultTy,
2129 const QualType *ArgArray, unsigned NumArgs,
2130 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002131 // Unique functions, to guarantee there is only one function of a particular
2132 // structure.
2133 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002134 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002135
2136 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002137 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002138 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002139 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002140
2141 // Determine whether the type being created is already canonical or not.
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002142 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00002143 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002144 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002145 isCanonical = false;
2146
Roman Divackycfe9af22011-03-01 17:40:53 +00002147 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2148 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2149 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002150
Reid Spencer5f016e22007-07-11 17:01:13 +00002151 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002152 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002153 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002154 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002155 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002156 CanonicalArgs.reserve(NumArgs);
2157 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002158 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002159
John McCalle23cf432010-12-14 08:05:40 +00002160 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002161 CanonicalEPI.ExceptionSpecType = EST_None;
2162 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002163 CanonicalEPI.ExtInfo
2164 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2165
Chris Lattnerf52ab252008-04-06 22:59:24 +00002166 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00002167 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002168 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002169
Reid Spencer5f016e22007-07-11 17:01:13 +00002170 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002171 FunctionProtoType *NewIP =
2172 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002173 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002174 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002175
John McCallf85e1932011-06-15 23:02:42 +00002176 // FunctionProtoType objects are allocated with extra bytes after
2177 // them for three variable size arrays at the end:
2178 // - parameter types
2179 // - exception types
2180 // - consumed-arguments flags
2181 // Instead of the exception types, there could be a noexcept
2182 // expression.
John McCalle23cf432010-12-14 08:05:40 +00002183 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002184 NumArgs * sizeof(QualType);
2185 if (EPI.ExceptionSpecType == EST_Dynamic)
2186 Size += EPI.NumExceptions * sizeof(QualType);
2187 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002188 Size += sizeof(Expr*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002189 }
John McCallf85e1932011-06-15 23:02:42 +00002190 if (EPI.ConsumedArguments)
2191 Size += NumArgs * sizeof(bool);
2192
John McCalle23cf432010-12-14 08:05:40 +00002193 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002194 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2195 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002196 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002197 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002198 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002199 return QualType(FTP, 0);
2200}
2201
John McCall3cb0ebd2010-03-10 03:28:59 +00002202#ifndef NDEBUG
2203static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2204 if (!isa<CXXRecordDecl>(D)) return false;
2205 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2206 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2207 return true;
2208 if (RD->getDescribedClassTemplate() &&
2209 !isa<ClassTemplateSpecializationDecl>(RD))
2210 return true;
2211 return false;
2212}
2213#endif
2214
2215/// getInjectedClassNameType - Return the unique reference to the
2216/// injected class name type for the specified templated declaration.
2217QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002218 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002219 assert(NeedsInjectedClassNameType(Decl));
2220 if (Decl->TypeForDecl) {
2221 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002222 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002223 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2224 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2225 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2226 } else {
John McCallf4c73712011-01-19 06:33:43 +00002227 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002228 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002229 Decl->TypeForDecl = newType;
2230 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002231 }
2232 return QualType(Decl->TypeForDecl, 0);
2233}
2234
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002235/// getTypeDeclType - Return the unique reference to the type for the
2236/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002237QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002238 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002239 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002240
Richard Smith162e1c12011-04-15 14:24:37 +00002241 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002242 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002243
John McCallbecb8d52010-03-10 06:48:02 +00002244 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2245 "Template type parameter types are always available.");
2246
John McCall19c85762010-02-16 03:57:14 +00002247 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002248 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002249 "struct/union has previous declaration");
2250 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002251 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002252 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002253 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002254 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002255 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002256 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002257 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002258 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2259 Decl->TypeForDecl = newType;
2260 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002261 } else
John McCallbecb8d52010-03-10 06:48:02 +00002262 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002263
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002264 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002265}
2266
Reid Spencer5f016e22007-07-11 17:01:13 +00002267/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002268/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002269QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002270ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2271 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002272 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002273
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002274 if (Canonical.isNull())
2275 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002276 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002277 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002278 Decl->TypeForDecl = newType;
2279 Types.push_back(newType);
2280 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002281}
2282
Jay Foad4ba2a172011-01-12 09:06:06 +00002283QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002284 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2285
Douglas Gregoref96ee02012-01-14 16:38:05 +00002286 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002287 if (PrevDecl->TypeForDecl)
2288 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2289
John McCallf4c73712011-01-19 06:33:43 +00002290 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2291 Decl->TypeForDecl = newType;
2292 Types.push_back(newType);
2293 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002294}
2295
Jay Foad4ba2a172011-01-12 09:06:06 +00002296QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002297 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2298
Douglas Gregoref96ee02012-01-14 16:38:05 +00002299 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002300 if (PrevDecl->TypeForDecl)
2301 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2302
John McCallf4c73712011-01-19 06:33:43 +00002303 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2304 Decl->TypeForDecl = newType;
2305 Types.push_back(newType);
2306 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002307}
2308
John McCall9d156a72011-01-06 01:58:22 +00002309QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2310 QualType modifiedType,
2311 QualType equivalentType) {
2312 llvm::FoldingSetNodeID id;
2313 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2314
2315 void *insertPos = 0;
2316 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2317 if (type) return QualType(type, 0);
2318
2319 QualType canon = getCanonicalType(equivalentType);
2320 type = new (*this, TypeAlignment)
2321 AttributedType(canon, attrKind, modifiedType, equivalentType);
2322
2323 Types.push_back(type);
2324 AttributedTypes.InsertNode(type, insertPos);
2325
2326 return QualType(type, 0);
2327}
2328
2329
John McCall49a832b2009-10-18 09:09:24 +00002330/// \brief Retrieve a substitution-result type.
2331QualType
2332ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002333 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002334 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002335 && "replacement types must always be canonical");
2336
2337 llvm::FoldingSetNodeID ID;
2338 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2339 void *InsertPos = 0;
2340 SubstTemplateTypeParmType *SubstParm
2341 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2342
2343 if (!SubstParm) {
2344 SubstParm = new (*this, TypeAlignment)
2345 SubstTemplateTypeParmType(Parm, Replacement);
2346 Types.push_back(SubstParm);
2347 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2348 }
2349
2350 return QualType(SubstParm, 0);
2351}
2352
Douglas Gregorc3069d62011-01-14 02:55:32 +00002353/// \brief Retrieve a
2354QualType ASTContext::getSubstTemplateTypeParmPackType(
2355 const TemplateTypeParmType *Parm,
2356 const TemplateArgument &ArgPack) {
2357#ifndef NDEBUG
2358 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2359 PEnd = ArgPack.pack_end();
2360 P != PEnd; ++P) {
2361 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2362 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2363 }
2364#endif
2365
2366 llvm::FoldingSetNodeID ID;
2367 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2368 void *InsertPos = 0;
2369 if (SubstTemplateTypeParmPackType *SubstParm
2370 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2371 return QualType(SubstParm, 0);
2372
2373 QualType Canon;
2374 if (!Parm->isCanonicalUnqualified()) {
2375 Canon = getCanonicalType(QualType(Parm, 0));
2376 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2377 ArgPack);
2378 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2379 }
2380
2381 SubstTemplateTypeParmPackType *SubstParm
2382 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2383 ArgPack);
2384 Types.push_back(SubstParm);
2385 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2386 return QualType(SubstParm, 0);
2387}
2388
Douglas Gregorfab9d672009-02-05 23:33:38 +00002389/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002390/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002391/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002392QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002393 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002394 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002395 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002396 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002397 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002398 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002399 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2400
2401 if (TypeParm)
2402 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002403
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002404 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002405 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002406 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002407
2408 TemplateTypeParmType *TypeCheck
2409 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2410 assert(!TypeCheck && "Template type parameter canonical type broken");
2411 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002412 } else
John McCall6b304a02009-09-24 23:30:46 +00002413 TypeParm = new (*this, TypeAlignment)
2414 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002415
2416 Types.push_back(TypeParm);
2417 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2418
2419 return QualType(TypeParm, 0);
2420}
2421
John McCall3cb0ebd2010-03-10 03:28:59 +00002422TypeSourceInfo *
2423ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2424 SourceLocation NameLoc,
2425 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002426 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002427 assert(!Name.getAsDependentTemplateName() &&
2428 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002429 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002430
2431 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2432 TemplateSpecializationTypeLoc TL
2433 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2434 TL.setTemplateNameLoc(NameLoc);
2435 TL.setLAngleLoc(Args.getLAngleLoc());
2436 TL.setRAngleLoc(Args.getRAngleLoc());
2437 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2438 TL.setArgLocInfo(i, Args[i].getLocInfo());
2439 return DI;
2440}
2441
Mike Stump1eb44332009-09-09 15:08:12 +00002442QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002443ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002444 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002445 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002446 assert(!Template.getAsDependentTemplateName() &&
2447 "No dependent template names here!");
2448
John McCalld5532b62009-11-23 01:53:49 +00002449 unsigned NumArgs = Args.size();
2450
Chris Lattner5f9e2722011-07-23 10:55:15 +00002451 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002452 ArgVec.reserve(NumArgs);
2453 for (unsigned i = 0; i != NumArgs; ++i)
2454 ArgVec.push_back(Args[i].getArgument());
2455
John McCall31f17ec2010-04-27 00:57:59 +00002456 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002457 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002458}
2459
Douglas Gregorb70126a2012-02-03 17:16:23 +00002460#ifndef NDEBUG
2461static bool hasAnyPackExpansions(const TemplateArgument *Args,
2462 unsigned NumArgs) {
2463 for (unsigned I = 0; I != NumArgs; ++I)
2464 if (Args[I].isPackExpansion())
2465 return true;
2466
2467 return true;
2468}
2469#endif
2470
John McCall833ca992009-10-29 08:12:44 +00002471QualType
2472ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002473 const TemplateArgument *Args,
2474 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002475 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002476 assert(!Template.getAsDependentTemplateName() &&
2477 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002478 // Look through qualified template names.
2479 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2480 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002481
Douglas Gregorb70126a2012-02-03 17:16:23 +00002482 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00002483 Template.getAsTemplateDecl() &&
2484 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00002485 QualType CanonType;
2486 if (!Underlying.isNull())
2487 CanonType = getCanonicalType(Underlying);
2488 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00002489 // We can get here with an alias template when the specialization contains
2490 // a pack expansion that does not match up with a parameter pack.
2491 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2492 "Caller must compute aliased type");
2493 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00002494 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2495 NumArgs);
2496 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002497
Douglas Gregor1275ae02009-07-28 23:00:59 +00002498 // Allocate the (non-canonical) template specialization type, but don't
2499 // try to unique it: these types typically have location information that
2500 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002501 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2502 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00002503 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00002504 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002505 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00002506 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2507 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00002508
Douglas Gregor55f6b142009-02-09 18:46:07 +00002509 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002510 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002511}
2512
Mike Stump1eb44332009-09-09 15:08:12 +00002513QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002514ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2515 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002516 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002517 assert(!Template.getAsDependentTemplateName() &&
2518 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002519
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002520 // Look through qualified template names.
2521 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2522 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002523
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002524 // Build the canonical template specialization type.
2525 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002526 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002527 CanonArgs.reserve(NumArgs);
2528 for (unsigned I = 0; I != NumArgs; ++I)
2529 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2530
2531 // Determine whether this canonical template specialization type already
2532 // exists.
2533 llvm::FoldingSetNodeID ID;
2534 TemplateSpecializationType::Profile(ID, CanonTemplate,
2535 CanonArgs.data(), NumArgs, *this);
2536
2537 void *InsertPos = 0;
2538 TemplateSpecializationType *Spec
2539 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2540
2541 if (!Spec) {
2542 // Allocate a new canonical template specialization type.
2543 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2544 sizeof(TemplateArgument) * NumArgs),
2545 TypeAlignment);
2546 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2547 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002548 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002549 Types.push_back(Spec);
2550 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2551 }
2552
2553 assert(Spec->isDependentType() &&
2554 "Non-dependent template-id type must have a canonical type");
2555 return QualType(Spec, 0);
2556}
2557
2558QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002559ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2560 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002561 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002562 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002563 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002564
2565 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002566 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002567 if (T)
2568 return QualType(T, 0);
2569
Douglas Gregor789b1f62010-02-04 18:10:26 +00002570 QualType Canon = NamedType;
2571 if (!Canon.isCanonical()) {
2572 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002573 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2574 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002575 (void)CheckT;
2576 }
2577
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002578 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002579 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002580 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002581 return QualType(T, 0);
2582}
2583
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002584QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002585ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002586 llvm::FoldingSetNodeID ID;
2587 ParenType::Profile(ID, InnerType);
2588
2589 void *InsertPos = 0;
2590 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2591 if (T)
2592 return QualType(T, 0);
2593
2594 QualType Canon = InnerType;
2595 if (!Canon.isCanonical()) {
2596 Canon = getCanonicalType(InnerType);
2597 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2598 assert(!CheckT && "Paren canonical type broken");
2599 (void)CheckT;
2600 }
2601
2602 T = new (*this) ParenType(InnerType, Canon);
2603 Types.push_back(T);
2604 ParenTypes.InsertNode(T, InsertPos);
2605 return QualType(T, 0);
2606}
2607
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002608QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2609 NestedNameSpecifier *NNS,
2610 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002611 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002612 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2613
2614 if (Canon.isNull()) {
2615 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002616 ElaboratedTypeKeyword CanonKeyword = Keyword;
2617 if (Keyword == ETK_None)
2618 CanonKeyword = ETK_Typename;
2619
2620 if (CanonNNS != NNS || CanonKeyword != Keyword)
2621 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002622 }
2623
2624 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002625 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002626
2627 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002628 DependentNameType *T
2629 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002630 if (T)
2631 return QualType(T, 0);
2632
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002633 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002634 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002635 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002636 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002637}
2638
Mike Stump1eb44332009-09-09 15:08:12 +00002639QualType
John McCall33500952010-06-11 00:33:02 +00002640ASTContext::getDependentTemplateSpecializationType(
2641 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002642 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002643 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002644 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00002645 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00002646 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00002647 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2648 ArgCopy.push_back(Args[I].getArgument());
2649 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2650 ArgCopy.size(),
2651 ArgCopy.data());
2652}
2653
2654QualType
2655ASTContext::getDependentTemplateSpecializationType(
2656 ElaboratedTypeKeyword Keyword,
2657 NestedNameSpecifier *NNS,
2658 const IdentifierInfo *Name,
2659 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002660 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00002661 assert((!NNS || NNS->isDependent()) &&
2662 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00002663
Douglas Gregor789b1f62010-02-04 18:10:26 +00002664 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002665 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2666 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002667
2668 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002669 DependentTemplateSpecializationType *T
2670 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002671 if (T)
2672 return QualType(T, 0);
2673
John McCall33500952010-06-11 00:33:02 +00002674 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002675
John McCall33500952010-06-11 00:33:02 +00002676 ElaboratedTypeKeyword CanonKeyword = Keyword;
2677 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2678
2679 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002680 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00002681 for (unsigned I = 0; I != NumArgs; ++I) {
2682 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2683 if (!CanonArgs[I].structurallyEquals(Args[I]))
2684 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002685 }
2686
John McCall33500952010-06-11 00:33:02 +00002687 QualType Canon;
2688 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2689 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2690 Name, NumArgs,
2691 CanonArgs.data());
2692
2693 // Find the insert position again.
2694 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2695 }
2696
2697 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2698 sizeof(TemplateArgument) * NumArgs),
2699 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002700 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002701 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002702 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002703 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002704 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002705}
2706
Douglas Gregorcded4f62011-01-14 17:04:44 +00002707QualType ASTContext::getPackExpansionType(QualType Pattern,
2708 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00002709 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002710 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002711
2712 assert(Pattern->containsUnexpandedParameterPack() &&
2713 "Pack expansions must expand one or more parameter packs");
2714 void *InsertPos = 0;
2715 PackExpansionType *T
2716 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2717 if (T)
2718 return QualType(T, 0);
2719
2720 QualType Canon;
2721 if (!Pattern.isCanonical()) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002722 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002723
2724 // Find the insert position again.
2725 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2726 }
2727
Douglas Gregorcded4f62011-01-14 17:04:44 +00002728 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002729 Types.push_back(T);
2730 PackExpansionTypes.InsertNode(T, InsertPos);
2731 return QualType(T, 0);
2732}
2733
Chris Lattner88cb27a2008-04-07 04:56:42 +00002734/// CmpProtocolNames - Comparison predicate for sorting protocols
2735/// alphabetically.
2736static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2737 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002738 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002739}
2740
John McCallc12c5bb2010-05-15 11:32:37 +00002741static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002742 unsigned NumProtocols) {
2743 if (NumProtocols == 0) return true;
2744
Douglas Gregor61cc2962012-01-02 02:00:30 +00002745 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2746 return false;
2747
John McCall54e14c42009-10-22 22:37:11 +00002748 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00002749 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2750 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00002751 return false;
2752 return true;
2753}
2754
2755static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002756 unsigned &NumProtocols) {
2757 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002758
Chris Lattner88cb27a2008-04-07 04:56:42 +00002759 // Sort protocols, keyed by name.
2760 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2761
Douglas Gregor61cc2962012-01-02 02:00:30 +00002762 // Canonicalize.
2763 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2764 Protocols[I] = Protocols[I]->getCanonicalDecl();
2765
Chris Lattner88cb27a2008-04-07 04:56:42 +00002766 // Remove duplicates.
2767 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2768 NumProtocols = ProtocolsEnd-Protocols;
2769}
2770
John McCallc12c5bb2010-05-15 11:32:37 +00002771QualType ASTContext::getObjCObjectType(QualType BaseType,
2772 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00002773 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002774 // If the base type is an interface and there aren't any protocols
2775 // to add, then the interface type will do just fine.
2776 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2777 return BaseType;
2778
2779 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002780 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002781 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002782 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002783 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2784 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002785
John McCallc12c5bb2010-05-15 11:32:37 +00002786 // Build the canonical type, which has the canonical base type and
2787 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002788 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002789 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2790 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2791 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002792 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00002793 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002794 unsigned UniqueCount = NumProtocols;
2795
John McCall54e14c42009-10-22 22:37:11 +00002796 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002797 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2798 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002799 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002800 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2801 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002802 }
2803
2804 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002805 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2806 }
2807
2808 unsigned Size = sizeof(ObjCObjectTypeImpl);
2809 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2810 void *Mem = Allocate(Size, TypeAlignment);
2811 ObjCObjectTypeImpl *T =
2812 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2813
2814 Types.push_back(T);
2815 ObjCObjectTypes.InsertNode(T, InsertPos);
2816 return QualType(T, 0);
2817}
2818
2819/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2820/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002821QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002822 llvm::FoldingSetNodeID ID;
2823 ObjCObjectPointerType::Profile(ID, ObjectT);
2824
2825 void *InsertPos = 0;
2826 if (ObjCObjectPointerType *QT =
2827 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2828 return QualType(QT, 0);
2829
2830 // Find the canonical object type.
2831 QualType Canonical;
2832 if (!ObjectT.isCanonical()) {
2833 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2834
2835 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002836 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2837 }
2838
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002839 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002840 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2841 ObjCObjectPointerType *QType =
2842 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002843
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002844 Types.push_back(QType);
2845 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002846 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002847}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002848
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002849/// getObjCInterfaceType - Return the unique reference to the type for the
2850/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00002851QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
2852 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002853 if (Decl->TypeForDecl)
2854 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002855
Douglas Gregor0af55012011-12-16 03:12:41 +00002856 if (PrevDecl) {
2857 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
2858 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2859 return QualType(PrevDecl->TypeForDecl, 0);
2860 }
2861
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00002862 // Prefer the definition, if there is one.
2863 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
2864 Decl = Def;
2865
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002866 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2867 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2868 Decl->TypeForDecl = T;
2869 Types.push_back(T);
2870 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002871}
2872
Douglas Gregor72564e72009-02-26 23:50:07 +00002873/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2874/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002875/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002876/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002877/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002878QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002879 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002880 if (tofExpr->isTypeDependent()) {
2881 llvm::FoldingSetNodeID ID;
2882 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002883
Douglas Gregorb1975722009-07-30 23:18:24 +00002884 void *InsertPos = 0;
2885 DependentTypeOfExprType *Canon
2886 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2887 if (Canon) {
2888 // We already have a "canonical" version of an identical, dependent
2889 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002890 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002891 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00002892 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00002893 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002894 Canon
2895 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002896 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2897 toe = Canon;
2898 }
2899 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002900 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002901 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002902 }
Steve Naroff9752f252007-08-01 18:02:17 +00002903 Types.push_back(toe);
2904 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002905}
2906
Steve Naroff9752f252007-08-01 18:02:17 +00002907/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2908/// TypeOfType AST's. The only motivation to unique these nodes would be
2909/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002910/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002911/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002912QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002913 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002914 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002915 Types.push_back(tot);
2916 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002917}
2918
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002919/// getDecltypeForExpr - Given an expr, will return the decltype for that
2920/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad4ba2a172011-01-12 09:06:06 +00002921static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002922 if (e->isTypeDependent())
2923 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002924
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002925 // If e is an id expression or a class member access, decltype(e) is defined
2926 // as the type of the entity named by e.
2927 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2928 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2929 return VD->getType();
2930 }
2931 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2932 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2933 return FD->getType();
2934 }
2935 // If e is a function call or an invocation of an overloaded operator,
2936 // (parentheses around e are ignored), decltype(e) is defined as the
2937 // return type of that function.
2938 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2939 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002940
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002941 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002942
2943 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002944 // defined as T&, otherwise decltype(e) is defined as T.
John McCall7eb0a9e2010-11-24 05:12:34 +00002945 if (e->isLValue())
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002946 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002947
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002948 return T;
2949}
2950
Anders Carlsson395b4752009-06-24 19:06:50 +00002951/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2952/// DecltypeType AST's. The only motivation to unique these nodes would be
2953/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002954/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00002955/// on canonical types (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002956QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002957 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00002958
2959 // C++0x [temp.type]p2:
2960 // If an expression e involves a template parameter, decltype(e) denotes a
2961 // unique dependent type. Two such decltype-specifiers refer to the same
2962 // type only if their expressions are equivalent (14.5.6.1).
2963 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002964 llvm::FoldingSetNodeID ID;
2965 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002966
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002967 void *InsertPos = 0;
2968 DependentDecltypeType *Canon
2969 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2970 if (Canon) {
2971 // We already have a "canonical" version of an equivalent, dependent
2972 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002973 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002974 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00002975 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002976 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002977 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002978 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2979 dt = Canon;
2980 }
2981 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002982 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002983 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002984 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002985 Types.push_back(dt);
2986 return QualType(dt, 0);
2987}
2988
Sean Huntca63c202011-05-24 22:41:36 +00002989/// getUnaryTransformationType - We don't unique these, since the memory
2990/// savings are minimal and these are rare.
2991QualType ASTContext::getUnaryTransformType(QualType BaseType,
2992 QualType UnderlyingType,
2993 UnaryTransformType::UTTKind Kind)
2994 const {
2995 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00002996 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2997 Kind,
2998 UnderlyingType->isDependentType() ?
2999 QualType() : UnderlyingType);
Sean Huntca63c202011-05-24 22:41:36 +00003000 Types.push_back(Ty);
3001 return QualType(Ty, 0);
3002}
3003
Richard Smith483b9f32011-02-21 20:05:19 +00003004/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00003005QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00003006 void *InsertPos = 0;
3007 if (!DeducedType.isNull()) {
3008 // Look in the folding set for an existing type.
3009 llvm::FoldingSetNodeID ID;
3010 AutoType::Profile(ID, DeducedType);
3011 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3012 return QualType(AT, 0);
3013 }
3014
3015 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3016 Types.push_back(AT);
3017 if (InsertPos)
3018 AutoTypes.InsertNode(AT, InsertPos);
3019 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003020}
3021
Eli Friedmanb001de72011-10-06 23:00:33 +00003022/// getAtomicType - Return the uniqued reference to the atomic type for
3023/// the given value type.
3024QualType ASTContext::getAtomicType(QualType T) const {
3025 // Unique pointers, to guarantee there is only one pointer of a particular
3026 // structure.
3027 llvm::FoldingSetNodeID ID;
3028 AtomicType::Profile(ID, T);
3029
3030 void *InsertPos = 0;
3031 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3032 return QualType(AT, 0);
3033
3034 // If the atomic value type isn't canonical, this won't be a canonical type
3035 // either, so fill in the canonical type field.
3036 QualType Canonical;
3037 if (!T.isCanonical()) {
3038 Canonical = getAtomicType(getCanonicalType(T));
3039
3040 // Get the new insert position for the node we care about.
3041 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3042 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3043 }
3044 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3045 Types.push_back(New);
3046 AtomicTypes.InsertNode(New, InsertPos);
3047 return QualType(New, 0);
3048}
3049
Richard Smithad762fc2011-04-14 22:09:26 +00003050/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3051QualType ASTContext::getAutoDeductType() const {
3052 if (AutoDeductTy.isNull())
3053 AutoDeductTy = getAutoType(QualType());
3054 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3055 return AutoDeductTy;
3056}
3057
3058/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3059QualType ASTContext::getAutoRRefDeductType() const {
3060 if (AutoRRefDeductTy.isNull())
3061 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3062 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3063 return AutoRRefDeductTy;
3064}
3065
Reid Spencer5f016e22007-07-11 17:01:13 +00003066/// getTagDeclType - Return the unique reference to the type for the
3067/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003068QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003069 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003070 // FIXME: What is the design on getTagDeclType when it requires casting
3071 // away const? mutable?
3072 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003073}
3074
Mike Stump1eb44332009-09-09 15:08:12 +00003075/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3076/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3077/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003078CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003079 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003080}
3081
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003082/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3083CanQualType ASTContext::getIntMaxType() const {
3084 return getFromTargetType(Target->getIntMaxType());
3085}
3086
3087/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3088CanQualType ASTContext::getUIntMaxType() const {
3089 return getFromTargetType(Target->getUIntMaxType());
3090}
3091
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003092/// getSignedWCharType - Return the type of "signed wchar_t".
3093/// Used when in C++, as a GCC extension.
3094QualType ASTContext::getSignedWCharType() const {
3095 // FIXME: derive from "Target" ?
3096 return WCharTy;
3097}
3098
3099/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3100/// Used when in C++, as a GCC extension.
3101QualType ASTContext::getUnsignedWCharType() const {
3102 // FIXME: derive from "Target" ?
3103 return UnsignedIntTy;
3104}
3105
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003106/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003107/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3108QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003109 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003110}
3111
Chris Lattnere6327742008-04-02 05:18:44 +00003112//===----------------------------------------------------------------------===//
3113// Type Operators
3114//===----------------------------------------------------------------------===//
3115
Jay Foad4ba2a172011-01-12 09:06:06 +00003116CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003117 // Push qualifiers into arrays, and then discard any remaining
3118 // qualifiers.
3119 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003120 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003121 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003122 QualType Result;
3123 if (isa<ArrayType>(Ty)) {
3124 Result = getArrayDecayedType(QualType(Ty,0));
3125 } else if (isa<FunctionType>(Ty)) {
3126 Result = getPointerType(QualType(Ty, 0));
3127 } else {
3128 Result = QualType(Ty, 0);
3129 }
3130
3131 return CanQualType::CreateUnsafe(Result);
3132}
3133
John McCall62c28c82011-01-18 07:41:22 +00003134QualType ASTContext::getUnqualifiedArrayType(QualType type,
3135 Qualifiers &quals) {
3136 SplitQualType splitType = type.getSplitUnqualifiedType();
3137
3138 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3139 // the unqualified desugared type and then drops it on the floor.
3140 // We then have to strip that sugar back off with
3141 // getUnqualifiedDesugaredType(), which is silly.
3142 const ArrayType *AT =
3143 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
3144
3145 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003146 if (!AT) {
John McCall62c28c82011-01-18 07:41:22 +00003147 quals = splitType.second;
3148 return QualType(splitType.first, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003149 }
3150
John McCall62c28c82011-01-18 07:41:22 +00003151 // Otherwise, recurse on the array's element type.
3152 QualType elementType = AT->getElementType();
3153 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3154
3155 // If that didn't change the element type, AT has no qualifiers, so we
3156 // can just use the results in splitType.
3157 if (elementType == unqualElementType) {
3158 assert(quals.empty()); // from the recursive call
3159 quals = splitType.second;
3160 return QualType(splitType.first, 0);
3161 }
3162
3163 // Otherwise, add in the qualifiers from the outermost type, then
3164 // build the type back up.
3165 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003166
Douglas Gregor9dadd942010-05-17 18:45:21 +00003167 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003168 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003169 CAT->getSizeModifier(), 0);
3170 }
3171
Douglas Gregor9dadd942010-05-17 18:45:21 +00003172 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003173 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003174 }
3175
Douglas Gregor9dadd942010-05-17 18:45:21 +00003176 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003177 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003178 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003179 VAT->getSizeModifier(),
3180 VAT->getIndexTypeCVRQualifiers(),
3181 VAT->getBracketsRange());
3182 }
3183
3184 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003185 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003186 DSAT->getSizeModifier(), 0,
3187 SourceRange());
3188}
3189
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003190/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3191/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3192/// they point to and return true. If T1 and T2 aren't pointer types
3193/// or pointer-to-member types, or if they are not similar at this
3194/// level, returns false and leaves T1 and T2 unchanged. Top-level
3195/// qualifiers on T1 and T2 are ignored. This function will typically
3196/// be called in a loop that successively "unwraps" pointer and
3197/// pointer-to-member types to compare them at each level.
3198bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3199 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3200 *T2PtrType = T2->getAs<PointerType>();
3201 if (T1PtrType && T2PtrType) {
3202 T1 = T1PtrType->getPointeeType();
3203 T2 = T2PtrType->getPointeeType();
3204 return true;
3205 }
3206
3207 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3208 *T2MPType = T2->getAs<MemberPointerType>();
3209 if (T1MPType && T2MPType &&
3210 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3211 QualType(T2MPType->getClass(), 0))) {
3212 T1 = T1MPType->getPointeeType();
3213 T2 = T2MPType->getPointeeType();
3214 return true;
3215 }
3216
3217 if (getLangOptions().ObjC1) {
3218 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3219 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3220 if (T1OPType && T2OPType) {
3221 T1 = T1OPType->getPointeeType();
3222 T2 = T2OPType->getPointeeType();
3223 return true;
3224 }
3225 }
3226
3227 // FIXME: Block pointers, too?
3228
3229 return false;
3230}
3231
Jay Foad4ba2a172011-01-12 09:06:06 +00003232DeclarationNameInfo
3233ASTContext::getNameForTemplate(TemplateName Name,
3234 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003235 switch (Name.getKind()) {
3236 case TemplateName::QualifiedTemplate:
3237 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003238 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003239 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3240 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003241
John McCall14606042011-06-30 08:33:18 +00003242 case TemplateName::OverloadedTemplate: {
3243 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3244 // DNInfo work in progress: CHECKME: what about DNLoc?
3245 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3246 }
3247
3248 case TemplateName::DependentTemplate: {
3249 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003250 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003251 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003252 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3253 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003254 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003255 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3256 // DNInfo work in progress: FIXME: source locations?
3257 DeclarationNameLoc DNLoc;
3258 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3259 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3260 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003261 }
3262 }
3263
John McCall14606042011-06-30 08:33:18 +00003264 case TemplateName::SubstTemplateTemplateParm: {
3265 SubstTemplateTemplateParmStorage *subst
3266 = Name.getAsSubstTemplateTemplateParm();
3267 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3268 NameLoc);
3269 }
3270
3271 case TemplateName::SubstTemplateTemplateParmPack: {
3272 SubstTemplateTemplateParmPackStorage *subst
3273 = Name.getAsSubstTemplateTemplateParmPack();
3274 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3275 NameLoc);
3276 }
3277 }
3278
3279 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003280}
3281
Jay Foad4ba2a172011-01-12 09:06:06 +00003282TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003283 switch (Name.getKind()) {
3284 case TemplateName::QualifiedTemplate:
3285 case TemplateName::Template: {
3286 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003287 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003288 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003289 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3290
3291 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003292 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003293 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003294
John McCall14606042011-06-30 08:33:18 +00003295 case TemplateName::OverloadedTemplate:
3296 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003297
John McCall14606042011-06-30 08:33:18 +00003298 case TemplateName::DependentTemplate: {
3299 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3300 assert(DTN && "Non-dependent template names must refer to template decls.");
3301 return DTN->CanonicalTemplateName;
3302 }
3303
3304 case TemplateName::SubstTemplateTemplateParm: {
3305 SubstTemplateTemplateParmStorage *subst
3306 = Name.getAsSubstTemplateTemplateParm();
3307 return getCanonicalTemplateName(subst->getReplacement());
3308 }
3309
3310 case TemplateName::SubstTemplateTemplateParmPack: {
3311 SubstTemplateTemplateParmPackStorage *subst
3312 = Name.getAsSubstTemplateTemplateParmPack();
3313 TemplateTemplateParmDecl *canonParameter
3314 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3315 TemplateArgument canonArgPack
3316 = getCanonicalTemplateArgument(subst->getArgumentPack());
3317 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3318 }
3319 }
3320
3321 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003322}
3323
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003324bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3325 X = getCanonicalTemplateName(X);
3326 Y = getCanonicalTemplateName(Y);
3327 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3328}
3329
Mike Stump1eb44332009-09-09 15:08:12 +00003330TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003331ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003332 switch (Arg.getKind()) {
3333 case TemplateArgument::Null:
3334 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003335
Douglas Gregor1275ae02009-07-28 23:00:59 +00003336 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003337 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003338
Douglas Gregor1275ae02009-07-28 23:00:59 +00003339 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00003340 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003341
Douglas Gregor788cd062009-11-11 01:00:40 +00003342 case TemplateArgument::Template:
3343 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003344
3345 case TemplateArgument::TemplateExpansion:
3346 return TemplateArgument(getCanonicalTemplateName(
3347 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003348 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003349
Douglas Gregor1275ae02009-07-28 23:00:59 +00003350 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00003351 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003352 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003353
Douglas Gregor1275ae02009-07-28 23:00:59 +00003354 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003355 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003356
Douglas Gregor1275ae02009-07-28 23:00:59 +00003357 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003358 if (Arg.pack_size() == 0)
3359 return Arg;
3360
Douglas Gregor910f8002010-11-07 23:05:16 +00003361 TemplateArgument *CanonArgs
3362 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003363 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003364 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003365 AEnd = Arg.pack_end();
3366 A != AEnd; (void)++A, ++Idx)
3367 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003368
Douglas Gregor910f8002010-11-07 23:05:16 +00003369 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003370 }
3371 }
3372
3373 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00003374 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00003375}
3376
Douglas Gregord57959a2009-03-27 23:10:48 +00003377NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003378ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003379 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003380 return 0;
3381
3382 switch (NNS->getKind()) {
3383 case NestedNameSpecifier::Identifier:
3384 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003385 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003386 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3387 NNS->getAsIdentifier());
3388
3389 case NestedNameSpecifier::Namespace:
3390 // A namespace is canonical; build a nested-name-specifier with
3391 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003392 return NestedNameSpecifier::Create(*this, 0,
3393 NNS->getAsNamespace()->getOriginalNamespace());
3394
3395 case NestedNameSpecifier::NamespaceAlias:
3396 // A namespace is canonical; build a nested-name-specifier with
3397 // this namespace and no prefix.
3398 return NestedNameSpecifier::Create(*this, 0,
3399 NNS->getAsNamespaceAlias()->getNamespace()
3400 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003401
3402 case NestedNameSpecifier::TypeSpec:
3403 case NestedNameSpecifier::TypeSpecWithTemplate: {
3404 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003405
3406 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3407 // break it apart into its prefix and identifier, then reconsititute those
3408 // as the canonical nested-name-specifier. This is required to canonicalize
3409 // a dependent nested-name-specifier involving typedefs of dependent-name
3410 // types, e.g.,
3411 // typedef typename T::type T1;
3412 // typedef typename T1::type T2;
3413 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3414 NestedNameSpecifier *Prefix
3415 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3416 return NestedNameSpecifier::Create(*this, Prefix,
3417 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3418 }
3419
Douglas Gregor643f8432010-11-04 00:14:23 +00003420 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor264bf662010-11-04 00:09:33 +00003421 if (const DependentTemplateSpecializationType *DTST
3422 = T->getAs<DependentTemplateSpecializationType>()) {
3423 NestedNameSpecifier *Prefix
3424 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003425
3426 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3427 Prefix, DTST->getIdentifier(),
3428 DTST->getNumArgs(),
3429 DTST->getArgs());
Douglas Gregor264bf662010-11-04 00:09:33 +00003430 T = getCanonicalType(T);
3431 }
3432
John McCall3b657512011-01-19 10:06:00 +00003433 return NestedNameSpecifier::Create(*this, 0, false,
3434 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003435 }
3436
3437 case NestedNameSpecifier::Global:
3438 // The global specifier is canonical and unique.
3439 return NNS;
3440 }
3441
David Blaikie7530c032012-01-17 06:56:22 +00003442 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00003443}
3444
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003445
Jay Foad4ba2a172011-01-12 09:06:06 +00003446const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003447 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003448 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003449 // Handle the common positive case fast.
3450 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3451 return AT;
3452 }
Mike Stump1eb44332009-09-09 15:08:12 +00003453
John McCall0953e762009-09-24 19:53:00 +00003454 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003455 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003456 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003457
John McCall0953e762009-09-24 19:53:00 +00003458 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003459 // implements C99 6.7.3p8: "If the specification of an array type includes
3460 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003461
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003462 // If we get here, we either have type qualifiers on the type, or we have
3463 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003464 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003465
John McCall3b657512011-01-19 10:06:00 +00003466 SplitQualType split = T.getSplitDesugaredType();
3467 Qualifiers qs = split.second;
Mike Stump1eb44332009-09-09 15:08:12 +00003468
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003469 // If we have a simple case, just return now.
John McCall3b657512011-01-19 10:06:00 +00003470 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3471 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003472 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003473
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003474 // Otherwise, we have an array and we have qualifiers on it. Push the
3475 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003476 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003477
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003478 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3479 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3480 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003481 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003482 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3483 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3484 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003485 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003486
Mike Stump1eb44332009-09-09 15:08:12 +00003487 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003488 = dyn_cast<DependentSizedArrayType>(ATy))
3489 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003490 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003491 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003492 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003493 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003494 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003495
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003496 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003497 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003498 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003499 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003500 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003501 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003502}
3503
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003504QualType ASTContext::getAdjustedParameterType(QualType T) {
3505 // C99 6.7.5.3p7:
3506 // A declaration of a parameter as "array of type" shall be
3507 // adjusted to "qualified pointer to type", where the type
3508 // qualifiers (if any) are those specified within the [ and ] of
3509 // the array type derivation.
3510 if (T->isArrayType())
3511 return getArrayDecayedType(T);
3512
3513 // C99 6.7.5.3p8:
3514 // A declaration of a parameter as "function returning type"
3515 // shall be adjusted to "pointer to function returning type", as
3516 // in 6.3.2.1.
3517 if (T->isFunctionType())
3518 return getPointerType(T);
3519
3520 return T;
3521}
3522
3523QualType ASTContext::getSignatureParameterType(QualType T) {
3524 T = getVariableArrayDecayedType(T);
3525 T = getAdjustedParameterType(T);
3526 return T.getUnqualifiedType();
3527}
3528
Chris Lattnere6327742008-04-02 05:18:44 +00003529/// getArrayDecayedType - Return the properly qualified result of decaying the
3530/// specified array type to a pointer. This operation is non-trivial when
3531/// handling typedefs etc. The canonical type of "T" must be an array type,
3532/// this returns a pointer to a properly qualified element of the array.
3533///
3534/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003535QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003536 // Get the element type with 'getAsArrayType' so that we don't lose any
3537 // typedefs in the element type of the array. This also handles propagation
3538 // of type qualifiers from the array type into the element type if present
3539 // (C99 6.7.3p8).
3540 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3541 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003542
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003543 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003544
3545 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003546 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003547}
3548
John McCall3b657512011-01-19 10:06:00 +00003549QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3550 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003551}
3552
John McCall3b657512011-01-19 10:06:00 +00003553QualType ASTContext::getBaseElementType(QualType type) const {
3554 Qualifiers qs;
3555 while (true) {
3556 SplitQualType split = type.getSplitDesugaredType();
3557 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3558 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003559
John McCall3b657512011-01-19 10:06:00 +00003560 type = array->getElementType();
3561 qs.addConsistentQualifiers(split.second);
3562 }
Mike Stump1eb44332009-09-09 15:08:12 +00003563
John McCall3b657512011-01-19 10:06:00 +00003564 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003565}
3566
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003567/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003568uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003569ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3570 uint64_t ElementCount = 1;
3571 do {
3572 ElementCount *= CA->getSize().getZExtValue();
3573 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3574 } while (CA);
3575 return ElementCount;
3576}
3577
Reid Spencer5f016e22007-07-11 17:01:13 +00003578/// getFloatingRank - Return a relative rank for floating point types.
3579/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003580static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003581 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003582 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003583
John McCall183700f2009-09-21 23:43:11 +00003584 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3585 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003586 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00003587 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00003588 case BuiltinType::Float: return FloatRank;
3589 case BuiltinType::Double: return DoubleRank;
3590 case BuiltinType::LongDouble: return LongDoubleRank;
3591 }
3592}
3593
Mike Stump1eb44332009-09-09 15:08:12 +00003594/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3595/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003596/// 'typeDomain' is a real floating point or complex type.
3597/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003598QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3599 QualType Domain) const {
3600 FloatingRank EltRank = getFloatingRank(Size);
3601 if (Domain->isComplexType()) {
3602 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00003603 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00003604 case FloatRank: return FloatComplexTy;
3605 case DoubleRank: return DoubleComplexTy;
3606 case LongDoubleRank: return LongDoubleComplexTy;
3607 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003608 }
Chris Lattner1361b112008-04-06 23:58:54 +00003609
3610 assert(Domain->isRealFloatingType() && "Unknown domain!");
3611 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00003612 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattner1361b112008-04-06 23:58:54 +00003613 case FloatRank: return FloatTy;
3614 case DoubleRank: return DoubleTy;
3615 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003616 }
David Blaikie561d3ab2012-01-17 02:30:50 +00003617 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00003618}
3619
Chris Lattner7cfeb082008-04-06 23:55:33 +00003620/// getFloatingTypeOrder - Compare the rank of the two specified floating
3621/// point types, ignoring the domain of the type (i.e. 'double' ==
3622/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003623/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003624int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003625 FloatingRank LHSR = getFloatingRank(LHS);
3626 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003627
Chris Lattnera75cea32008-04-06 23:38:49 +00003628 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003629 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003630 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003631 return 1;
3632 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003633}
3634
Chris Lattnerf52ab252008-04-06 22:59:24 +00003635/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3636/// routine will assert if passed a built-in type that isn't an integer or enum,
3637/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003638unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003639 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003640
Chris Lattnerf52ab252008-04-06 22:59:24 +00003641 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003642 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00003643 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003644 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003645 case BuiltinType::Char_S:
3646 case BuiltinType::Char_U:
3647 case BuiltinType::SChar:
3648 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003649 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003650 case BuiltinType::Short:
3651 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003652 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003653 case BuiltinType::Int:
3654 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003655 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003656 case BuiltinType::Long:
3657 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003658 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003659 case BuiltinType::LongLong:
3660 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003661 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003662 case BuiltinType::Int128:
3663 case BuiltinType::UInt128:
3664 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003665 }
3666}
3667
Eli Friedman04e83572009-08-20 04:21:42 +00003668/// \brief Whether this is a promotable bitfield reference according
3669/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3670///
3671/// \returns the type this bit-field will promote to, or NULL if no
3672/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00003673QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003674 if (E->isTypeDependent() || E->isValueDependent())
3675 return QualType();
3676
Eli Friedman04e83572009-08-20 04:21:42 +00003677 FieldDecl *Field = E->getBitField();
3678 if (!Field)
3679 return QualType();
3680
3681 QualType FT = Field->getType();
3682
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003683 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00003684 uint64_t IntSize = getTypeSize(IntTy);
3685 // GCC extension compatibility: if the bit-field size is less than or equal
3686 // to the size of int, it gets promoted no matter what its type is.
3687 // For instance, unsigned long bf : 4 gets promoted to signed int.
3688 if (BitWidth < IntSize)
3689 return IntTy;
3690
3691 if (BitWidth == IntSize)
3692 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3693
3694 // Types bigger than int are not subject to promotions, and therefore act
3695 // like the base type.
3696 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3697 // is ridiculous.
3698 return QualType();
3699}
3700
Eli Friedmana95d7572009-08-19 07:44:53 +00003701/// getPromotedIntegerType - Returns the type that Promotable will
3702/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3703/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003704QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003705 assert(!Promotable.isNull());
3706 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003707 if (const EnumType *ET = Promotable->getAs<EnumType>())
3708 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00003709
3710 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3711 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3712 // (3.9.1) can be converted to a prvalue of the first of the following
3713 // types that can represent all the values of its underlying type:
3714 // int, unsigned int, long int, unsigned long int, long long int, or
3715 // unsigned long long int [...]
3716 // FIXME: Is there some better way to compute this?
3717 if (BT->getKind() == BuiltinType::WChar_S ||
3718 BT->getKind() == BuiltinType::WChar_U ||
3719 BT->getKind() == BuiltinType::Char16 ||
3720 BT->getKind() == BuiltinType::Char32) {
3721 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3722 uint64_t FromSize = getTypeSize(BT);
3723 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3724 LongLongTy, UnsignedLongLongTy };
3725 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3726 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3727 if (FromSize < ToSize ||
3728 (FromSize == ToSize &&
3729 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3730 return PromoteTypes[Idx];
3731 }
3732 llvm_unreachable("char type should fit into long long");
3733 }
3734 }
3735
3736 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00003737 if (Promotable->isSignedIntegerType())
3738 return IntTy;
3739 uint64_t PromotableSize = getTypeSize(Promotable);
3740 uint64_t IntSize = getTypeSize(IntTy);
3741 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3742 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3743}
3744
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003745/// \brief Recurses in pointer/array types until it finds an objc retainable
3746/// type and returns its ownership.
3747Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3748 while (!T.isNull()) {
3749 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3750 return T.getObjCLifetime();
3751 if (T->isArrayType())
3752 T = getBaseElementType(T);
3753 else if (const PointerType *PT = T->getAs<PointerType>())
3754 T = PT->getPointeeType();
3755 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00003756 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003757 else
3758 break;
3759 }
3760
3761 return Qualifiers::OCL_None;
3762}
3763
Mike Stump1eb44332009-09-09 15:08:12 +00003764/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003765/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003766/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003767int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00003768 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3769 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003770 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003771
Chris Lattnerf52ab252008-04-06 22:59:24 +00003772 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3773 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003774
Chris Lattner7cfeb082008-04-06 23:55:33 +00003775 unsigned LHSRank = getIntegerRank(LHSC);
3776 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003777
Chris Lattner7cfeb082008-04-06 23:55:33 +00003778 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3779 if (LHSRank == RHSRank) return 0;
3780 return LHSRank > RHSRank ? 1 : -1;
3781 }
Mike Stump1eb44332009-09-09 15:08:12 +00003782
Chris Lattner7cfeb082008-04-06 23:55:33 +00003783 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3784 if (LHSUnsigned) {
3785 // If the unsigned [LHS] type is larger, return it.
3786 if (LHSRank >= RHSRank)
3787 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003788
Chris Lattner7cfeb082008-04-06 23:55:33 +00003789 // If the signed type can represent all values of the unsigned type, it
3790 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003791 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003792 return -1;
3793 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003794
Chris Lattner7cfeb082008-04-06 23:55:33 +00003795 // If the unsigned [RHS] type is larger, return it.
3796 if (RHSRank >= LHSRank)
3797 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003798
Chris Lattner7cfeb082008-04-06 23:55:33 +00003799 // If the signed type can represent all values of the unsigned type, it
3800 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003801 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003802 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003803}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003804
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003805static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003806CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3807 DeclContext *DC, IdentifierInfo *Id) {
3808 SourceLocation Loc;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003809 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003810 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003811 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003812 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003813}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003814
Mike Stump1eb44332009-09-09 15:08:12 +00003815// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003816QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003817 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003818 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003819 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003820 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003821 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003822
Anders Carlssonf06273f2007-11-19 00:25:30 +00003823 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003824
Anders Carlsson71993dd2007-08-17 05:31:46 +00003825 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003826 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003827 // int flags;
3828 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003829 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003830 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003831 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003832 FieldTypes[3] = LongTy;
3833
Anders Carlsson71993dd2007-08-17 05:31:46 +00003834 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003835 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003836 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003837 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00003838 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003839 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003840 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003841 /*Mutable=*/false,
3842 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003843 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003844 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003845 }
3846
Douglas Gregor838db382010-02-11 01:19:42 +00003847 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003848 }
Mike Stump1eb44332009-09-09 15:08:12 +00003849
Anders Carlsson71993dd2007-08-17 05:31:46 +00003850 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003851}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003852
Douglas Gregor319ac892009-04-23 22:29:11 +00003853void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003854 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003855 assert(Rec && "Invalid CFConstantStringType");
3856 CFConstantStringTypeDecl = Rec->getDecl();
3857}
3858
Jay Foad4ba2a172011-01-12 09:06:06 +00003859QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00003860 if (BlockDescriptorType)
3861 return getTagDeclType(BlockDescriptorType);
3862
3863 RecordDecl *T;
3864 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003865 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003866 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003867 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003868
3869 QualType FieldTypes[] = {
3870 UnsignedLongTy,
3871 UnsignedLongTy,
3872 };
3873
3874 const char *FieldNames[] = {
3875 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003876 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003877 };
3878
3879 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003880 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003881 SourceLocation(),
3882 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003883 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003884 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003885 /*Mutable=*/false,
3886 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003887 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003888 T->addDecl(Field);
3889 }
3890
Douglas Gregor838db382010-02-11 01:19:42 +00003891 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003892
3893 BlockDescriptorType = T;
3894
3895 return getTagDeclType(BlockDescriptorType);
3896}
3897
Jay Foad4ba2a172011-01-12 09:06:06 +00003898QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00003899 if (BlockDescriptorExtendedType)
3900 return getTagDeclType(BlockDescriptorExtendedType);
3901
3902 RecordDecl *T;
3903 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003904 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003905 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003906 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003907
3908 QualType FieldTypes[] = {
3909 UnsignedLongTy,
3910 UnsignedLongTy,
3911 getPointerType(VoidPtrTy),
3912 getPointerType(VoidPtrTy)
3913 };
3914
3915 const char *FieldNames[] = {
3916 "reserved",
3917 "Size",
3918 "CopyFuncPtr",
3919 "DestroyFuncPtr"
3920 };
3921
3922 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003923 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00003924 SourceLocation(),
3925 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003926 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003927 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003928 /*Mutable=*/false,
3929 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003930 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003931 T->addDecl(Field);
3932 }
3933
Douglas Gregor838db382010-02-11 01:19:42 +00003934 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003935
3936 BlockDescriptorExtendedType = T;
3937
3938 return getTagDeclType(BlockDescriptorExtendedType);
3939}
3940
Jay Foad4ba2a172011-01-12 09:06:06 +00003941bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCallf85e1932011-06-15 23:02:42 +00003942 if (Ty->isObjCRetainableType())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003943 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003944 if (getLangOptions().CPlusPlus) {
3945 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3946 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Huntffe37fd2011-05-25 20:50:04 +00003947 return RD->hasConstCopyConstructor();
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003948
3949 }
3950 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003951 return false;
3952}
3953
Jay Foad4ba2a172011-01-12 09:06:06 +00003954QualType
Chris Lattner5f9e2722011-07-23 10:55:15 +00003955ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003956 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003957 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003958 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003959 // unsigned int __flags;
3960 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003961 // void *__copy_helper; // as needed
3962 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003963 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003964 // } *
3965
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003966 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3967
3968 // FIXME: Move up
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003969 SmallString<36> Name;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003970 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3971 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003972 RecordDecl *T;
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003973 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003974 T->startDefinition();
3975 QualType Int32Ty = IntTy;
3976 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3977 QualType FieldTypes[] = {
3978 getPointerType(VoidPtrTy),
3979 getPointerType(getTagDeclType(T)),
3980 Int32Ty,
3981 Int32Ty,
3982 getPointerType(VoidPtrTy),
3983 getPointerType(VoidPtrTy),
3984 Ty
3985 };
3986
Chris Lattner5f9e2722011-07-23 10:55:15 +00003987 StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003988 "__isa",
3989 "__forwarding",
3990 "__flags",
3991 "__size",
3992 "__copy_helper",
3993 "__destroy_helper",
3994 DeclName,
3995 };
3996
3997 for (size_t i = 0; i < 7; ++i) {
3998 if (!HasCopyAndDispose && i >=4 && i <= 5)
3999 continue;
4000 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004001 SourceLocation(),
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004002 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004003 FieldTypes[i], /*TInfo=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004004 /*BitWidth=*/0, /*Mutable=*/false,
4005 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00004006 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004007 T->addDecl(Field);
4008 }
4009
Douglas Gregor838db382010-02-11 01:19:42 +00004010 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004011
4012 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00004013}
4014
Douglas Gregore97179c2011-09-08 01:46:34 +00004015TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4016 if (!ObjCInstanceTypeDecl)
4017 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4018 getTranslationUnitDecl(),
4019 SourceLocation(),
4020 SourceLocation(),
4021 &Idents.get("instancetype"),
4022 getTrivialTypeSourceInfo(getObjCIdType()));
4023 return ObjCInstanceTypeDecl;
4024}
4025
Anders Carlssone8c49532007-10-29 06:33:42 +00004026// This returns true if a type has been typedefed to BOOL:
4027// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004028static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004029 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004030 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4031 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004032
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004033 return false;
4034}
4035
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004036/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004037/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004038CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004039 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4040 return CharUnits::Zero();
4041
Ken Dyck199c3d62010-01-11 17:06:35 +00004042 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004043
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004044 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004045 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004046 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004047 // Treat arrays as pointers, since that's how they're passed in.
4048 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004049 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004050 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004051}
4052
4053static inline
4054std::string charUnitsToString(const CharUnits &CU) {
4055 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004056}
4057
John McCall6b5a61b2011-02-07 10:33:21 +00004058/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004059/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004060std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4061 std::string S;
4062
David Chisnall5e530af2009-11-17 19:33:30 +00004063 const BlockDecl *Decl = Expr->getBlockDecl();
4064 QualType BlockTy =
4065 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4066 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00004067 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00004068 // Compute size of all parameters.
4069 // Start with computing size of a pointer in number of bytes.
4070 // FIXME: There might(should) be a better way of doing this computation!
4071 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004072 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4073 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004074 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004075 E = Decl->param_end(); PI != E; ++PI) {
4076 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004077 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00004078 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004079 ParmOffset += sz;
4080 }
4081 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004082 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004083 // Block pointer and offset.
4084 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004085
4086 // Argument types.
4087 ParmOffset = PtrSize;
4088 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4089 Decl->param_end(); PI != E; ++PI) {
4090 ParmVarDecl *PVDecl = *PI;
4091 QualType PType = PVDecl->getOriginalType();
4092 if (const ArrayType *AT =
4093 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4094 // Use array's original type only if it has known number of
4095 // elements.
4096 if (!isa<ConstantArrayType>(AT))
4097 PType = PVDecl->getType();
4098 } else if (PType->isFunctionType())
4099 PType = PVDecl->getType();
4100 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004101 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004102 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004103 }
John McCall6b5a61b2011-02-07 10:33:21 +00004104
4105 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004106}
4107
Douglas Gregorf968d832011-05-27 01:19:52 +00004108bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004109 std::string& S) {
4110 // Encode result type.
4111 getObjCEncodingForType(Decl->getResultType(), S);
4112 CharUnits ParmOffset;
4113 // Compute size of all parameters.
4114 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4115 E = Decl->param_end(); PI != E; ++PI) {
4116 QualType PType = (*PI)->getType();
4117 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004118 if (sz.isZero())
4119 return true;
4120
David Chisnall5389f482010-12-30 14:05:53 +00004121 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004122 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004123 ParmOffset += sz;
4124 }
4125 S += charUnitsToString(ParmOffset);
4126 ParmOffset = CharUnits::Zero();
4127
4128 // Argument types.
4129 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4130 E = Decl->param_end(); PI != E; ++PI) {
4131 ParmVarDecl *PVDecl = *PI;
4132 QualType PType = PVDecl->getOriginalType();
4133 if (const ArrayType *AT =
4134 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4135 // Use array's original type only if it has known number of
4136 // elements.
4137 if (!isa<ConstantArrayType>(AT))
4138 PType = PVDecl->getType();
4139 } else if (PType->isFunctionType())
4140 PType = PVDecl->getType();
4141 getObjCEncodingForType(PType, S);
4142 S += charUnitsToString(ParmOffset);
4143 ParmOffset += getObjCEncodingTypeSize(PType);
4144 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004145
4146 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004147}
4148
Bob Wilsondc8dab62011-11-30 01:57:58 +00004149/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4150/// method parameter or return type. If Extended, include class names and
4151/// block object types.
4152void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4153 QualType T, std::string& S,
4154 bool Extended) const {
4155 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4156 getObjCEncodingForTypeQualifier(QT, S);
4157 // Encode parameter type.
4158 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4159 true /*OutermostType*/,
4160 false /*EncodingProperty*/,
4161 false /*StructField*/,
4162 Extended /*EncodeBlockParameters*/,
4163 Extended /*EncodeClassNames*/);
4164}
4165
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004166/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004167/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004168bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004169 std::string& S,
4170 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004171 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004172 // Encode return type.
4173 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4174 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004175 // Compute size of all parameters.
4176 // Start with computing size of a pointer in number of bytes.
4177 // FIXME: There might(should) be a better way of doing this computation!
4178 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004179 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004180 // The first two arguments (self and _cmd) are pointers; account for
4181 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004182 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004183 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004184 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004185 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004186 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004187 if (sz.isZero())
4188 return true;
4189
Ken Dyck199c3d62010-01-11 17:06:35 +00004190 assert (sz.isPositive() &&
4191 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004192 ParmOffset += sz;
4193 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004194 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004195 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004196 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004197
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004198 // Argument types.
4199 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004200 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004201 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004202 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004203 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004204 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004205 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4206 // Use array's original type only if it has known number of
4207 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004208 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004209 PType = PVDecl->getType();
4210 } else if (PType->isFunctionType())
4211 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004212 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4213 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004214 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004215 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004216 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004217
4218 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004219}
4220
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004221/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004222/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004223/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4224/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004225/// Property attributes are stored as a comma-delimited C string. The simple
4226/// attributes readonly and bycopy are encoded as single characters. The
4227/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4228/// encoded as single characters, followed by an identifier. Property types
4229/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004230/// these attributes are defined by the following enumeration:
4231/// @code
4232/// enum PropertyAttributes {
4233/// kPropertyReadOnly = 'R', // property is read-only.
4234/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4235/// kPropertyByref = '&', // property is a reference to the value last assigned
4236/// kPropertyDynamic = 'D', // property is dynamic
4237/// kPropertyGetter = 'G', // followed by getter selector name
4238/// kPropertySetter = 'S', // followed by setter selector name
4239/// kPropertyInstanceVariable = 'V' // followed by instance variable name
4240/// kPropertyType = 't' // followed by old-style type encoding.
4241/// kPropertyWeak = 'W' // 'weak' property
4242/// kPropertyStrong = 'P' // property GC'able
4243/// kPropertyNonAtomic = 'N' // property non-atomic
4244/// };
4245/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004246void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004247 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004248 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004249 // Collect information from the property implementation decl(s).
4250 bool Dynamic = false;
4251 ObjCPropertyImplDecl *SynthesizePID = 0;
4252
4253 // FIXME: Duplicated code due to poor abstraction.
4254 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004255 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004256 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4257 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004258 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004259 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004260 ObjCPropertyImplDecl *PID = *i;
4261 if (PID->getPropertyDecl() == PD) {
4262 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4263 Dynamic = true;
4264 } else {
4265 SynthesizePID = PID;
4266 }
4267 }
4268 }
4269 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004270 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004271 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004272 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004273 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004274 ObjCPropertyImplDecl *PID = *i;
4275 if (PID->getPropertyDecl() == PD) {
4276 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4277 Dynamic = true;
4278 } else {
4279 SynthesizePID = PID;
4280 }
4281 }
Mike Stump1eb44332009-09-09 15:08:12 +00004282 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004283 }
4284 }
4285
4286 // FIXME: This is not very efficient.
4287 S = "T";
4288
4289 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004290 // GCC has some special rules regarding encoding of properties which
4291 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004292 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004293 true /* outermost type */,
4294 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004295
4296 if (PD->isReadOnly()) {
4297 S += ",R";
4298 } else {
4299 switch (PD->getSetterKind()) {
4300 case ObjCPropertyDecl::Assign: break;
4301 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004302 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004303 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004304 }
4305 }
4306
4307 // It really isn't clear at all what this means, since properties
4308 // are "dynamic by default".
4309 if (Dynamic)
4310 S += ",D";
4311
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004312 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4313 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004314
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004315 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4316 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004317 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004318 }
4319
4320 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4321 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004322 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004323 }
4324
4325 if (SynthesizePID) {
4326 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4327 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004328 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004329 }
4330
4331 // FIXME: OBJCGC: weak & strong
4332}
4333
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004334/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004335/// Another legacy compatibility encoding: 32-bit longs are encoded as
4336/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004337/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4338///
4339void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004340 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004341 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004342 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004343 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004344 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004345 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004346 PointeeTy = IntTy;
4347 }
4348 }
4349}
4350
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004351void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004352 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004353 // We follow the behavior of gcc, expanding structures which are
4354 // directly pointed to, and expanding embedded structures. Note that
4355 // these rules are sufficient to prevent recursive encoding of the
4356 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004357 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004358 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004359}
4360
David Chisnall64fd7e82010-06-04 01:10:52 +00004361static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4362 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004363 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnall64fd7e82010-06-04 01:10:52 +00004364 case BuiltinType::Void: return 'v';
4365 case BuiltinType::Bool: return 'B';
4366 case BuiltinType::Char_U:
4367 case BuiltinType::UChar: return 'C';
4368 case BuiltinType::UShort: return 'S';
4369 case BuiltinType::UInt: return 'I';
4370 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00004371 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004372 case BuiltinType::UInt128: return 'T';
4373 case BuiltinType::ULongLong: return 'Q';
4374 case BuiltinType::Char_S:
4375 case BuiltinType::SChar: return 'c';
4376 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004377 case BuiltinType::WChar_S:
4378 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004379 case BuiltinType::Int: return 'i';
4380 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00004381 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004382 case BuiltinType::LongLong: return 'q';
4383 case BuiltinType::Int128: return 't';
4384 case BuiltinType::Float: return 'f';
4385 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004386 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004387 }
4388}
4389
Douglas Gregor5471bc82011-09-08 17:18:35 +00004390static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4391 EnumDecl *Enum = ET->getDecl();
4392
4393 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4394 if (!Enum->isFixed())
4395 return 'i';
4396
4397 // The encoding of a fixed enum type matches its fixed underlying type.
4398 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4399}
4400
Jay Foad4ba2a172011-01-12 09:06:06 +00004401static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004402 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004403 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004404 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004405 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4406 // The GNU runtime requires more information; bitfields are encoded as b,
4407 // then the offset (in bits) of the first element, then the type of the
4408 // bitfield, then the size in bits. For example, in this structure:
4409 //
4410 // struct
4411 // {
4412 // int integer;
4413 // int flags:2;
4414 // };
4415 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4416 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4417 // information is not especially sensible, but we're stuck with it for
4418 // compatibility with GCC, although providing it breaks anything that
4419 // actually uses runtime introspection and wants to work on both runtimes...
4420 if (!Ctx->getLangOptions().NeXTRuntime) {
4421 const RecordDecl *RD = FD->getParent();
4422 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004423 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00004424 if (const EnumType *ET = T->getAs<EnumType>())
4425 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnallc7ff82c2010-12-26 20:12:30 +00004426 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004427 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004428 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004429 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004430}
4431
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004432// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004433void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4434 bool ExpandPointedToStructures,
4435 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004436 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004437 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004438 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004439 bool StructField,
4440 bool EncodeBlockParameters,
4441 bool EncodeClassNames) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004442 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004443 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004444 return EncodeBitField(this, S, T, FD);
4445 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004446 return;
4447 }
Mike Stump1eb44332009-09-09 15:08:12 +00004448
John McCall183700f2009-09-21 23:43:11 +00004449 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004450 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004451 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004452 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004453 return;
4454 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004455
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004456 // encoding for pointer or r3eference types.
4457 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004458 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004459 if (PT->isObjCSelType()) {
4460 S += ':';
4461 return;
4462 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004463 PointeeTy = PT->getPointeeType();
4464 }
4465 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4466 PointeeTy = RT->getPointeeType();
4467 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004468 bool isReadOnly = false;
4469 // For historical/compatibility reasons, the read-only qualifier of the
4470 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4471 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004472 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004473 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004474 if (OutermostType && T.isConstQualified()) {
4475 isReadOnly = true;
4476 S += 'r';
4477 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004478 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004479 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004480 while (P->getAs<PointerType>())
4481 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004482 if (P.isConstQualified()) {
4483 isReadOnly = true;
4484 S += 'r';
4485 }
4486 }
4487 if (isReadOnly) {
4488 // Another legacy compatibility encoding. Some ObjC qualifier and type
4489 // combinations need to be rearranged.
4490 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00004491 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00004492 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004493 }
Mike Stump1eb44332009-09-09 15:08:12 +00004494
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004495 if (PointeeTy->isCharType()) {
4496 // char pointer types should be encoded as '*' unless it is a
4497 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004498 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004499 S += '*';
4500 return;
4501 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004502 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004503 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4504 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4505 S += '#';
4506 return;
4507 }
4508 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4509 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4510 S += '@';
4511 return;
4512 }
4513 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004514 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004515 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004516 getLegacyIntegralTypeEncoding(PointeeTy);
4517
Mike Stump1eb44332009-09-09 15:08:12 +00004518 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004519 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004520 return;
4521 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004522
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004523 if (const ArrayType *AT =
4524 // Ignore type qualifiers etc.
4525 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004526 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004527 // Incomplete arrays are encoded as a pointer to the array element.
4528 S += '^';
4529
Mike Stump1eb44332009-09-09 15:08:12 +00004530 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004531 false, ExpandStructures, FD);
4532 } else {
4533 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004534
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004535 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4536 if (getTypeSize(CAT->getElementType()) == 0)
4537 S += '0';
4538 else
4539 S += llvm::utostr(CAT->getSize().getZExtValue());
4540 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00004541 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004542 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4543 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00004544 S += '0';
4545 }
Mike Stump1eb44332009-09-09 15:08:12 +00004546
4547 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004548 false, ExpandStructures, FD);
4549 S += ']';
4550 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004551 return;
4552 }
Mike Stump1eb44332009-09-09 15:08:12 +00004553
John McCall183700f2009-09-21 23:43:11 +00004554 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004555 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004556 return;
4557 }
Mike Stump1eb44332009-09-09 15:08:12 +00004558
Ted Kremenek6217b802009-07-29 21:53:49 +00004559 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004560 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004561 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004562 // Anonymous structures print as '?'
4563 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4564 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004565 if (ClassTemplateSpecializationDecl *Spec
4566 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4567 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4568 std::string TemplateArgsStr
4569 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004570 TemplateArgs.data(),
4571 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00004572 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004573
4574 S += TemplateArgsStr;
4575 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004576 } else {
4577 S += '?';
4578 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004579 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004580 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004581 if (!RDecl->isUnion()) {
4582 getObjCEncodingForStructureImpl(RDecl, S, FD);
4583 } else {
4584 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4585 FieldEnd = RDecl->field_end();
4586 Field != FieldEnd; ++Field) {
4587 if (FD) {
4588 S += '"';
4589 S += Field->getNameAsString();
4590 S += '"';
4591 }
Mike Stump1eb44332009-09-09 15:08:12 +00004592
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004593 // Special case bit-fields.
4594 if (Field->isBitField()) {
4595 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4596 (*Field));
4597 } else {
4598 QualType qt = Field->getType();
4599 getLegacyIntegralTypeEncoding(qt);
4600 getObjCEncodingForTypeImpl(qt, S, false, true,
4601 FD, /*OutermostType*/false,
4602 /*EncodingProperty*/false,
4603 /*StructField*/true);
4604 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004605 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004606 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004607 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004608 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004609 return;
4610 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004611
Douglas Gregor5471bc82011-09-08 17:18:35 +00004612 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004613 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004614 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004615 else
Douglas Gregor5471bc82011-09-08 17:18:35 +00004616 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004617 return;
4618 }
Mike Stump1eb44332009-09-09 15:08:12 +00004619
Bob Wilsondc8dab62011-11-30 01:57:58 +00004620 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004621 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00004622 if (EncodeBlockParameters) {
4623 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4624
4625 S += '<';
4626 // Block return type
4627 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4628 ExpandPointedToStructures, ExpandStructures,
4629 FD,
4630 false /* OutermostType */,
4631 EncodingProperty,
4632 false /* StructField */,
4633 EncodeBlockParameters,
4634 EncodeClassNames);
4635 // Block self
4636 S += "@?";
4637 // Block parameters
4638 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4639 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4640 E = FPT->arg_type_end(); I && (I != E); ++I) {
4641 getObjCEncodingForTypeImpl(*I, S,
4642 ExpandPointedToStructures,
4643 ExpandStructures,
4644 FD,
4645 false /* OutermostType */,
4646 EncodingProperty,
4647 false /* StructField */,
4648 EncodeBlockParameters,
4649 EncodeClassNames);
4650 }
4651 }
4652 S += '>';
4653 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004654 return;
4655 }
Mike Stump1eb44332009-09-09 15:08:12 +00004656
John McCallc12c5bb2010-05-15 11:32:37 +00004657 // Ignore protocol qualifiers when mangling at this level.
4658 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4659 T = OT->getBaseType();
4660
John McCall0953e762009-09-24 19:53:00 +00004661 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004662 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004663 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004664 S += '{';
4665 const IdentifierInfo *II = OI->getIdentifier();
4666 S += II->getName();
4667 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00004668 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004669 DeepCollectObjCIvars(OI, true, Ivars);
4670 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00004671 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004672 if (Field->isBitField())
4673 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004674 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004675 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004676 }
4677 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004678 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004679 }
Mike Stump1eb44332009-09-09 15:08:12 +00004680
John McCall183700f2009-09-21 23:43:11 +00004681 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004682 if (OPT->isObjCIdType()) {
4683 S += '@';
4684 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004685 }
Mike Stump1eb44332009-09-09 15:08:12 +00004686
Steve Naroff27d20a22009-10-28 22:03:49 +00004687 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4688 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4689 // Since this is a binary compatibility issue, need to consult with runtime
4690 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004691 S += '#';
4692 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004693 }
Mike Stump1eb44332009-09-09 15:08:12 +00004694
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004695 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004696 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004697 ExpandPointedToStructures,
4698 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00004699 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00004700 // Note that we do extended encoding of protocol qualifer list
4701 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004702 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004703 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4704 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004705 S += '<';
4706 S += (*I)->getNameAsString();
4707 S += '>';
4708 }
4709 S += '"';
4710 }
4711 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004712 }
Mike Stump1eb44332009-09-09 15:08:12 +00004713
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004714 QualType PointeeTy = OPT->getPointeeType();
4715 if (!EncodingProperty &&
4716 isa<TypedefType>(PointeeTy.getTypePtr())) {
4717 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004718 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004719 // {...};
4720 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004721 getObjCEncodingForTypeImpl(PointeeTy, S,
4722 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004723 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004724 return;
4725 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004726
4727 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00004728 if (OPT->getInterfaceDecl() &&
4729 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004730 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004731 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004732 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4733 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004734 S += '<';
4735 S += (*I)->getNameAsString();
4736 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004737 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004738 S += '"';
4739 }
4740 return;
4741 }
Mike Stump1eb44332009-09-09 15:08:12 +00004742
John McCall532ec7b2010-05-17 23:56:34 +00004743 // gcc just blithely ignores member pointers.
4744 // TODO: maybe there should be a mangling for these
4745 if (T->getAs<MemberPointerType>())
4746 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004747
4748 if (T->isVectorType()) {
4749 // This matches gcc's encoding, even though technically it is
4750 // insufficient.
4751 // FIXME. We should do a better job than gcc.
4752 return;
4753 }
4754
David Blaikieb219cfc2011-09-23 05:06:16 +00004755 llvm_unreachable("@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004756}
4757
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004758void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4759 std::string &S,
4760 const FieldDecl *FD,
4761 bool includeVBases) const {
4762 assert(RDecl && "Expected non-null RecordDecl");
4763 assert(!RDecl->isUnion() && "Should not be called for unions");
4764 if (!RDecl->getDefinition())
4765 return;
4766
4767 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4768 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4769 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4770
4771 if (CXXRec) {
4772 for (CXXRecordDecl::base_class_iterator
4773 BI = CXXRec->bases_begin(),
4774 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4775 if (!BI->isVirtual()) {
4776 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004777 if (base->isEmpty())
4778 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004779 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4780 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4781 std::make_pair(offs, base));
4782 }
4783 }
4784 }
4785
4786 unsigned i = 0;
4787 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4788 FieldEnd = RDecl->field_end();
4789 Field != FieldEnd; ++Field, ++i) {
4790 uint64_t offs = layout.getFieldOffset(i);
4791 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4792 std::make_pair(offs, *Field));
4793 }
4794
4795 if (CXXRec && includeVBases) {
4796 for (CXXRecordDecl::base_class_iterator
4797 BI = CXXRec->vbases_begin(),
4798 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4799 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004800 if (base->isEmpty())
4801 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004802 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00004803 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4804 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4805 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004806 }
4807 }
4808
4809 CharUnits size;
4810 if (CXXRec) {
4811 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4812 } else {
4813 size = layout.getSize();
4814 }
4815
4816 uint64_t CurOffs = 0;
4817 std::multimap<uint64_t, NamedDecl *>::iterator
4818 CurLayObj = FieldOrBaseOffsets.begin();
4819
Argyrios Kyrtzidiscb8061e2011-08-22 16:03:14 +00004820 if ((CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) ||
4821 (CurLayObj == FieldOrBaseOffsets.end() &&
4822 CXXRec && CXXRec->isDynamicClass())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004823 assert(CXXRec && CXXRec->isDynamicClass() &&
4824 "Offset 0 was empty but no VTable ?");
4825 if (FD) {
4826 S += "\"_vptr$";
4827 std::string recname = CXXRec->getNameAsString();
4828 if (recname.empty()) recname = "?";
4829 S += recname;
4830 S += '"';
4831 }
4832 S += "^^?";
4833 CurOffs += getTypeSize(VoidPtrTy);
4834 }
4835
4836 if (!RDecl->hasFlexibleArrayMember()) {
4837 // Mark the end of the structure.
4838 uint64_t offs = toBits(size);
4839 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4840 std::make_pair(offs, (NamedDecl*)0));
4841 }
4842
4843 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4844 assert(CurOffs <= CurLayObj->first);
4845
4846 if (CurOffs < CurLayObj->first) {
4847 uint64_t padding = CurLayObj->first - CurOffs;
4848 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4849 // packing/alignment of members is different that normal, in which case
4850 // the encoding will be out-of-sync with the real layout.
4851 // If the runtime switches to just consider the size of types without
4852 // taking into account alignment, we could make padding explicit in the
4853 // encoding (e.g. using arrays of chars). The encoding strings would be
4854 // longer then though.
4855 CurOffs += padding;
4856 }
4857
4858 NamedDecl *dcl = CurLayObj->second;
4859 if (dcl == 0)
4860 break; // reached end of structure.
4861
4862 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4863 // We expand the bases without their virtual bases since those are going
4864 // in the initial structure. Note that this differs from gcc which
4865 // expands virtual bases each time one is encountered in the hierarchy,
4866 // making the encoding type bigger than it really is.
4867 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004868 assert(!base->isEmpty());
4869 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004870 } else {
4871 FieldDecl *field = cast<FieldDecl>(dcl);
4872 if (FD) {
4873 S += '"';
4874 S += field->getNameAsString();
4875 S += '"';
4876 }
4877
4878 if (field->isBitField()) {
4879 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004880 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004881 } else {
4882 QualType qt = field->getType();
4883 getLegacyIntegralTypeEncoding(qt);
4884 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4885 /*OutermostType*/false,
4886 /*EncodingProperty*/false,
4887 /*StructField*/true);
4888 CurOffs += getTypeSize(field->getType());
4889 }
4890 }
4891 }
4892}
4893
Mike Stump1eb44332009-09-09 15:08:12 +00004894void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004895 std::string& S) const {
4896 if (QT & Decl::OBJC_TQ_In)
4897 S += 'n';
4898 if (QT & Decl::OBJC_TQ_Inout)
4899 S += 'N';
4900 if (QT & Decl::OBJC_TQ_Out)
4901 S += 'o';
4902 if (QT & Decl::OBJC_TQ_Bycopy)
4903 S += 'O';
4904 if (QT & Decl::OBJC_TQ_Byref)
4905 S += 'R';
4906 if (QT & Decl::OBJC_TQ_Oneway)
4907 S += 'V';
4908}
4909
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004910void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004911 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004912
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004913 BuiltinVaListType = T;
4914}
4915
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00004916TypedefDecl *ASTContext::getObjCIdDecl() const {
4917 if (!ObjCIdDecl) {
4918 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4919 T = getObjCObjectPointerType(T);
4920 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4921 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4922 getTranslationUnitDecl(),
4923 SourceLocation(), SourceLocation(),
4924 &Idents.get("id"), IdInfo);
4925 }
4926
4927 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00004928}
4929
Douglas Gregor7a27ea52011-08-12 06:17:30 +00004930TypedefDecl *ASTContext::getObjCSelDecl() const {
4931 if (!ObjCSelDecl) {
4932 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4933 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4934 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4935 getTranslationUnitDecl(),
4936 SourceLocation(), SourceLocation(),
4937 &Idents.get("SEL"), SelInfo);
4938 }
4939 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004940}
4941
Douglas Gregor79d67262011-08-12 05:59:41 +00004942TypedefDecl *ASTContext::getObjCClassDecl() const {
4943 if (!ObjCClassDecl) {
4944 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4945 T = getObjCObjectPointerType(T);
4946 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4947 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4948 getTranslationUnitDecl(),
4949 SourceLocation(), SourceLocation(),
4950 &Idents.get("Class"), ClassInfo);
4951 }
4952
4953 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004954}
4955
Douglas Gregora6ea10e2012-01-17 18:09:05 +00004956ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
4957 if (!ObjCProtocolClassDecl) {
4958 ObjCProtocolClassDecl
4959 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
4960 SourceLocation(),
4961 &Idents.get("Protocol"),
4962 /*PrevDecl=*/0,
4963 SourceLocation(), true);
4964 }
4965
4966 return ObjCProtocolClassDecl;
4967}
4968
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004969void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004970 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004971 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004972
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004973 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004974}
4975
John McCall0bd6feb2009-12-02 08:04:21 +00004976/// \brief Retrieve the template name that corresponds to a non-empty
4977/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00004978TemplateName
4979ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4980 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00004981 unsigned size = End - Begin;
4982 assert(size > 1 && "set is not overloaded!");
4983
4984 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4985 size * sizeof(FunctionTemplateDecl*));
4986 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4987
4988 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004989 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004990 NamedDecl *D = *I;
4991 assert(isa<FunctionTemplateDecl>(D) ||
4992 (isa<UsingShadowDecl>(D) &&
4993 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4994 *Storage++ = D;
4995 }
4996
4997 return TemplateName(OT);
4998}
4999
Douglas Gregor7532dc62009-03-30 22:58:21 +00005000/// \brief Retrieve the template name that represents a qualified
5001/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00005002TemplateName
5003ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5004 bool TemplateKeyword,
5005 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00005006 assert(NNS && "Missing nested-name-specifier in qualified template name");
5007
Douglas Gregor789b1f62010-02-04 18:10:26 +00005008 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00005009 llvm::FoldingSetNodeID ID;
5010 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5011
5012 void *InsertPos = 0;
5013 QualifiedTemplateName *QTN =
5014 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5015 if (!QTN) {
5016 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
5017 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5018 }
5019
5020 return TemplateName(QTN);
5021}
5022
5023/// \brief Retrieve the template name that represents a dependent
5024/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00005025TemplateName
5026ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5027 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00005028 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00005029 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00005030
5031 llvm::FoldingSetNodeID ID;
5032 DependentTemplateName::Profile(ID, NNS, Name);
5033
5034 void *InsertPos = 0;
5035 DependentTemplateName *QTN =
5036 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5037
5038 if (QTN)
5039 return TemplateName(QTN);
5040
5041 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5042 if (CanonNNS == NNS) {
5043 QTN = new (*this,4) DependentTemplateName(NNS, Name);
5044 } else {
5045 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5046 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005047 DependentTemplateName *CheckQTN =
5048 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5049 assert(!CheckQTN && "Dependent type name canonicalization broken");
5050 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00005051 }
5052
5053 DependentTemplateNames.InsertNode(QTN, InsertPos);
5054 return TemplateName(QTN);
5055}
5056
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005057/// \brief Retrieve the template name that represents a dependent
5058/// template name such as \c MetaFun::template operator+.
5059TemplateName
5060ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00005061 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005062 assert((!NNS || NNS->isDependent()) &&
5063 "Nested name specifier must be dependent");
5064
5065 llvm::FoldingSetNodeID ID;
5066 DependentTemplateName::Profile(ID, NNS, Operator);
5067
5068 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00005069 DependentTemplateName *QTN
5070 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005071
5072 if (QTN)
5073 return TemplateName(QTN);
5074
5075 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5076 if (CanonNNS == NNS) {
5077 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5078 } else {
5079 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5080 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005081
5082 DependentTemplateName *CheckQTN
5083 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5084 assert(!CheckQTN && "Dependent template name canonicalization broken");
5085 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005086 }
5087
5088 DependentTemplateNames.InsertNode(QTN, InsertPos);
5089 return TemplateName(QTN);
5090}
5091
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005092TemplateName
John McCall14606042011-06-30 08:33:18 +00005093ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5094 TemplateName replacement) const {
5095 llvm::FoldingSetNodeID ID;
5096 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5097
5098 void *insertPos = 0;
5099 SubstTemplateTemplateParmStorage *subst
5100 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5101
5102 if (!subst) {
5103 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5104 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5105 }
5106
5107 return TemplateName(subst);
5108}
5109
5110TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005111ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5112 const TemplateArgument &ArgPack) const {
5113 ASTContext &Self = const_cast<ASTContext &>(*this);
5114 llvm::FoldingSetNodeID ID;
5115 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5116
5117 void *InsertPos = 0;
5118 SubstTemplateTemplateParmPackStorage *Subst
5119 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5120
5121 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00005122 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005123 ArgPack.pack_size(),
5124 ArgPack.pack_begin());
5125 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5126 }
5127
5128 return TemplateName(Subst);
5129}
5130
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005131/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00005132/// TargetInfo, produce the corresponding type. The unsigned @p Type
5133/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00005134CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005135 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00005136 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005137 case TargetInfo::SignedShort: return ShortTy;
5138 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5139 case TargetInfo::SignedInt: return IntTy;
5140 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5141 case TargetInfo::SignedLong: return LongTy;
5142 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5143 case TargetInfo::SignedLongLong: return LongLongTy;
5144 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5145 }
5146
David Blaikieb219cfc2011-09-23 05:06:16 +00005147 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005148}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00005149
5150//===----------------------------------------------------------------------===//
5151// Type Predicates.
5152//===----------------------------------------------------------------------===//
5153
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005154/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5155/// garbage collection attribute.
5156///
John McCallae278a32011-01-12 00:34:59 +00005157Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
Douglas Gregore289d812011-09-13 17:21:33 +00005158 if (getLangOptions().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00005159 return Qualifiers::GCNone;
5160
5161 assert(getLangOptions().ObjC1);
5162 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5163
5164 // Default behaviour under objective-C's gc is for ObjC pointers
5165 // (or pointers to them) be treated as though they were declared
5166 // as __strong.
5167 if (GCAttrs == Qualifiers::GCNone) {
5168 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5169 return Qualifiers::Strong;
5170 else if (Ty->isPointerType())
5171 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5172 } else {
5173 // It's not valid to set GC attributes on anything that isn't a
5174 // pointer.
5175#ifndef NDEBUG
5176 QualType CT = Ty->getCanonicalTypeInternal();
5177 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5178 CT = AT->getElementType();
5179 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5180#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005181 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00005182 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005183}
5184
Chris Lattner6ac46a42008-04-07 06:51:04 +00005185//===----------------------------------------------------------------------===//
5186// Type Compatibility Testing
5187//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00005188
Mike Stump1eb44332009-09-09 15:08:12 +00005189/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005190/// compatible.
5191static bool areCompatVectorTypes(const VectorType *LHS,
5192 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00005193 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00005194 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00005195 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00005196}
5197
Douglas Gregor255210e2010-08-06 10:14:59 +00005198bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5199 QualType SecondVec) {
5200 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5201 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5202
5203 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5204 return true;
5205
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005206 // Treat Neon vector types and most AltiVec vector types as if they are the
5207 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00005208 const VectorType *First = FirstVec->getAs<VectorType>();
5209 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005210 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00005211 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005212 First->getVectorKind() != VectorType::AltiVecPixel &&
5213 First->getVectorKind() != VectorType::AltiVecBool &&
5214 Second->getVectorKind() != VectorType::AltiVecPixel &&
5215 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00005216 return true;
5217
5218 return false;
5219}
5220
Steve Naroff4084c302009-07-23 01:01:38 +00005221//===----------------------------------------------------------------------===//
5222// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5223//===----------------------------------------------------------------------===//
5224
5225/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5226/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00005227bool
5228ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5229 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005230 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00005231 return true;
5232 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5233 E = rProto->protocol_end(); PI != E; ++PI)
5234 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5235 return true;
5236 return false;
5237}
5238
Steve Naroff4084c302009-07-23 01:01:38 +00005239/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5240/// return true if lhs's protocols conform to rhs's protocol; false
5241/// otherwise.
5242bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5243 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5244 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5245 return false;
5246}
5247
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005248/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5249/// Class<p1, ...>.
5250bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5251 QualType rhs) {
5252 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5253 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5254 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5255
5256 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5257 E = lhsQID->qual_end(); I != E; ++I) {
5258 bool match = false;
5259 ObjCProtocolDecl *lhsProto = *I;
5260 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5261 E = rhsOPT->qual_end(); J != E; ++J) {
5262 ObjCProtocolDecl *rhsProto = *J;
5263 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5264 match = true;
5265 break;
5266 }
5267 }
5268 if (!match)
5269 return false;
5270 }
5271 return true;
5272}
5273
Steve Naroff4084c302009-07-23 01:01:38 +00005274/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5275/// ObjCQualifiedIDType.
5276bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5277 bool compare) {
5278 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00005279 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005280 lhs->isObjCIdType() || lhs->isObjCClassType())
5281 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005282 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005283 rhs->isObjCIdType() || rhs->isObjCClassType())
5284 return true;
5285
5286 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00005287 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005288
Steve Naroff4084c302009-07-23 01:01:38 +00005289 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005290
Steve Naroff4084c302009-07-23 01:01:38 +00005291 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005292 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00005293 // make sure we check the class hierarchy.
5294 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5295 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5296 E = lhsQID->qual_end(); I != E; ++I) {
5297 // when comparing an id<P> on lhs with a static type on rhs,
5298 // see if static class implements all of id's protocols, directly or
5299 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005300 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00005301 return false;
5302 }
5303 }
5304 // If there are no qualifiers and no interface, we have an 'id'.
5305 return true;
5306 }
Mike Stump1eb44332009-09-09 15:08:12 +00005307 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005308 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5309 E = lhsQID->qual_end(); I != E; ++I) {
5310 ObjCProtocolDecl *lhsProto = *I;
5311 bool match = false;
5312
5313 // when comparing an id<P> on lhs with a static type on rhs,
5314 // see if static class implements all of id's protocols, directly or
5315 // through its super class and categories.
5316 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5317 E = rhsOPT->qual_end(); J != E; ++J) {
5318 ObjCProtocolDecl *rhsProto = *J;
5319 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5320 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5321 match = true;
5322 break;
5323 }
5324 }
Mike Stump1eb44332009-09-09 15:08:12 +00005325 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00005326 // make sure we check the class hierarchy.
5327 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5328 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5329 E = lhsQID->qual_end(); I != E; ++I) {
5330 // when comparing an id<P> on lhs with a static type on rhs,
5331 // see if static class implements all of id's protocols, directly or
5332 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005333 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00005334 match = true;
5335 break;
5336 }
5337 }
5338 }
5339 if (!match)
5340 return false;
5341 }
Mike Stump1eb44332009-09-09 15:08:12 +00005342
Steve Naroff4084c302009-07-23 01:01:38 +00005343 return true;
5344 }
Mike Stump1eb44332009-09-09 15:08:12 +00005345
Steve Naroff4084c302009-07-23 01:01:38 +00005346 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5347 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5348
Mike Stump1eb44332009-09-09 15:08:12 +00005349 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00005350 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005351 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005352 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5353 E = lhsOPT->qual_end(); I != E; ++I) {
5354 ObjCProtocolDecl *lhsProto = *I;
5355 bool match = false;
5356
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005357 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00005358 // see if static class implements all of id's protocols, directly or
5359 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005360 // First, lhs protocols in the qualifier list must be found, direct
5361 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00005362 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5363 E = rhsQID->qual_end(); J != E; ++J) {
5364 ObjCProtocolDecl *rhsProto = *J;
5365 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5366 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5367 match = true;
5368 break;
5369 }
5370 }
5371 if (!match)
5372 return false;
5373 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005374
5375 // Static class's protocols, or its super class or category protocols
5376 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5377 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5378 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5379 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5380 // This is rather dubious but matches gcc's behavior. If lhs has
5381 // no type qualifier and its class has no static protocol(s)
5382 // assume that it is mismatch.
5383 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5384 return false;
5385 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5386 LHSInheritedProtocols.begin(),
5387 E = LHSInheritedProtocols.end(); I != E; ++I) {
5388 bool match = false;
5389 ObjCProtocolDecl *lhsProto = (*I);
5390 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5391 E = rhsQID->qual_end(); J != E; ++J) {
5392 ObjCProtocolDecl *rhsProto = *J;
5393 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5394 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5395 match = true;
5396 break;
5397 }
5398 }
5399 if (!match)
5400 return false;
5401 }
5402 }
Steve Naroff4084c302009-07-23 01:01:38 +00005403 return true;
5404 }
5405 return false;
5406}
5407
Eli Friedman3d815e72008-08-22 00:56:42 +00005408/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005409/// compatible for assignment from RHS to LHS. This handles validation of any
5410/// protocol qualifiers on the LHS or RHS.
5411///
Steve Naroff14108da2009-07-10 23:34:53 +00005412bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5413 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00005414 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5415 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5416
Steve Naroffde2e22d2009-07-15 18:40:39 +00005417 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00005418 if (LHS->isObjCUnqualifiedIdOrClass() ||
5419 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00005420 return true;
5421
John McCallc12c5bb2010-05-15 11:32:37 +00005422 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00005423 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5424 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00005425 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005426
5427 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5428 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5429 QualType(RHSOPT,0));
5430
John McCallc12c5bb2010-05-15 11:32:37 +00005431 // If we have 2 user-defined types, fall into that path.
5432 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00005433 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00005434
Steve Naroff4084c302009-07-23 01:01:38 +00005435 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005436}
5437
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005438/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00005439/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005440/// arguments in block literals. When passed as arguments, passing 'A*' where
5441/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5442/// not OK. For the return type, the opposite is not OK.
5443bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5444 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005445 const ObjCObjectPointerType *RHSOPT,
5446 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005447 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005448 return true;
5449
5450 if (LHSOPT->isObjCBuiltinType()) {
5451 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5452 }
5453
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005454 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005455 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5456 QualType(RHSOPT,0),
5457 false);
5458
5459 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5460 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5461 if (LHS && RHS) { // We have 2 user-defined types.
5462 if (LHS != RHS) {
5463 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005464 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005465 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005466 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005467 }
5468 else
5469 return true;
5470 }
5471 return false;
5472}
5473
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005474/// getIntersectionOfProtocols - This routine finds the intersection of set
5475/// of protocols inherited from two distinct objective-c pointer objects.
5476/// It is used to build composite qualifier list of the composite type of
5477/// the conditional expression involving two objective-c pointer objects.
5478static
5479void getIntersectionOfProtocols(ASTContext &Context,
5480 const ObjCObjectPointerType *LHSOPT,
5481 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005482 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005483
John McCallc12c5bb2010-05-15 11:32:37 +00005484 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5485 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5486 assert(LHS->getInterface() && "LHS must have an interface base");
5487 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005488
5489 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5490 unsigned LHSNumProtocols = LHS->getNumProtocols();
5491 if (LHSNumProtocols > 0)
5492 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5493 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005494 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005495 Context.CollectInheritedProtocols(LHS->getInterface(),
5496 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005497 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5498 LHSInheritedProtocols.end());
5499 }
5500
5501 unsigned RHSNumProtocols = RHS->getNumProtocols();
5502 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00005503 ObjCProtocolDecl **RHSProtocols =
5504 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005505 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5506 if (InheritedProtocolSet.count(RHSProtocols[i]))
5507 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00005508 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005509 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005510 Context.CollectInheritedProtocols(RHS->getInterface(),
5511 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005512 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5513 RHSInheritedProtocols.begin(),
5514 E = RHSInheritedProtocols.end(); I != E; ++I)
5515 if (InheritedProtocolSet.count((*I)))
5516 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005517 }
5518}
5519
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005520/// areCommonBaseCompatible - Returns common base class of the two classes if
5521/// one found. Note that this is O'2 algorithm. But it will be called as the
5522/// last type comparison in a ?-exp of ObjC pointer types before a
5523/// warning is issued. So, its invokation is extremely rare.
5524QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00005525 const ObjCObjectPointerType *Lptr,
5526 const ObjCObjectPointerType *Rptr) {
5527 const ObjCObjectType *LHS = Lptr->getObjectType();
5528 const ObjCObjectType *RHS = Rptr->getObjectType();
5529 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5530 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00005531 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005532 return QualType();
5533
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005534 do {
John McCallc12c5bb2010-05-15 11:32:37 +00005535 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005536 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005537 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005538 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5539
5540 QualType Result = QualType(LHS, 0);
5541 if (!Protocols.empty())
5542 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5543 Result = getObjCObjectPointerType(Result);
5544 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005545 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005546 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005547
5548 return QualType();
5549}
5550
John McCallc12c5bb2010-05-15 11:32:37 +00005551bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5552 const ObjCObjectType *RHS) {
5553 assert(LHS->getInterface() && "LHS is not an interface type");
5554 assert(RHS->getInterface() && "RHS is not an interface type");
5555
Chris Lattner6ac46a42008-04-07 06:51:04 +00005556 // Verify that the base decls are compatible: the RHS must be a subclass of
5557 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00005558 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00005559 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005560
Chris Lattner6ac46a42008-04-07 06:51:04 +00005561 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5562 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00005563 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00005564 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005565
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005566 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5567 // more detailed analysis is required.
5568 if (RHS->getNumProtocols() == 0) {
5569 // OK, if LHS is a superclass of RHS *and*
5570 // this superclass is assignment compatible with LHS.
5571 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005572 bool IsSuperClass =
5573 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5574 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005575 // OK if conversion of LHS to SuperClass results in narrowing of types
5576 // ; i.e., SuperClass may implement at least one of the protocols
5577 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5578 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5579 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005580 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005581 // If super class has no protocols, it is not a match.
5582 if (SuperClassInheritedProtocols.empty())
5583 return false;
5584
5585 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5586 LHSPE = LHS->qual_end();
5587 LHSPI != LHSPE; LHSPI++) {
5588 bool SuperImplementsProtocol = false;
5589 ObjCProtocolDecl *LHSProto = (*LHSPI);
5590
5591 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5592 SuperClassInheritedProtocols.begin(),
5593 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5594 ObjCProtocolDecl *SuperClassProto = (*I);
5595 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5596 SuperImplementsProtocol = true;
5597 break;
5598 }
5599 }
5600 if (!SuperImplementsProtocol)
5601 return false;
5602 }
5603 return true;
5604 }
5605 return false;
5606 }
Mike Stump1eb44332009-09-09 15:08:12 +00005607
John McCallc12c5bb2010-05-15 11:32:37 +00005608 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5609 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005610 LHSPI != LHSPE; LHSPI++) {
5611 bool RHSImplementsProtocol = false;
5612
5613 // If the RHS doesn't implement the protocol on the left, the types
5614 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00005615 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5616 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00005617 RHSPI != RHSPE; RHSPI++) {
5618 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005619 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00005620 break;
5621 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005622 }
5623 // FIXME: For better diagnostics, consider passing back the protocol name.
5624 if (!RHSImplementsProtocol)
5625 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005626 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005627 // The RHS implements all protocols listed on the LHS.
5628 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005629}
5630
Steve Naroff389bf462009-02-12 17:52:19 +00005631bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5632 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00005633 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5634 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005635
Steve Naroff14108da2009-07-10 23:34:53 +00005636 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00005637 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005638
5639 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5640 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00005641}
5642
Douglas Gregor569c3162010-08-07 11:51:51 +00005643bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5644 return canAssignObjCInterfaces(
5645 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5646 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5647}
5648
Mike Stump1eb44332009-09-09 15:08:12 +00005649/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00005650/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00005651/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00005652/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00005653bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5654 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005655 if (getLangOptions().CPlusPlus)
5656 return hasSameType(LHS, RHS);
5657
Douglas Gregor447234d2010-07-29 15:18:02 +00005658 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00005659}
5660
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005661bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00005662 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005663}
5664
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005665bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5666 return !mergeTypes(LHS, RHS, true).isNull();
5667}
5668
Peter Collingbourne48466752010-10-24 18:30:18 +00005669/// mergeTransparentUnionType - if T is a transparent union type and a member
5670/// of T is compatible with SubType, return the merged type, else return
5671/// QualType()
5672QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5673 bool OfBlockPointer,
5674 bool Unqualified) {
5675 if (const RecordType *UT = T->getAsUnionType()) {
5676 RecordDecl *UD = UT->getDecl();
5677 if (UD->hasAttr<TransparentUnionAttr>()) {
5678 for (RecordDecl::field_iterator it = UD->field_begin(),
5679 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00005680 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005681 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5682 if (!MT.isNull())
5683 return MT;
5684 }
5685 }
5686 }
5687
5688 return QualType();
5689}
5690
5691/// mergeFunctionArgumentTypes - merge two types which appear as function
5692/// argument types
5693QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5694 bool OfBlockPointer,
5695 bool Unqualified) {
5696 // GNU extension: two types are compatible if they appear as a function
5697 // argument, one of the types is a transparent union type and the other
5698 // type is compatible with a union member
5699 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5700 Unqualified);
5701 if (!lmerge.isNull())
5702 return lmerge;
5703
5704 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5705 Unqualified);
5706 if (!rmerge.isNull())
5707 return rmerge;
5708
5709 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5710}
5711
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005712QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00005713 bool OfBlockPointer,
5714 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00005715 const FunctionType *lbase = lhs->getAs<FunctionType>();
5716 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00005717 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5718 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00005719 bool allLTypes = true;
5720 bool allRTypes = true;
5721
5722 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005723 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005724 if (OfBlockPointer) {
5725 QualType RHS = rbase->getResultType();
5726 QualType LHS = lbase->getResultType();
5727 bool UnqualifiedResult = Unqualified;
5728 if (!UnqualifiedResult)
5729 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005730 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005731 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005732 else
John McCall8cc246c2010-12-15 01:06:38 +00005733 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5734 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005735 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005736
5737 if (Unqualified)
5738 retType = retType.getUnqualifiedType();
5739
5740 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5741 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5742 if (Unqualified) {
5743 LRetType = LRetType.getUnqualifiedType();
5744 RRetType = RRetType.getUnqualifiedType();
5745 }
5746
5747 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005748 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00005749 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005750 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005751
Daniel Dunbar6a15c852010-04-28 16:20:58 +00005752 // FIXME: double check this
5753 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5754 // rbase->getRegParmAttr() != 0 &&
5755 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00005756 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5757 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00005758
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005759 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00005760 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005761 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005762
John McCall8cc246c2010-12-15 01:06:38 +00005763 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00005764 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5765 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00005766 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5767 return QualType();
5768
John McCallf85e1932011-06-15 23:02:42 +00005769 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5770 return QualType();
5771
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005772 // functypes which return are preferred over those that do not.
5773 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5774 allLTypes = false;
5775 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5776 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005777 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5778 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00005779
John McCallf85e1932011-06-15 23:02:42 +00005780 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00005781
Eli Friedman3d815e72008-08-22 00:56:42 +00005782 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00005783 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5784 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005785 unsigned lproto_nargs = lproto->getNumArgs();
5786 unsigned rproto_nargs = rproto->getNumArgs();
5787
5788 // Compatible functions must have the same number of arguments
5789 if (lproto_nargs != rproto_nargs)
5790 return QualType();
5791
5792 // Variadic and non-variadic functions aren't compatible
5793 if (lproto->isVariadic() != rproto->isVariadic())
5794 return QualType();
5795
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00005796 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5797 return QualType();
5798
Fariborz Jahanian78213e42011-09-28 21:52:05 +00005799 if (LangOpts.ObjCAutoRefCount &&
5800 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5801 return QualType();
5802
Eli Friedman3d815e72008-08-22 00:56:42 +00005803 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00005804 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00005805 for (unsigned i = 0; i < lproto_nargs; i++) {
5806 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5807 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005808 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5809 OfBlockPointer,
5810 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005811 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005812
5813 if (Unqualified)
5814 argtype = argtype.getUnqualifiedType();
5815
Eli Friedman3d815e72008-08-22 00:56:42 +00005816 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00005817 if (Unqualified) {
5818 largtype = largtype.getUnqualifiedType();
5819 rargtype = rargtype.getUnqualifiedType();
5820 }
5821
Chris Lattner61710852008-10-05 17:34:18 +00005822 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5823 allLTypes = false;
5824 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5825 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00005826 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00005827
Eli Friedman3d815e72008-08-22 00:56:42 +00005828 if (allLTypes) return lhs;
5829 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005830
5831 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5832 EPI.ExtInfo = einfo;
5833 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005834 }
5835
5836 if (lproto) allRTypes = false;
5837 if (rproto) allLTypes = false;
5838
Douglas Gregor72564e72009-02-26 23:50:07 +00005839 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00005840 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00005841 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005842 if (proto->isVariadic()) return QualType();
5843 // Check that the types are compatible with the types that
5844 // would result from default argument promotions (C99 6.7.5.3p15).
5845 // The only types actually affected are promotable integer
5846 // types and floats, which would be passed as a different
5847 // type depending on whether the prototype is visible.
5848 unsigned proto_nargs = proto->getNumArgs();
5849 for (unsigned i = 0; i < proto_nargs; ++i) {
5850 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00005851
5852 // Look at the promotion type of enum types, since that is the type used
5853 // to pass enum values.
5854 if (const EnumType *Enum = argTy->getAs<EnumType>())
5855 argTy = Enum->getDecl()->getPromotionType();
5856
Eli Friedman3d815e72008-08-22 00:56:42 +00005857 if (argTy->isPromotableIntegerType() ||
5858 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5859 return QualType();
5860 }
5861
5862 if (allLTypes) return lhs;
5863 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005864
5865 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5866 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00005867 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005868 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005869 }
5870
5871 if (allLTypes) return lhs;
5872 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00005873 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00005874}
5875
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005876QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00005877 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005878 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00005879 // C++ [expr]: If an expression initially has the type "reference to T", the
5880 // type is adjusted to "T" prior to any further analysis, the expression
5881 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005882 // expression is an lvalue unless the reference is an rvalue reference and
5883 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005884 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5885 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00005886
5887 if (Unqualified) {
5888 LHS = LHS.getUnqualifiedType();
5889 RHS = RHS.getUnqualifiedType();
5890 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005891
Eli Friedman3d815e72008-08-22 00:56:42 +00005892 QualType LHSCan = getCanonicalType(LHS),
5893 RHSCan = getCanonicalType(RHS);
5894
5895 // If two types are identical, they are compatible.
5896 if (LHSCan == RHSCan)
5897 return LHS;
5898
John McCall0953e762009-09-24 19:53:00 +00005899 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005900 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5901 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00005902 if (LQuals != RQuals) {
5903 // If any of these qualifiers are different, we have a type
5904 // mismatch.
5905 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00005906 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5907 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00005908 return QualType();
5909
5910 // Exactly one GC qualifier difference is allowed: __strong is
5911 // okay if the other type has no GC qualifier but is an Objective
5912 // C object pointer (i.e. implicitly strong by default). We fix
5913 // this by pretending that the unqualified type was actually
5914 // qualified __strong.
5915 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5916 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5917 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5918
5919 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5920 return QualType();
5921
5922 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5923 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5924 }
5925 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5926 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5927 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005928 return QualType();
John McCall0953e762009-09-24 19:53:00 +00005929 }
5930
5931 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00005932
Eli Friedman852d63b2009-06-01 01:22:52 +00005933 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5934 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00005935
Chris Lattner1adb8832008-01-14 05:45:46 +00005936 // We want to consider the two function types to be the same for these
5937 // comparisons, just force one to the other.
5938 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5939 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00005940
5941 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00005942 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5943 LHSClass = Type::ConstantArray;
5944 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5945 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00005946
John McCallc12c5bb2010-05-15 11:32:37 +00005947 // ObjCInterfaces are just specialized ObjCObjects.
5948 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5949 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5950
Nate Begeman213541a2008-04-18 23:10:10 +00005951 // Canonicalize ExtVector -> Vector.
5952 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5953 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00005954
Chris Lattnera36a61f2008-04-07 05:43:21 +00005955 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005956 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00005957 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00005958 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00005959 // Compatibility is based on the underlying type, not the promotion
5960 // type.
John McCall183700f2009-09-21 23:43:11 +00005961 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005962 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5963 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005964 }
John McCall183700f2009-09-21 23:43:11 +00005965 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005966 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5967 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005968 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00005969 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00005970 if (OfBlockPointer && !BlockReturnType) {
5971 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
5972 return LHS;
5973 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
5974 return RHS;
5975 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00005976
Eli Friedman3d815e72008-08-22 00:56:42 +00005977 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005978 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005979
Steve Naroff4a746782008-01-09 22:43:08 +00005980 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005981 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00005982#define TYPE(Class, Base)
5983#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00005984#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00005985#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5986#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5987#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00005988 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00005989
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005990 case Type::LValueReference:
5991 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00005992 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00005993 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00005994
John McCallc12c5bb2010-05-15 11:32:37 +00005995 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00005996 case Type::IncompleteArray:
5997 case Type::VariableArray:
5998 case Type::FunctionProto:
5999 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00006000 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00006001
Chris Lattner1adb8832008-01-14 05:45:46 +00006002 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00006003 {
6004 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006005 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6006 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006007 if (Unqualified) {
6008 LHSPointee = LHSPointee.getUnqualifiedType();
6009 RHSPointee = RHSPointee.getUnqualifiedType();
6010 }
6011 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6012 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006013 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00006014 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00006015 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00006016 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00006017 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006018 return getPointerType(ResultType);
6019 }
Steve Naroffc0febd52008-12-10 17:49:55 +00006020 case Type::BlockPointer:
6021 {
6022 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006023 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6024 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006025 if (Unqualified) {
6026 LHSPointee = LHSPointee.getUnqualifiedType();
6027 RHSPointee = RHSPointee.getUnqualifiedType();
6028 }
6029 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6030 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00006031 if (ResultType.isNull()) return QualType();
6032 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6033 return LHS;
6034 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6035 return RHS;
6036 return getBlockPointerType(ResultType);
6037 }
Eli Friedmanb001de72011-10-06 23:00:33 +00006038 case Type::Atomic:
6039 {
6040 // Merge two pointer types, while trying to preserve typedef info
6041 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6042 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6043 if (Unqualified) {
6044 LHSValue = LHSValue.getUnqualifiedType();
6045 RHSValue = RHSValue.getUnqualifiedType();
6046 }
6047 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6048 Unqualified);
6049 if (ResultType.isNull()) return QualType();
6050 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6051 return LHS;
6052 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6053 return RHS;
6054 return getAtomicType(ResultType);
6055 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006056 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00006057 {
6058 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6059 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6060 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6061 return QualType();
6062
6063 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6064 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006065 if (Unqualified) {
6066 LHSElem = LHSElem.getUnqualifiedType();
6067 RHSElem = RHSElem.getUnqualifiedType();
6068 }
6069
6070 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006071 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00006072 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6073 return LHS;
6074 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6075 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00006076 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6077 ArrayType::ArraySizeModifier(), 0);
6078 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6079 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006080 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6081 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00006082 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6083 return LHS;
6084 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6085 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006086 if (LVAT) {
6087 // FIXME: This isn't correct! But tricky to implement because
6088 // the array's size has to be the size of LHS, but the type
6089 // has to be different.
6090 return LHS;
6091 }
6092 if (RVAT) {
6093 // FIXME: This isn't correct! But tricky to implement because
6094 // the array's size has to be the size of RHS, but the type
6095 // has to be different.
6096 return RHS;
6097 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00006098 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6099 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00006100 return getIncompleteArrayType(ResultType,
6101 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006102 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006103 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00006104 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00006105 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00006106 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00006107 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00006108 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006109 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00006110 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00006111 case Type::Complex:
6112 // Distinct complex types are incompatible.
6113 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006114 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006115 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00006116 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6117 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006118 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00006119 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00006120 case Type::ObjCObject: {
6121 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006122 // FIXME: This should be type compatibility, e.g. whether
6123 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00006124 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6125 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6126 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00006127 return LHS;
6128
Eli Friedman3d815e72008-08-22 00:56:42 +00006129 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00006130 }
Steve Naroff14108da2009-07-10 23:34:53 +00006131 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006132 if (OfBlockPointer) {
6133 if (canAssignObjCInterfacesInBlockPointer(
6134 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006135 RHS->getAs<ObjCObjectPointerType>(),
6136 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00006137 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006138 return QualType();
6139 }
John McCall183700f2009-09-21 23:43:11 +00006140 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6141 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00006142 return LHS;
6143
Steve Naroffbc76dd02008-12-10 22:14:21 +00006144 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00006145 }
Steve Naroffec0550f2007-10-15 20:41:53 +00006146 }
Douglas Gregor72564e72009-02-26 23:50:07 +00006147
David Blaikie7530c032012-01-17 06:56:22 +00006148 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00006149}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00006150
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006151bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6152 const FunctionProtoType *FromFunctionType,
6153 const FunctionProtoType *ToFunctionType) {
6154 if (FromFunctionType->hasAnyConsumedArgs() !=
6155 ToFunctionType->hasAnyConsumedArgs())
6156 return false;
6157 FunctionProtoType::ExtProtoInfo FromEPI =
6158 FromFunctionType->getExtProtoInfo();
6159 FunctionProtoType::ExtProtoInfo ToEPI =
6160 ToFunctionType->getExtProtoInfo();
6161 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6162 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6163 ArgIdx != NumArgs; ++ArgIdx) {
6164 if (FromEPI.ConsumedArguments[ArgIdx] !=
6165 ToEPI.ConsumedArguments[ArgIdx])
6166 return false;
6167 }
6168 return true;
6169}
6170
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006171/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6172/// 'RHS' attributes and returns the merged version; including for function
6173/// return types.
6174QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6175 QualType LHSCan = getCanonicalType(LHS),
6176 RHSCan = getCanonicalType(RHS);
6177 // If two types are identical, they are compatible.
6178 if (LHSCan == RHSCan)
6179 return LHS;
6180 if (RHSCan->isFunctionType()) {
6181 if (!LHSCan->isFunctionType())
6182 return QualType();
6183 QualType OldReturnType =
6184 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6185 QualType NewReturnType =
6186 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6187 QualType ResReturnType =
6188 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6189 if (ResReturnType.isNull())
6190 return QualType();
6191 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6192 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6193 // In either case, use OldReturnType to build the new function type.
6194 const FunctionType *F = LHS->getAs<FunctionType>();
6195 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00006196 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6197 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006198 QualType ResultType
6199 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006200 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006201 return ResultType;
6202 }
6203 }
6204 return QualType();
6205 }
6206
6207 // If the qualifiers are different, the types can still be merged.
6208 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6209 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6210 if (LQuals != RQuals) {
6211 // If any of these qualifiers are different, we have a type mismatch.
6212 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6213 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6214 return QualType();
6215
6216 // Exactly one GC qualifier difference is allowed: __strong is
6217 // okay if the other type has no GC qualifier but is an Objective
6218 // C object pointer (i.e. implicitly strong by default). We fix
6219 // this by pretending that the unqualified type was actually
6220 // qualified __strong.
6221 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6222 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6223 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6224
6225 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6226 return QualType();
6227
6228 if (GC_L == Qualifiers::Strong)
6229 return LHS;
6230 if (GC_R == Qualifiers::Strong)
6231 return RHS;
6232 return QualType();
6233 }
6234
6235 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6236 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6237 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6238 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6239 if (ResQT == LHSBaseQT)
6240 return LHS;
6241 if (ResQT == RHSBaseQT)
6242 return RHS;
6243 }
6244 return QualType();
6245}
6246
Chris Lattner5426bf62008-04-07 07:01:58 +00006247//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00006248// Integer Predicates
6249//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00006250
Jay Foad4ba2a172011-01-12 09:06:06 +00006251unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00006252 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00006253 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006254 if (T->isBooleanType())
6255 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00006256 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00006257 return (unsigned)getTypeSize(T);
6258}
6259
6260QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00006261 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00006262
6263 // Turn <4 x signed int> -> <4 x unsigned int>
6264 if (const VectorType *VTy = T->getAs<VectorType>())
6265 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00006266 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00006267
6268 // For enums, we return the unsigned version of the base type.
6269 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00006270 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00006271
6272 const BuiltinType *BTy = T->getAs<BuiltinType>();
6273 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006274 switch (BTy->getKind()) {
6275 case BuiltinType::Char_S:
6276 case BuiltinType::SChar:
6277 return UnsignedCharTy;
6278 case BuiltinType::Short:
6279 return UnsignedShortTy;
6280 case BuiltinType::Int:
6281 return UnsignedIntTy;
6282 case BuiltinType::Long:
6283 return UnsignedLongTy;
6284 case BuiltinType::LongLong:
6285 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00006286 case BuiltinType::Int128:
6287 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00006288 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00006289 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006290 }
6291}
6292
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00006293ASTMutationListener::~ASTMutationListener() { }
6294
Chris Lattner86df27b2009-06-14 00:45:47 +00006295
6296//===----------------------------------------------------------------------===//
6297// Builtin Type Computation
6298//===----------------------------------------------------------------------===//
6299
6300/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00006301/// pointer over the consumed characters. This returns the resultant type. If
6302/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6303/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6304/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00006305///
6306/// RequiresICE is filled in on return to indicate whether the value is required
6307/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00006308static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00006309 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00006310 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00006311 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00006312 // Modifiers.
6313 int HowLong = 0;
6314 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00006315 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006316
Chris Lattner33daae62010-10-01 22:42:38 +00006317 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00006318 bool Done = false;
6319 while (!Done) {
6320 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00006321 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006322 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00006323 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006324 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006325 case 'S':
6326 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6327 assert(!Signed && "Can't use 'S' modifier multiple times!");
6328 Signed = true;
6329 break;
6330 case 'U':
6331 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6332 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6333 Unsigned = true;
6334 break;
6335 case 'L':
6336 assert(HowLong <= 2 && "Can't have LLLL modifier");
6337 ++HowLong;
6338 break;
6339 }
6340 }
6341
6342 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00006343
Chris Lattner86df27b2009-06-14 00:45:47 +00006344 // Read the base type.
6345 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00006346 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00006347 case 'v':
6348 assert(HowLong == 0 && !Signed && !Unsigned &&
6349 "Bad modifiers used with 'v'!");
6350 Type = Context.VoidTy;
6351 break;
6352 case 'f':
6353 assert(HowLong == 0 && !Signed && !Unsigned &&
6354 "Bad modifiers used with 'f'!");
6355 Type = Context.FloatTy;
6356 break;
6357 case 'd':
6358 assert(HowLong < 2 && !Signed && !Unsigned &&
6359 "Bad modifiers used with 'd'!");
6360 if (HowLong)
6361 Type = Context.LongDoubleTy;
6362 else
6363 Type = Context.DoubleTy;
6364 break;
6365 case 's':
6366 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6367 if (Unsigned)
6368 Type = Context.UnsignedShortTy;
6369 else
6370 Type = Context.ShortTy;
6371 break;
6372 case 'i':
6373 if (HowLong == 3)
6374 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6375 else if (HowLong == 2)
6376 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6377 else if (HowLong == 1)
6378 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6379 else
6380 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6381 break;
6382 case 'c':
6383 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6384 if (Signed)
6385 Type = Context.SignedCharTy;
6386 else if (Unsigned)
6387 Type = Context.UnsignedCharTy;
6388 else
6389 Type = Context.CharTy;
6390 break;
6391 case 'b': // boolean
6392 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6393 Type = Context.BoolTy;
6394 break;
6395 case 'z': // size_t.
6396 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6397 Type = Context.getSizeType();
6398 break;
6399 case 'F':
6400 Type = Context.getCFConstantStringType();
6401 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00006402 case 'G':
6403 Type = Context.getObjCIdType();
6404 break;
6405 case 'H':
6406 Type = Context.getObjCSelType();
6407 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006408 case 'a':
6409 Type = Context.getBuiltinVaListType();
6410 assert(!Type.isNull() && "builtin va list type not initialized!");
6411 break;
6412 case 'A':
6413 // This is a "reference" to a va_list; however, what exactly
6414 // this means depends on how va_list is defined. There are two
6415 // different kinds of va_list: ones passed by value, and ones
6416 // passed by reference. An example of a by-value va_list is
6417 // x86, where va_list is a char*. An example of by-ref va_list
6418 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6419 // we want this argument to be a char*&; for x86-64, we want
6420 // it to be a __va_list_tag*.
6421 Type = Context.getBuiltinVaListType();
6422 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00006423 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00006424 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00006425 else
Chris Lattner86df27b2009-06-14 00:45:47 +00006426 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00006427 break;
6428 case 'V': {
6429 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00006430 unsigned NumElements = strtoul(Str, &End, 10);
6431 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00006432 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00006433
Chris Lattner14e0e742010-10-01 22:53:11 +00006434 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6435 RequiresICE, false);
6436 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00006437
6438 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00006439 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00006440 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00006441 break;
6442 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00006443 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00006444 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6445 false);
6446 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00006447 Type = Context.getComplexType(ElementType);
6448 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00006449 }
6450 case 'Y' : {
6451 Type = Context.getPointerDiffType();
6452 break;
6453 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006454 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00006455 Type = Context.getFILEType();
6456 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006457 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00006458 return QualType();
6459 }
Mike Stumpfd612db2009-07-28 23:47:15 +00006460 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006461 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00006462 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00006463 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00006464 else
6465 Type = Context.getjmp_bufType();
6466
Mike Stumpfd612db2009-07-28 23:47:15 +00006467 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006468 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00006469 return QualType();
6470 }
6471 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00006472 case 'K':
6473 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6474 Type = Context.getucontext_tType();
6475
6476 if (Type.isNull()) {
6477 Error = ASTContext::GE_Missing_ucontext;
6478 return QualType();
6479 }
6480 break;
Mike Stump782fa302009-07-28 02:25:19 +00006481 }
Mike Stump1eb44332009-09-09 15:08:12 +00006482
Chris Lattner33daae62010-10-01 22:42:38 +00006483 // If there are modifiers and if we're allowed to parse them, go for it.
6484 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00006485 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00006486 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00006487 default: Done = true; --Str; break;
6488 case '*':
6489 case '&': {
6490 // Both pointers and references can have their pointee types
6491 // qualified with an address space.
6492 char *End;
6493 unsigned AddrSpace = strtoul(Str, &End, 10);
6494 if (End != Str && AddrSpace != 0) {
6495 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6496 Str = End;
6497 }
6498 if (c == '*')
6499 Type = Context.getPointerType(Type);
6500 else
6501 Type = Context.getLValueReferenceType(Type);
6502 break;
6503 }
6504 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6505 case 'C':
6506 Type = Type.withConst();
6507 break;
6508 case 'D':
6509 Type = Context.getVolatileType(Type);
6510 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00006511 case 'R':
6512 Type = Type.withRestrict();
6513 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006514 }
6515 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00006516
Chris Lattner14e0e742010-10-01 22:53:11 +00006517 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00006518 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00006519
Chris Lattner86df27b2009-06-14 00:45:47 +00006520 return Type;
6521}
6522
6523/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00006524QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00006525 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00006526 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00006527 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00006528
Chris Lattner5f9e2722011-07-23 10:55:15 +00006529 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00006530
Chris Lattner14e0e742010-10-01 22:53:11 +00006531 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00006532 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00006533 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6534 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006535 if (Error != GE_None)
6536 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00006537
6538 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6539
Chris Lattner86df27b2009-06-14 00:45:47 +00006540 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00006541 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006542 if (Error != GE_None)
6543 return QualType();
6544
Chris Lattner14e0e742010-10-01 22:53:11 +00006545 // If this argument is required to be an IntegerConstantExpression and the
6546 // caller cares, fill in the bitmask we return.
6547 if (RequiresICE && IntegerConstantArgs)
6548 *IntegerConstantArgs |= 1 << ArgTypes.size();
6549
Chris Lattner86df27b2009-06-14 00:45:47 +00006550 // Do array -> pointer decay. The builtin should use the decayed type.
6551 if (Ty->isArrayType())
6552 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00006553
Chris Lattner86df27b2009-06-14 00:45:47 +00006554 ArgTypes.push_back(Ty);
6555 }
6556
6557 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6558 "'.' should only occur at end of builtin type list!");
6559
John McCall00ccbef2010-12-21 00:44:39 +00006560 FunctionType::ExtInfo EI;
6561 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6562
6563 bool Variadic = (TypeStr[0] == '.');
6564
6565 // We really shouldn't be making a no-proto type here, especially in C++.
6566 if (ArgTypes.empty() && Variadic)
6567 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00006568
John McCalle23cf432010-12-14 08:05:40 +00006569 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00006570 EPI.ExtInfo = EI;
6571 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00006572
6573 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00006574}
Eli Friedmana95d7572009-08-19 07:44:53 +00006575
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006576GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6577 GVALinkage External = GVA_StrongExternal;
6578
6579 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006580 switch (L) {
6581 case NoLinkage:
6582 case InternalLinkage:
6583 case UniqueExternalLinkage:
6584 return GVA_Internal;
6585
6586 case ExternalLinkage:
6587 switch (FD->getTemplateSpecializationKind()) {
6588 case TSK_Undeclared:
6589 case TSK_ExplicitSpecialization:
6590 External = GVA_StrongExternal;
6591 break;
6592
6593 case TSK_ExplicitInstantiationDefinition:
6594 return GVA_ExplicitTemplateInstantiation;
6595
6596 case TSK_ExplicitInstantiationDeclaration:
6597 case TSK_ImplicitInstantiation:
6598 External = GVA_TemplateInstantiation;
6599 break;
6600 }
6601 }
6602
6603 if (!FD->isInlined())
6604 return External;
6605
6606 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6607 // GNU or C99 inline semantics. Determine whether this symbol should be
6608 // externally visible.
6609 if (FD->isInlineDefinitionExternallyVisible())
6610 return External;
6611
6612 // C99 inline semantics, where the symbol is not externally visible.
6613 return GVA_C99Inline;
6614 }
6615
6616 // C++0x [temp.explicit]p9:
6617 // [ Note: The intent is that an inline function that is the subject of
6618 // an explicit instantiation declaration will still be implicitly
6619 // instantiated when used so that the body can be considered for
6620 // inlining, but that no out-of-line copy of the inline function would be
6621 // generated in the translation unit. -- end note ]
6622 if (FD->getTemplateSpecializationKind()
6623 == TSK_ExplicitInstantiationDeclaration)
6624 return GVA_C99Inline;
6625
6626 return GVA_CXXInline;
6627}
6628
6629GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6630 // If this is a static data member, compute the kind of template
6631 // specialization. Otherwise, this variable is not part of a
6632 // template.
6633 TemplateSpecializationKind TSK = TSK_Undeclared;
6634 if (VD->isStaticDataMember())
6635 TSK = VD->getTemplateSpecializationKind();
6636
6637 Linkage L = VD->getLinkage();
6638 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6639 VD->getType()->getLinkage() == UniqueExternalLinkage)
6640 L = UniqueExternalLinkage;
6641
6642 switch (L) {
6643 case NoLinkage:
6644 case InternalLinkage:
6645 case UniqueExternalLinkage:
6646 return GVA_Internal;
6647
6648 case ExternalLinkage:
6649 switch (TSK) {
6650 case TSK_Undeclared:
6651 case TSK_ExplicitSpecialization:
6652 return GVA_StrongExternal;
6653
6654 case TSK_ExplicitInstantiationDeclaration:
6655 llvm_unreachable("Variable should not be instantiated");
6656 // Fall through to treat this like any other instantiation.
6657
6658 case TSK_ExplicitInstantiationDefinition:
6659 return GVA_ExplicitTemplateInstantiation;
6660
6661 case TSK_ImplicitInstantiation:
6662 return GVA_TemplateInstantiation;
6663 }
6664 }
6665
David Blaikie7530c032012-01-17 06:56:22 +00006666 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006667}
6668
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00006669bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006670 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6671 if (!VD->isFileVarDecl())
6672 return false;
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00006673 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006674 return false;
6675
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006676 // Weak references don't produce any output by themselves.
6677 if (D->hasAttr<WeakRefAttr>())
6678 return false;
6679
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006680 // Aliases and used decls are required.
6681 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6682 return true;
6683
6684 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6685 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00006686 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00006687 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006688
6689 // Constructors and destructors are required.
6690 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6691 return true;
6692
6693 // The key function for a class is required.
6694 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6695 const CXXRecordDecl *RD = MD->getParent();
6696 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6697 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6698 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6699 return true;
6700 }
6701 }
6702
6703 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6704
6705 // static, static inline, always_inline, and extern inline functions can
6706 // always be deferred. Normal inline functions can be deferred in C99/C++.
6707 // Implicit template instantiations can also be deferred in C++.
6708 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00006709 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006710 return false;
6711 return true;
6712 }
Douglas Gregor94da1582011-09-10 00:22:34 +00006713
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006714 const VarDecl *VD = cast<VarDecl>(D);
6715 assert(VD->isFileVarDecl() && "Expected file scoped var");
6716
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006717 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6718 return false;
6719
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006720 // Structs that have non-trivial constructors or destructors are required.
6721
6722 // FIXME: Handle references.
Sean Hunt023df372011-05-09 18:22:59 +00006723 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006724 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6725 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Sean Hunt023df372011-05-09 18:22:59 +00006726 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6727 RD->hasTrivialCopyConstructor() &&
6728 RD->hasTrivialMoveConstructor() &&
6729 RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006730 return true;
6731 }
6732 }
6733
6734 GVALinkage L = GetGVALinkageForVariable(VD);
6735 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6736 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6737 return false;
6738 }
6739
6740 return true;
6741}
Charles Davis071cc7d2010-08-16 03:33:14 +00006742
Charles Davisee743f92010-11-09 18:04:24 +00006743CallingConv ASTContext::getDefaultMethodCallConv() {
6744 // Pass through to the C++ ABI object
6745 return ABI->getDefaultMethodCallConv();
6746}
6747
Jay Foad4ba2a172011-01-12 09:06:06 +00006748bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00006749 // Pass through to the C++ ABI object
6750 return ABI->isNearlyEmpty(RD);
6751}
6752
Peter Collingbourne14110472011-01-13 18:57:25 +00006753MangleContext *ASTContext::createMangleContext() {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00006754 switch (Target->getCXXABI()) {
Peter Collingbourne14110472011-01-13 18:57:25 +00006755 case CXXABI_ARM:
6756 case CXXABI_Itanium:
6757 return createItaniumMangleContext(*this, getDiagnostics());
6758 case CXXABI_Microsoft:
6759 return createMicrosoftMangleContext(*this, getDiagnostics());
6760 }
David Blaikieb219cfc2011-09-23 05:06:16 +00006761 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00006762}
6763
Charles Davis071cc7d2010-08-16 03:33:14 +00006764CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00006765
6766size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00006767 return ASTRecordLayouts.getMemorySize()
6768 + llvm::capacity_in_bytes(ObjCLayouts)
6769 + llvm::capacity_in_bytes(KeyFunctions)
6770 + llvm::capacity_in_bytes(ObjCImpls)
6771 + llvm::capacity_in_bytes(BlockVarCopyInits)
6772 + llvm::capacity_in_bytes(DeclAttrs)
6773 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6774 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6775 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6776 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6777 + llvm::capacity_in_bytes(OverriddenMethods)
6778 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00006779 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00006780 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00006781}
Ted Kremenekd211cb72011-10-06 05:00:56 +00006782
6783void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6784 ParamIndices[D] = index;
6785}
6786
6787unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6788 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6789 assert(I != ParamIndices.end() &&
6790 "ParmIndices lacks entry set by ParmVarDecl");
6791 return I->second;
6792}