blob: 51cbc3c9d7b8ba6c160a758251b6df2405e45e38 [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());
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002434 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00002435 TL.setTemplateNameLoc(NameLoc);
2436 TL.setLAngleLoc(Args.getLAngleLoc());
2437 TL.setRAngleLoc(Args.getRAngleLoc());
2438 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2439 TL.setArgLocInfo(i, Args[i].getLocInfo());
2440 return DI;
2441}
2442
Mike Stump1eb44332009-09-09 15:08:12 +00002443QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002444ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002445 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002446 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002447 assert(!Template.getAsDependentTemplateName() &&
2448 "No dependent template names here!");
2449
John McCalld5532b62009-11-23 01:53:49 +00002450 unsigned NumArgs = Args.size();
2451
Chris Lattner5f9e2722011-07-23 10:55:15 +00002452 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002453 ArgVec.reserve(NumArgs);
2454 for (unsigned i = 0; i != NumArgs; ++i)
2455 ArgVec.push_back(Args[i].getArgument());
2456
John McCall31f17ec2010-04-27 00:57:59 +00002457 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002458 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002459}
2460
Douglas Gregorb70126a2012-02-03 17:16:23 +00002461#ifndef NDEBUG
2462static bool hasAnyPackExpansions(const TemplateArgument *Args,
2463 unsigned NumArgs) {
2464 for (unsigned I = 0; I != NumArgs; ++I)
2465 if (Args[I].isPackExpansion())
2466 return true;
2467
2468 return true;
2469}
2470#endif
2471
John McCall833ca992009-10-29 08:12:44 +00002472QualType
2473ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002474 const TemplateArgument *Args,
2475 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002476 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002477 assert(!Template.getAsDependentTemplateName() &&
2478 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002479 // Look through qualified template names.
2480 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2481 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002482
Douglas Gregorb70126a2012-02-03 17:16:23 +00002483 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00002484 Template.getAsTemplateDecl() &&
2485 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00002486 QualType CanonType;
2487 if (!Underlying.isNull())
2488 CanonType = getCanonicalType(Underlying);
2489 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00002490 // We can get here with an alias template when the specialization contains
2491 // a pack expansion that does not match up with a parameter pack.
2492 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2493 "Caller must compute aliased type");
2494 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00002495 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2496 NumArgs);
2497 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002498
Douglas Gregor1275ae02009-07-28 23:00:59 +00002499 // Allocate the (non-canonical) template specialization type, but don't
2500 // try to unique it: these types typically have location information that
2501 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002502 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2503 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00002504 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00002505 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002506 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00002507 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2508 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00002509
Douglas Gregor55f6b142009-02-09 18:46:07 +00002510 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002511 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002512}
2513
Mike Stump1eb44332009-09-09 15:08:12 +00002514QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002515ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2516 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002517 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002518 assert(!Template.getAsDependentTemplateName() &&
2519 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002520
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002521 // Look through qualified template names.
2522 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2523 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002524
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002525 // Build the canonical template specialization type.
2526 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002527 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002528 CanonArgs.reserve(NumArgs);
2529 for (unsigned I = 0; I != NumArgs; ++I)
2530 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2531
2532 // Determine whether this canonical template specialization type already
2533 // exists.
2534 llvm::FoldingSetNodeID ID;
2535 TemplateSpecializationType::Profile(ID, CanonTemplate,
2536 CanonArgs.data(), NumArgs, *this);
2537
2538 void *InsertPos = 0;
2539 TemplateSpecializationType *Spec
2540 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2541
2542 if (!Spec) {
2543 // Allocate a new canonical template specialization type.
2544 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2545 sizeof(TemplateArgument) * NumArgs),
2546 TypeAlignment);
2547 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2548 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002549 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002550 Types.push_back(Spec);
2551 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2552 }
2553
2554 assert(Spec->isDependentType() &&
2555 "Non-dependent template-id type must have a canonical type");
2556 return QualType(Spec, 0);
2557}
2558
2559QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002560ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2561 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002562 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002563 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002564 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002565
2566 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002567 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002568 if (T)
2569 return QualType(T, 0);
2570
Douglas Gregor789b1f62010-02-04 18:10:26 +00002571 QualType Canon = NamedType;
2572 if (!Canon.isCanonical()) {
2573 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002574 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2575 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002576 (void)CheckT;
2577 }
2578
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002579 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002580 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002581 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002582 return QualType(T, 0);
2583}
2584
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002585QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002586ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002587 llvm::FoldingSetNodeID ID;
2588 ParenType::Profile(ID, InnerType);
2589
2590 void *InsertPos = 0;
2591 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2592 if (T)
2593 return QualType(T, 0);
2594
2595 QualType Canon = InnerType;
2596 if (!Canon.isCanonical()) {
2597 Canon = getCanonicalType(InnerType);
2598 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2599 assert(!CheckT && "Paren canonical type broken");
2600 (void)CheckT;
2601 }
2602
2603 T = new (*this) ParenType(InnerType, Canon);
2604 Types.push_back(T);
2605 ParenTypes.InsertNode(T, InsertPos);
2606 return QualType(T, 0);
2607}
2608
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002609QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2610 NestedNameSpecifier *NNS,
2611 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002612 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002613 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2614
2615 if (Canon.isNull()) {
2616 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002617 ElaboratedTypeKeyword CanonKeyword = Keyword;
2618 if (Keyword == ETK_None)
2619 CanonKeyword = ETK_Typename;
2620
2621 if (CanonNNS != NNS || CanonKeyword != Keyword)
2622 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002623 }
2624
2625 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002626 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002627
2628 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002629 DependentNameType *T
2630 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002631 if (T)
2632 return QualType(T, 0);
2633
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002634 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002635 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002636 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002637 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002638}
2639
Mike Stump1eb44332009-09-09 15:08:12 +00002640QualType
John McCall33500952010-06-11 00:33:02 +00002641ASTContext::getDependentTemplateSpecializationType(
2642 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002643 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002644 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002645 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00002646 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00002647 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00002648 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2649 ArgCopy.push_back(Args[I].getArgument());
2650 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2651 ArgCopy.size(),
2652 ArgCopy.data());
2653}
2654
2655QualType
2656ASTContext::getDependentTemplateSpecializationType(
2657 ElaboratedTypeKeyword Keyword,
2658 NestedNameSpecifier *NNS,
2659 const IdentifierInfo *Name,
2660 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002661 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00002662 assert((!NNS || NNS->isDependent()) &&
2663 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00002664
Douglas Gregor789b1f62010-02-04 18:10:26 +00002665 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002666 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2667 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002668
2669 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002670 DependentTemplateSpecializationType *T
2671 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002672 if (T)
2673 return QualType(T, 0);
2674
John McCall33500952010-06-11 00:33:02 +00002675 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002676
John McCall33500952010-06-11 00:33:02 +00002677 ElaboratedTypeKeyword CanonKeyword = Keyword;
2678 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2679
2680 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002681 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00002682 for (unsigned I = 0; I != NumArgs; ++I) {
2683 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2684 if (!CanonArgs[I].structurallyEquals(Args[I]))
2685 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002686 }
2687
John McCall33500952010-06-11 00:33:02 +00002688 QualType Canon;
2689 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2690 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2691 Name, NumArgs,
2692 CanonArgs.data());
2693
2694 // Find the insert position again.
2695 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2696 }
2697
2698 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2699 sizeof(TemplateArgument) * NumArgs),
2700 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002701 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002702 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002703 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002704 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002705 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002706}
2707
Douglas Gregorcded4f62011-01-14 17:04:44 +00002708QualType ASTContext::getPackExpansionType(QualType Pattern,
2709 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00002710 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002711 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002712
2713 assert(Pattern->containsUnexpandedParameterPack() &&
2714 "Pack expansions must expand one or more parameter packs");
2715 void *InsertPos = 0;
2716 PackExpansionType *T
2717 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2718 if (T)
2719 return QualType(T, 0);
2720
2721 QualType Canon;
2722 if (!Pattern.isCanonical()) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002723 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002724
2725 // Find the insert position again.
2726 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2727 }
2728
Douglas Gregorcded4f62011-01-14 17:04:44 +00002729 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002730 Types.push_back(T);
2731 PackExpansionTypes.InsertNode(T, InsertPos);
2732 return QualType(T, 0);
2733}
2734
Chris Lattner88cb27a2008-04-07 04:56:42 +00002735/// CmpProtocolNames - Comparison predicate for sorting protocols
2736/// alphabetically.
2737static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2738 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002739 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002740}
2741
John McCallc12c5bb2010-05-15 11:32:37 +00002742static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002743 unsigned NumProtocols) {
2744 if (NumProtocols == 0) return true;
2745
Douglas Gregor61cc2962012-01-02 02:00:30 +00002746 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2747 return false;
2748
John McCall54e14c42009-10-22 22:37:11 +00002749 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00002750 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2751 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00002752 return false;
2753 return true;
2754}
2755
2756static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002757 unsigned &NumProtocols) {
2758 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002759
Chris Lattner88cb27a2008-04-07 04:56:42 +00002760 // Sort protocols, keyed by name.
2761 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2762
Douglas Gregor61cc2962012-01-02 02:00:30 +00002763 // Canonicalize.
2764 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2765 Protocols[I] = Protocols[I]->getCanonicalDecl();
2766
Chris Lattner88cb27a2008-04-07 04:56:42 +00002767 // Remove duplicates.
2768 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2769 NumProtocols = ProtocolsEnd-Protocols;
2770}
2771
John McCallc12c5bb2010-05-15 11:32:37 +00002772QualType ASTContext::getObjCObjectType(QualType BaseType,
2773 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00002774 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002775 // If the base type is an interface and there aren't any protocols
2776 // to add, then the interface type will do just fine.
2777 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2778 return BaseType;
2779
2780 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002781 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002782 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002783 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002784 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2785 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002786
John McCallc12c5bb2010-05-15 11:32:37 +00002787 // Build the canonical type, which has the canonical base type and
2788 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002789 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002790 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2791 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2792 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002793 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00002794 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002795 unsigned UniqueCount = NumProtocols;
2796
John McCall54e14c42009-10-22 22:37:11 +00002797 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002798 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2799 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002800 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002801 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2802 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002803 }
2804
2805 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002806 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2807 }
2808
2809 unsigned Size = sizeof(ObjCObjectTypeImpl);
2810 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2811 void *Mem = Allocate(Size, TypeAlignment);
2812 ObjCObjectTypeImpl *T =
2813 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2814
2815 Types.push_back(T);
2816 ObjCObjectTypes.InsertNode(T, InsertPos);
2817 return QualType(T, 0);
2818}
2819
2820/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2821/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002822QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002823 llvm::FoldingSetNodeID ID;
2824 ObjCObjectPointerType::Profile(ID, ObjectT);
2825
2826 void *InsertPos = 0;
2827 if (ObjCObjectPointerType *QT =
2828 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2829 return QualType(QT, 0);
2830
2831 // Find the canonical object type.
2832 QualType Canonical;
2833 if (!ObjectT.isCanonical()) {
2834 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2835
2836 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002837 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2838 }
2839
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002840 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002841 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2842 ObjCObjectPointerType *QType =
2843 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002844
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002845 Types.push_back(QType);
2846 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002847 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002848}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002849
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002850/// getObjCInterfaceType - Return the unique reference to the type for the
2851/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00002852QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
2853 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002854 if (Decl->TypeForDecl)
2855 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002856
Douglas Gregor0af55012011-12-16 03:12:41 +00002857 if (PrevDecl) {
2858 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
2859 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2860 return QualType(PrevDecl->TypeForDecl, 0);
2861 }
2862
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00002863 // Prefer the definition, if there is one.
2864 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
2865 Decl = Def;
2866
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002867 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2868 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2869 Decl->TypeForDecl = T;
2870 Types.push_back(T);
2871 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002872}
2873
Douglas Gregor72564e72009-02-26 23:50:07 +00002874/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2875/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002876/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002877/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002878/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002879QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002880 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002881 if (tofExpr->isTypeDependent()) {
2882 llvm::FoldingSetNodeID ID;
2883 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002884
Douglas Gregorb1975722009-07-30 23:18:24 +00002885 void *InsertPos = 0;
2886 DependentTypeOfExprType *Canon
2887 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2888 if (Canon) {
2889 // We already have a "canonical" version of an identical, dependent
2890 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002891 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002892 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00002893 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00002894 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002895 Canon
2896 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002897 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2898 toe = Canon;
2899 }
2900 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002901 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002902 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002903 }
Steve Naroff9752f252007-08-01 18:02:17 +00002904 Types.push_back(toe);
2905 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002906}
2907
Steve Naroff9752f252007-08-01 18:02:17 +00002908/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2909/// TypeOfType AST's. The only motivation to unique these nodes would be
2910/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002911/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002912/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002913QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002914 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002915 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002916 Types.push_back(tot);
2917 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002918}
2919
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002920/// getDecltypeForExpr - Given an expr, will return the decltype for that
2921/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad4ba2a172011-01-12 09:06:06 +00002922static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002923 if (e->isTypeDependent())
2924 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002925
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002926 // If e is an id expression or a class member access, decltype(e) is defined
2927 // as the type of the entity named by e.
2928 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2929 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2930 return VD->getType();
2931 }
2932 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2933 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2934 return FD->getType();
2935 }
2936 // If e is a function call or an invocation of an overloaded operator,
2937 // (parentheses around e are ignored), decltype(e) is defined as the
2938 // return type of that function.
2939 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2940 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002941
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002942 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002943
2944 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002945 // defined as T&, otherwise decltype(e) is defined as T.
John McCall7eb0a9e2010-11-24 05:12:34 +00002946 if (e->isLValue())
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002947 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002948
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002949 return T;
2950}
2951
Anders Carlsson395b4752009-06-24 19:06:50 +00002952/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2953/// DecltypeType AST's. The only motivation to unique these nodes would be
2954/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002955/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00002956/// on canonical types (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002957QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002958 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00002959
2960 // C++0x [temp.type]p2:
2961 // If an expression e involves a template parameter, decltype(e) denotes a
2962 // unique dependent type. Two such decltype-specifiers refer to the same
2963 // type only if their expressions are equivalent (14.5.6.1).
2964 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002965 llvm::FoldingSetNodeID ID;
2966 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002967
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002968 void *InsertPos = 0;
2969 DependentDecltypeType *Canon
2970 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2971 if (Canon) {
2972 // We already have a "canonical" version of an equivalent, dependent
2973 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002974 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002975 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00002976 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002977 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002978 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002979 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2980 dt = Canon;
2981 }
2982 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002983 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002984 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002985 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002986 Types.push_back(dt);
2987 return QualType(dt, 0);
2988}
2989
Sean Huntca63c202011-05-24 22:41:36 +00002990/// getUnaryTransformationType - We don't unique these, since the memory
2991/// savings are minimal and these are rare.
2992QualType ASTContext::getUnaryTransformType(QualType BaseType,
2993 QualType UnderlyingType,
2994 UnaryTransformType::UTTKind Kind)
2995 const {
2996 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00002997 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2998 Kind,
2999 UnderlyingType->isDependentType() ?
3000 QualType() : UnderlyingType);
Sean Huntca63c202011-05-24 22:41:36 +00003001 Types.push_back(Ty);
3002 return QualType(Ty, 0);
3003}
3004
Richard Smith483b9f32011-02-21 20:05:19 +00003005/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00003006QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00003007 void *InsertPos = 0;
3008 if (!DeducedType.isNull()) {
3009 // Look in the folding set for an existing type.
3010 llvm::FoldingSetNodeID ID;
3011 AutoType::Profile(ID, DeducedType);
3012 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3013 return QualType(AT, 0);
3014 }
3015
3016 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3017 Types.push_back(AT);
3018 if (InsertPos)
3019 AutoTypes.InsertNode(AT, InsertPos);
3020 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003021}
3022
Eli Friedmanb001de72011-10-06 23:00:33 +00003023/// getAtomicType - Return the uniqued reference to the atomic type for
3024/// the given value type.
3025QualType ASTContext::getAtomicType(QualType T) const {
3026 // Unique pointers, to guarantee there is only one pointer of a particular
3027 // structure.
3028 llvm::FoldingSetNodeID ID;
3029 AtomicType::Profile(ID, T);
3030
3031 void *InsertPos = 0;
3032 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3033 return QualType(AT, 0);
3034
3035 // If the atomic value type isn't canonical, this won't be a canonical type
3036 // either, so fill in the canonical type field.
3037 QualType Canonical;
3038 if (!T.isCanonical()) {
3039 Canonical = getAtomicType(getCanonicalType(T));
3040
3041 // Get the new insert position for the node we care about.
3042 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3043 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3044 }
3045 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3046 Types.push_back(New);
3047 AtomicTypes.InsertNode(New, InsertPos);
3048 return QualType(New, 0);
3049}
3050
Richard Smithad762fc2011-04-14 22:09:26 +00003051/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3052QualType ASTContext::getAutoDeductType() const {
3053 if (AutoDeductTy.isNull())
3054 AutoDeductTy = getAutoType(QualType());
3055 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3056 return AutoDeductTy;
3057}
3058
3059/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3060QualType ASTContext::getAutoRRefDeductType() const {
3061 if (AutoRRefDeductTy.isNull())
3062 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3063 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3064 return AutoRRefDeductTy;
3065}
3066
Reid Spencer5f016e22007-07-11 17:01:13 +00003067/// getTagDeclType - Return the unique reference to the type for the
3068/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003069QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003070 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003071 // FIXME: What is the design on getTagDeclType when it requires casting
3072 // away const? mutable?
3073 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003074}
3075
Mike Stump1eb44332009-09-09 15:08:12 +00003076/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3077/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3078/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003079CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003080 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003081}
3082
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003083/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3084CanQualType ASTContext::getIntMaxType() const {
3085 return getFromTargetType(Target->getIntMaxType());
3086}
3087
3088/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3089CanQualType ASTContext::getUIntMaxType() const {
3090 return getFromTargetType(Target->getUIntMaxType());
3091}
3092
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003093/// getSignedWCharType - Return the type of "signed wchar_t".
3094/// Used when in C++, as a GCC extension.
3095QualType ASTContext::getSignedWCharType() const {
3096 // FIXME: derive from "Target" ?
3097 return WCharTy;
3098}
3099
3100/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3101/// Used when in C++, as a GCC extension.
3102QualType ASTContext::getUnsignedWCharType() const {
3103 // FIXME: derive from "Target" ?
3104 return UnsignedIntTy;
3105}
3106
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003107/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003108/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3109QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003110 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003111}
3112
Chris Lattnere6327742008-04-02 05:18:44 +00003113//===----------------------------------------------------------------------===//
3114// Type Operators
3115//===----------------------------------------------------------------------===//
3116
Jay Foad4ba2a172011-01-12 09:06:06 +00003117CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003118 // Push qualifiers into arrays, and then discard any remaining
3119 // qualifiers.
3120 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003121 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003122 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003123 QualType Result;
3124 if (isa<ArrayType>(Ty)) {
3125 Result = getArrayDecayedType(QualType(Ty,0));
3126 } else if (isa<FunctionType>(Ty)) {
3127 Result = getPointerType(QualType(Ty, 0));
3128 } else {
3129 Result = QualType(Ty, 0);
3130 }
3131
3132 return CanQualType::CreateUnsafe(Result);
3133}
3134
John McCall62c28c82011-01-18 07:41:22 +00003135QualType ASTContext::getUnqualifiedArrayType(QualType type,
3136 Qualifiers &quals) {
3137 SplitQualType splitType = type.getSplitUnqualifiedType();
3138
3139 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3140 // the unqualified desugared type and then drops it on the floor.
3141 // We then have to strip that sugar back off with
3142 // getUnqualifiedDesugaredType(), which is silly.
3143 const ArrayType *AT =
3144 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
3145
3146 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003147 if (!AT) {
John McCall62c28c82011-01-18 07:41:22 +00003148 quals = splitType.second;
3149 return QualType(splitType.first, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003150 }
3151
John McCall62c28c82011-01-18 07:41:22 +00003152 // Otherwise, recurse on the array's element type.
3153 QualType elementType = AT->getElementType();
3154 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3155
3156 // If that didn't change the element type, AT has no qualifiers, so we
3157 // can just use the results in splitType.
3158 if (elementType == unqualElementType) {
3159 assert(quals.empty()); // from the recursive call
3160 quals = splitType.second;
3161 return QualType(splitType.first, 0);
3162 }
3163
3164 // Otherwise, add in the qualifiers from the outermost type, then
3165 // build the type back up.
3166 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003167
Douglas Gregor9dadd942010-05-17 18:45:21 +00003168 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003169 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003170 CAT->getSizeModifier(), 0);
3171 }
3172
Douglas Gregor9dadd942010-05-17 18:45:21 +00003173 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003174 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003175 }
3176
Douglas Gregor9dadd942010-05-17 18:45:21 +00003177 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003178 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003179 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003180 VAT->getSizeModifier(),
3181 VAT->getIndexTypeCVRQualifiers(),
3182 VAT->getBracketsRange());
3183 }
3184
3185 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003186 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003187 DSAT->getSizeModifier(), 0,
3188 SourceRange());
3189}
3190
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003191/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3192/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3193/// they point to and return true. If T1 and T2 aren't pointer types
3194/// or pointer-to-member types, or if they are not similar at this
3195/// level, returns false and leaves T1 and T2 unchanged. Top-level
3196/// qualifiers on T1 and T2 are ignored. This function will typically
3197/// be called in a loop that successively "unwraps" pointer and
3198/// pointer-to-member types to compare them at each level.
3199bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3200 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3201 *T2PtrType = T2->getAs<PointerType>();
3202 if (T1PtrType && T2PtrType) {
3203 T1 = T1PtrType->getPointeeType();
3204 T2 = T2PtrType->getPointeeType();
3205 return true;
3206 }
3207
3208 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3209 *T2MPType = T2->getAs<MemberPointerType>();
3210 if (T1MPType && T2MPType &&
3211 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3212 QualType(T2MPType->getClass(), 0))) {
3213 T1 = T1MPType->getPointeeType();
3214 T2 = T2MPType->getPointeeType();
3215 return true;
3216 }
3217
3218 if (getLangOptions().ObjC1) {
3219 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3220 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3221 if (T1OPType && T2OPType) {
3222 T1 = T1OPType->getPointeeType();
3223 T2 = T2OPType->getPointeeType();
3224 return true;
3225 }
3226 }
3227
3228 // FIXME: Block pointers, too?
3229
3230 return false;
3231}
3232
Jay Foad4ba2a172011-01-12 09:06:06 +00003233DeclarationNameInfo
3234ASTContext::getNameForTemplate(TemplateName Name,
3235 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003236 switch (Name.getKind()) {
3237 case TemplateName::QualifiedTemplate:
3238 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003239 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003240 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3241 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003242
John McCall14606042011-06-30 08:33:18 +00003243 case TemplateName::OverloadedTemplate: {
3244 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3245 // DNInfo work in progress: CHECKME: what about DNLoc?
3246 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3247 }
3248
3249 case TemplateName::DependentTemplate: {
3250 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003251 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003252 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003253 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3254 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003255 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003256 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3257 // DNInfo work in progress: FIXME: source locations?
3258 DeclarationNameLoc DNLoc;
3259 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3260 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3261 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003262 }
3263 }
3264
John McCall14606042011-06-30 08:33:18 +00003265 case TemplateName::SubstTemplateTemplateParm: {
3266 SubstTemplateTemplateParmStorage *subst
3267 = Name.getAsSubstTemplateTemplateParm();
3268 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3269 NameLoc);
3270 }
3271
3272 case TemplateName::SubstTemplateTemplateParmPack: {
3273 SubstTemplateTemplateParmPackStorage *subst
3274 = Name.getAsSubstTemplateTemplateParmPack();
3275 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3276 NameLoc);
3277 }
3278 }
3279
3280 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003281}
3282
Jay Foad4ba2a172011-01-12 09:06:06 +00003283TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003284 switch (Name.getKind()) {
3285 case TemplateName::QualifiedTemplate:
3286 case TemplateName::Template: {
3287 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003288 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003289 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003290 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3291
3292 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003293 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003294 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003295
John McCall14606042011-06-30 08:33:18 +00003296 case TemplateName::OverloadedTemplate:
3297 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003298
John McCall14606042011-06-30 08:33:18 +00003299 case TemplateName::DependentTemplate: {
3300 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3301 assert(DTN && "Non-dependent template names must refer to template decls.");
3302 return DTN->CanonicalTemplateName;
3303 }
3304
3305 case TemplateName::SubstTemplateTemplateParm: {
3306 SubstTemplateTemplateParmStorage *subst
3307 = Name.getAsSubstTemplateTemplateParm();
3308 return getCanonicalTemplateName(subst->getReplacement());
3309 }
3310
3311 case TemplateName::SubstTemplateTemplateParmPack: {
3312 SubstTemplateTemplateParmPackStorage *subst
3313 = Name.getAsSubstTemplateTemplateParmPack();
3314 TemplateTemplateParmDecl *canonParameter
3315 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3316 TemplateArgument canonArgPack
3317 = getCanonicalTemplateArgument(subst->getArgumentPack());
3318 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3319 }
3320 }
3321
3322 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003323}
3324
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003325bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3326 X = getCanonicalTemplateName(X);
3327 Y = getCanonicalTemplateName(Y);
3328 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3329}
3330
Mike Stump1eb44332009-09-09 15:08:12 +00003331TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003332ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003333 switch (Arg.getKind()) {
3334 case TemplateArgument::Null:
3335 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003336
Douglas Gregor1275ae02009-07-28 23:00:59 +00003337 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003338 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003339
Douglas Gregor1275ae02009-07-28 23:00:59 +00003340 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00003341 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003342
Douglas Gregor788cd062009-11-11 01:00:40 +00003343 case TemplateArgument::Template:
3344 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003345
3346 case TemplateArgument::TemplateExpansion:
3347 return TemplateArgument(getCanonicalTemplateName(
3348 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003349 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003350
Douglas Gregor1275ae02009-07-28 23:00:59 +00003351 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00003352 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003353 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003354
Douglas Gregor1275ae02009-07-28 23:00:59 +00003355 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003356 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003357
Douglas Gregor1275ae02009-07-28 23:00:59 +00003358 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003359 if (Arg.pack_size() == 0)
3360 return Arg;
3361
Douglas Gregor910f8002010-11-07 23:05:16 +00003362 TemplateArgument *CanonArgs
3363 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003364 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003365 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003366 AEnd = Arg.pack_end();
3367 A != AEnd; (void)++A, ++Idx)
3368 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003369
Douglas Gregor910f8002010-11-07 23:05:16 +00003370 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003371 }
3372 }
3373
3374 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00003375 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00003376}
3377
Douglas Gregord57959a2009-03-27 23:10:48 +00003378NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003379ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003380 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003381 return 0;
3382
3383 switch (NNS->getKind()) {
3384 case NestedNameSpecifier::Identifier:
3385 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003386 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003387 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3388 NNS->getAsIdentifier());
3389
3390 case NestedNameSpecifier::Namespace:
3391 // A namespace is canonical; build a nested-name-specifier with
3392 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003393 return NestedNameSpecifier::Create(*this, 0,
3394 NNS->getAsNamespace()->getOriginalNamespace());
3395
3396 case NestedNameSpecifier::NamespaceAlias:
3397 // A namespace is canonical; build a nested-name-specifier with
3398 // this namespace and no prefix.
3399 return NestedNameSpecifier::Create(*this, 0,
3400 NNS->getAsNamespaceAlias()->getNamespace()
3401 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003402
3403 case NestedNameSpecifier::TypeSpec:
3404 case NestedNameSpecifier::TypeSpecWithTemplate: {
3405 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003406
3407 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3408 // break it apart into its prefix and identifier, then reconsititute those
3409 // as the canonical nested-name-specifier. This is required to canonicalize
3410 // a dependent nested-name-specifier involving typedefs of dependent-name
3411 // types, e.g.,
3412 // typedef typename T::type T1;
3413 // typedef typename T1::type T2;
3414 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3415 NestedNameSpecifier *Prefix
3416 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3417 return NestedNameSpecifier::Create(*this, Prefix,
3418 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3419 }
3420
Douglas Gregor643f8432010-11-04 00:14:23 +00003421 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor264bf662010-11-04 00:09:33 +00003422 if (const DependentTemplateSpecializationType *DTST
3423 = T->getAs<DependentTemplateSpecializationType>()) {
3424 NestedNameSpecifier *Prefix
3425 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003426
3427 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3428 Prefix, DTST->getIdentifier(),
3429 DTST->getNumArgs(),
3430 DTST->getArgs());
Douglas Gregor264bf662010-11-04 00:09:33 +00003431 T = getCanonicalType(T);
3432 }
3433
John McCall3b657512011-01-19 10:06:00 +00003434 return NestedNameSpecifier::Create(*this, 0, false,
3435 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003436 }
3437
3438 case NestedNameSpecifier::Global:
3439 // The global specifier is canonical and unique.
3440 return NNS;
3441 }
3442
David Blaikie7530c032012-01-17 06:56:22 +00003443 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00003444}
3445
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003446
Jay Foad4ba2a172011-01-12 09:06:06 +00003447const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003448 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003449 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003450 // Handle the common positive case fast.
3451 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3452 return AT;
3453 }
Mike Stump1eb44332009-09-09 15:08:12 +00003454
John McCall0953e762009-09-24 19:53:00 +00003455 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003456 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003457 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003458
John McCall0953e762009-09-24 19:53:00 +00003459 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003460 // implements C99 6.7.3p8: "If the specification of an array type includes
3461 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003462
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003463 // If we get here, we either have type qualifiers on the type, or we have
3464 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003465 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003466
John McCall3b657512011-01-19 10:06:00 +00003467 SplitQualType split = T.getSplitDesugaredType();
3468 Qualifiers qs = split.second;
Mike Stump1eb44332009-09-09 15:08:12 +00003469
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003470 // If we have a simple case, just return now.
John McCall3b657512011-01-19 10:06:00 +00003471 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3472 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003473 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003474
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003475 // Otherwise, we have an array and we have qualifiers on it. Push the
3476 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003477 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003478
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003479 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3480 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3481 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003482 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003483 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3484 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3485 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003486 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003487
Mike Stump1eb44332009-09-09 15:08:12 +00003488 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003489 = dyn_cast<DependentSizedArrayType>(ATy))
3490 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003491 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003492 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003493 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003494 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003495 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003496
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003497 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003498 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003499 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003500 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003501 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003502 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003503}
3504
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003505QualType ASTContext::getAdjustedParameterType(QualType T) {
3506 // C99 6.7.5.3p7:
3507 // A declaration of a parameter as "array of type" shall be
3508 // adjusted to "qualified pointer to type", where the type
3509 // qualifiers (if any) are those specified within the [ and ] of
3510 // the array type derivation.
3511 if (T->isArrayType())
3512 return getArrayDecayedType(T);
3513
3514 // C99 6.7.5.3p8:
3515 // A declaration of a parameter as "function returning type"
3516 // shall be adjusted to "pointer to function returning type", as
3517 // in 6.3.2.1.
3518 if (T->isFunctionType())
3519 return getPointerType(T);
3520
3521 return T;
3522}
3523
3524QualType ASTContext::getSignatureParameterType(QualType T) {
3525 T = getVariableArrayDecayedType(T);
3526 T = getAdjustedParameterType(T);
3527 return T.getUnqualifiedType();
3528}
3529
Chris Lattnere6327742008-04-02 05:18:44 +00003530/// getArrayDecayedType - Return the properly qualified result of decaying the
3531/// specified array type to a pointer. This operation is non-trivial when
3532/// handling typedefs etc. The canonical type of "T" must be an array type,
3533/// this returns a pointer to a properly qualified element of the array.
3534///
3535/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003536QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003537 // Get the element type with 'getAsArrayType' so that we don't lose any
3538 // typedefs in the element type of the array. This also handles propagation
3539 // of type qualifiers from the array type into the element type if present
3540 // (C99 6.7.3p8).
3541 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3542 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003543
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003544 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003545
3546 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003547 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003548}
3549
John McCall3b657512011-01-19 10:06:00 +00003550QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3551 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003552}
3553
John McCall3b657512011-01-19 10:06:00 +00003554QualType ASTContext::getBaseElementType(QualType type) const {
3555 Qualifiers qs;
3556 while (true) {
3557 SplitQualType split = type.getSplitDesugaredType();
3558 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3559 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003560
John McCall3b657512011-01-19 10:06:00 +00003561 type = array->getElementType();
3562 qs.addConsistentQualifiers(split.second);
3563 }
Mike Stump1eb44332009-09-09 15:08:12 +00003564
John McCall3b657512011-01-19 10:06:00 +00003565 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003566}
3567
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003568/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003569uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003570ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3571 uint64_t ElementCount = 1;
3572 do {
3573 ElementCount *= CA->getSize().getZExtValue();
3574 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3575 } while (CA);
3576 return ElementCount;
3577}
3578
Reid Spencer5f016e22007-07-11 17:01:13 +00003579/// getFloatingRank - Return a relative rank for floating point types.
3580/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003581static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003582 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003583 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003584
John McCall183700f2009-09-21 23:43:11 +00003585 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3586 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003587 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00003588 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00003589 case BuiltinType::Float: return FloatRank;
3590 case BuiltinType::Double: return DoubleRank;
3591 case BuiltinType::LongDouble: return LongDoubleRank;
3592 }
3593}
3594
Mike Stump1eb44332009-09-09 15:08:12 +00003595/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3596/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003597/// 'typeDomain' is a real floating point or complex type.
3598/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003599QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3600 QualType Domain) const {
3601 FloatingRank EltRank = getFloatingRank(Size);
3602 if (Domain->isComplexType()) {
3603 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00003604 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00003605 case FloatRank: return FloatComplexTy;
3606 case DoubleRank: return DoubleComplexTy;
3607 case LongDoubleRank: return LongDoubleComplexTy;
3608 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003609 }
Chris Lattner1361b112008-04-06 23:58:54 +00003610
3611 assert(Domain->isRealFloatingType() && "Unknown domain!");
3612 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00003613 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattner1361b112008-04-06 23:58:54 +00003614 case FloatRank: return FloatTy;
3615 case DoubleRank: return DoubleTy;
3616 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003617 }
David Blaikie561d3ab2012-01-17 02:30:50 +00003618 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00003619}
3620
Chris Lattner7cfeb082008-04-06 23:55:33 +00003621/// getFloatingTypeOrder - Compare the rank of the two specified floating
3622/// point types, ignoring the domain of the type (i.e. 'double' ==
3623/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003624/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003625int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003626 FloatingRank LHSR = getFloatingRank(LHS);
3627 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003628
Chris Lattnera75cea32008-04-06 23:38:49 +00003629 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003630 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003631 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003632 return 1;
3633 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003634}
3635
Chris Lattnerf52ab252008-04-06 22:59:24 +00003636/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3637/// routine will assert if passed a built-in type that isn't an integer or enum,
3638/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003639unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003640 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003641
Chris Lattnerf52ab252008-04-06 22:59:24 +00003642 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003643 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00003644 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003645 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003646 case BuiltinType::Char_S:
3647 case BuiltinType::Char_U:
3648 case BuiltinType::SChar:
3649 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003650 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003651 case BuiltinType::Short:
3652 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003653 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003654 case BuiltinType::Int:
3655 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003656 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003657 case BuiltinType::Long:
3658 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003659 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003660 case BuiltinType::LongLong:
3661 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003662 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003663 case BuiltinType::Int128:
3664 case BuiltinType::UInt128:
3665 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003666 }
3667}
3668
Eli Friedman04e83572009-08-20 04:21:42 +00003669/// \brief Whether this is a promotable bitfield reference according
3670/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3671///
3672/// \returns the type this bit-field will promote to, or NULL if no
3673/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00003674QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003675 if (E->isTypeDependent() || E->isValueDependent())
3676 return QualType();
3677
Eli Friedman04e83572009-08-20 04:21:42 +00003678 FieldDecl *Field = E->getBitField();
3679 if (!Field)
3680 return QualType();
3681
3682 QualType FT = Field->getType();
3683
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003684 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00003685 uint64_t IntSize = getTypeSize(IntTy);
3686 // GCC extension compatibility: if the bit-field size is less than or equal
3687 // to the size of int, it gets promoted no matter what its type is.
3688 // For instance, unsigned long bf : 4 gets promoted to signed int.
3689 if (BitWidth < IntSize)
3690 return IntTy;
3691
3692 if (BitWidth == IntSize)
3693 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3694
3695 // Types bigger than int are not subject to promotions, and therefore act
3696 // like the base type.
3697 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3698 // is ridiculous.
3699 return QualType();
3700}
3701
Eli Friedmana95d7572009-08-19 07:44:53 +00003702/// getPromotedIntegerType - Returns the type that Promotable will
3703/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3704/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003705QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003706 assert(!Promotable.isNull());
3707 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003708 if (const EnumType *ET = Promotable->getAs<EnumType>())
3709 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00003710
3711 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3712 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3713 // (3.9.1) can be converted to a prvalue of the first of the following
3714 // types that can represent all the values of its underlying type:
3715 // int, unsigned int, long int, unsigned long int, long long int, or
3716 // unsigned long long int [...]
3717 // FIXME: Is there some better way to compute this?
3718 if (BT->getKind() == BuiltinType::WChar_S ||
3719 BT->getKind() == BuiltinType::WChar_U ||
3720 BT->getKind() == BuiltinType::Char16 ||
3721 BT->getKind() == BuiltinType::Char32) {
3722 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3723 uint64_t FromSize = getTypeSize(BT);
3724 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3725 LongLongTy, UnsignedLongLongTy };
3726 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3727 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3728 if (FromSize < ToSize ||
3729 (FromSize == ToSize &&
3730 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3731 return PromoteTypes[Idx];
3732 }
3733 llvm_unreachable("char type should fit into long long");
3734 }
3735 }
3736
3737 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00003738 if (Promotable->isSignedIntegerType())
3739 return IntTy;
3740 uint64_t PromotableSize = getTypeSize(Promotable);
3741 uint64_t IntSize = getTypeSize(IntTy);
3742 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3743 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3744}
3745
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003746/// \brief Recurses in pointer/array types until it finds an objc retainable
3747/// type and returns its ownership.
3748Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3749 while (!T.isNull()) {
3750 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3751 return T.getObjCLifetime();
3752 if (T->isArrayType())
3753 T = getBaseElementType(T);
3754 else if (const PointerType *PT = T->getAs<PointerType>())
3755 T = PT->getPointeeType();
3756 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00003757 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003758 else
3759 break;
3760 }
3761
3762 return Qualifiers::OCL_None;
3763}
3764
Mike Stump1eb44332009-09-09 15:08:12 +00003765/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003766/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003767/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003768int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00003769 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3770 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003771 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003772
Chris Lattnerf52ab252008-04-06 22:59:24 +00003773 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3774 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003775
Chris Lattner7cfeb082008-04-06 23:55:33 +00003776 unsigned LHSRank = getIntegerRank(LHSC);
3777 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003778
Chris Lattner7cfeb082008-04-06 23:55:33 +00003779 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3780 if (LHSRank == RHSRank) return 0;
3781 return LHSRank > RHSRank ? 1 : -1;
3782 }
Mike Stump1eb44332009-09-09 15:08:12 +00003783
Chris Lattner7cfeb082008-04-06 23:55:33 +00003784 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3785 if (LHSUnsigned) {
3786 // If the unsigned [LHS] type is larger, return it.
3787 if (LHSRank >= RHSRank)
3788 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003789
Chris Lattner7cfeb082008-04-06 23:55:33 +00003790 // If the signed type can represent all values of the unsigned type, it
3791 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003792 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003793 return -1;
3794 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003795
Chris Lattner7cfeb082008-04-06 23:55:33 +00003796 // If the unsigned [RHS] type is larger, return it.
3797 if (RHSRank >= LHSRank)
3798 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003799
Chris Lattner7cfeb082008-04-06 23:55:33 +00003800 // If the signed type can represent all values of the unsigned type, it
3801 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003802 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003803 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003804}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003805
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003806static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003807CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3808 DeclContext *DC, IdentifierInfo *Id) {
3809 SourceLocation Loc;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003810 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003811 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003812 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003813 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003814}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003815
Mike Stump1eb44332009-09-09 15:08:12 +00003816// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003817QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003818 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003819 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003820 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003821 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003822 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003823
Anders Carlssonf06273f2007-11-19 00:25:30 +00003824 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003825
Anders Carlsson71993dd2007-08-17 05:31:46 +00003826 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003827 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003828 // int flags;
3829 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003830 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003831 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003832 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003833 FieldTypes[3] = LongTy;
3834
Anders Carlsson71993dd2007-08-17 05:31:46 +00003835 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003836 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003837 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003838 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00003839 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003840 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003841 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003842 /*Mutable=*/false,
3843 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003844 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003845 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003846 }
3847
Douglas Gregor838db382010-02-11 01:19:42 +00003848 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003849 }
Mike Stump1eb44332009-09-09 15:08:12 +00003850
Anders Carlsson71993dd2007-08-17 05:31:46 +00003851 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003852}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003853
Douglas Gregor319ac892009-04-23 22:29:11 +00003854void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003855 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003856 assert(Rec && "Invalid CFConstantStringType");
3857 CFConstantStringTypeDecl = Rec->getDecl();
3858}
3859
Jay Foad4ba2a172011-01-12 09:06:06 +00003860QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00003861 if (BlockDescriptorType)
3862 return getTagDeclType(BlockDescriptorType);
3863
3864 RecordDecl *T;
3865 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003866 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003867 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003868 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003869
3870 QualType FieldTypes[] = {
3871 UnsignedLongTy,
3872 UnsignedLongTy,
3873 };
3874
3875 const char *FieldNames[] = {
3876 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003877 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003878 };
3879
3880 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003881 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003882 SourceLocation(),
3883 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003884 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003885 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003886 /*Mutable=*/false,
3887 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003888 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003889 T->addDecl(Field);
3890 }
3891
Douglas Gregor838db382010-02-11 01:19:42 +00003892 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003893
3894 BlockDescriptorType = T;
3895
3896 return getTagDeclType(BlockDescriptorType);
3897}
3898
Jay Foad4ba2a172011-01-12 09:06:06 +00003899QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00003900 if (BlockDescriptorExtendedType)
3901 return getTagDeclType(BlockDescriptorExtendedType);
3902
3903 RecordDecl *T;
3904 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003905 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003906 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003907 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003908
3909 QualType FieldTypes[] = {
3910 UnsignedLongTy,
3911 UnsignedLongTy,
3912 getPointerType(VoidPtrTy),
3913 getPointerType(VoidPtrTy)
3914 };
3915
3916 const char *FieldNames[] = {
3917 "reserved",
3918 "Size",
3919 "CopyFuncPtr",
3920 "DestroyFuncPtr"
3921 };
3922
3923 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003924 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00003925 SourceLocation(),
3926 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003927 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003928 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003929 /*Mutable=*/false,
3930 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003931 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003932 T->addDecl(Field);
3933 }
3934
Douglas Gregor838db382010-02-11 01:19:42 +00003935 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003936
3937 BlockDescriptorExtendedType = T;
3938
3939 return getTagDeclType(BlockDescriptorExtendedType);
3940}
3941
Jay Foad4ba2a172011-01-12 09:06:06 +00003942bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCallf85e1932011-06-15 23:02:42 +00003943 if (Ty->isObjCRetainableType())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003944 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003945 if (getLangOptions().CPlusPlus) {
3946 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3947 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Huntffe37fd2011-05-25 20:50:04 +00003948 return RD->hasConstCopyConstructor();
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003949
3950 }
3951 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003952 return false;
3953}
3954
Jay Foad4ba2a172011-01-12 09:06:06 +00003955QualType
Chris Lattner5f9e2722011-07-23 10:55:15 +00003956ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003957 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003958 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003959 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003960 // unsigned int __flags;
3961 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003962 // void *__copy_helper; // as needed
3963 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003964 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003965 // } *
3966
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003967 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3968
3969 // FIXME: Move up
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003970 SmallString<36> Name;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003971 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3972 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003973 RecordDecl *T;
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003974 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003975 T->startDefinition();
3976 QualType Int32Ty = IntTy;
3977 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3978 QualType FieldTypes[] = {
3979 getPointerType(VoidPtrTy),
3980 getPointerType(getTagDeclType(T)),
3981 Int32Ty,
3982 Int32Ty,
3983 getPointerType(VoidPtrTy),
3984 getPointerType(VoidPtrTy),
3985 Ty
3986 };
3987
Chris Lattner5f9e2722011-07-23 10:55:15 +00003988 StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003989 "__isa",
3990 "__forwarding",
3991 "__flags",
3992 "__size",
3993 "__copy_helper",
3994 "__destroy_helper",
3995 DeclName,
3996 };
3997
3998 for (size_t i = 0; i < 7; ++i) {
3999 if (!HasCopyAndDispose && i >=4 && i <= 5)
4000 continue;
4001 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004002 SourceLocation(),
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004003 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004004 FieldTypes[i], /*TInfo=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004005 /*BitWidth=*/0, /*Mutable=*/false,
4006 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00004007 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004008 T->addDecl(Field);
4009 }
4010
Douglas Gregor838db382010-02-11 01:19:42 +00004011 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004012
4013 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00004014}
4015
Douglas Gregore97179c2011-09-08 01:46:34 +00004016TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4017 if (!ObjCInstanceTypeDecl)
4018 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4019 getTranslationUnitDecl(),
4020 SourceLocation(),
4021 SourceLocation(),
4022 &Idents.get("instancetype"),
4023 getTrivialTypeSourceInfo(getObjCIdType()));
4024 return ObjCInstanceTypeDecl;
4025}
4026
Anders Carlssone8c49532007-10-29 06:33:42 +00004027// This returns true if a type has been typedefed to BOOL:
4028// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004029static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004030 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004031 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4032 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004033
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004034 return false;
4035}
4036
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004037/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004038/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004039CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004040 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4041 return CharUnits::Zero();
4042
Ken Dyck199c3d62010-01-11 17:06:35 +00004043 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004044
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004045 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004046 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004047 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004048 // Treat arrays as pointers, since that's how they're passed in.
4049 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004050 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004051 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004052}
4053
4054static inline
4055std::string charUnitsToString(const CharUnits &CU) {
4056 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004057}
4058
John McCall6b5a61b2011-02-07 10:33:21 +00004059/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004060/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004061std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4062 std::string S;
4063
David Chisnall5e530af2009-11-17 19:33:30 +00004064 const BlockDecl *Decl = Expr->getBlockDecl();
4065 QualType BlockTy =
4066 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4067 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00004068 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00004069 // Compute size of all parameters.
4070 // Start with computing size of a pointer in number of bytes.
4071 // FIXME: There might(should) be a better way of doing this computation!
4072 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004073 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4074 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004075 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004076 E = Decl->param_end(); PI != E; ++PI) {
4077 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004078 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00004079 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004080 ParmOffset += sz;
4081 }
4082 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004083 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004084 // Block pointer and offset.
4085 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004086
4087 // Argument types.
4088 ParmOffset = PtrSize;
4089 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4090 Decl->param_end(); PI != E; ++PI) {
4091 ParmVarDecl *PVDecl = *PI;
4092 QualType PType = PVDecl->getOriginalType();
4093 if (const ArrayType *AT =
4094 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4095 // Use array's original type only if it has known number of
4096 // elements.
4097 if (!isa<ConstantArrayType>(AT))
4098 PType = PVDecl->getType();
4099 } else if (PType->isFunctionType())
4100 PType = PVDecl->getType();
4101 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004102 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004103 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004104 }
John McCall6b5a61b2011-02-07 10:33:21 +00004105
4106 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004107}
4108
Douglas Gregorf968d832011-05-27 01:19:52 +00004109bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004110 std::string& S) {
4111 // Encode result type.
4112 getObjCEncodingForType(Decl->getResultType(), S);
4113 CharUnits ParmOffset;
4114 // Compute size of all parameters.
4115 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4116 E = Decl->param_end(); PI != E; ++PI) {
4117 QualType PType = (*PI)->getType();
4118 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004119 if (sz.isZero())
4120 return true;
4121
David Chisnall5389f482010-12-30 14:05:53 +00004122 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004123 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004124 ParmOffset += sz;
4125 }
4126 S += charUnitsToString(ParmOffset);
4127 ParmOffset = CharUnits::Zero();
4128
4129 // Argument types.
4130 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4131 E = Decl->param_end(); PI != E; ++PI) {
4132 ParmVarDecl *PVDecl = *PI;
4133 QualType PType = PVDecl->getOriginalType();
4134 if (const ArrayType *AT =
4135 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4136 // Use array's original type only if it has known number of
4137 // elements.
4138 if (!isa<ConstantArrayType>(AT))
4139 PType = PVDecl->getType();
4140 } else if (PType->isFunctionType())
4141 PType = PVDecl->getType();
4142 getObjCEncodingForType(PType, S);
4143 S += charUnitsToString(ParmOffset);
4144 ParmOffset += getObjCEncodingTypeSize(PType);
4145 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004146
4147 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004148}
4149
Bob Wilsondc8dab62011-11-30 01:57:58 +00004150/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4151/// method parameter or return type. If Extended, include class names and
4152/// block object types.
4153void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4154 QualType T, std::string& S,
4155 bool Extended) const {
4156 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4157 getObjCEncodingForTypeQualifier(QT, S);
4158 // Encode parameter type.
4159 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4160 true /*OutermostType*/,
4161 false /*EncodingProperty*/,
4162 false /*StructField*/,
4163 Extended /*EncodeBlockParameters*/,
4164 Extended /*EncodeClassNames*/);
4165}
4166
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004167/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004168/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004169bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004170 std::string& S,
4171 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004172 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004173 // Encode return type.
4174 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4175 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004176 // Compute size of all parameters.
4177 // Start with computing size of a pointer in number of bytes.
4178 // FIXME: There might(should) be a better way of doing this computation!
4179 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004180 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004181 // The first two arguments (self and _cmd) are pointers; account for
4182 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004183 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004184 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004185 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004186 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004187 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004188 if (sz.isZero())
4189 return true;
4190
Ken Dyck199c3d62010-01-11 17:06:35 +00004191 assert (sz.isPositive() &&
4192 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004193 ParmOffset += sz;
4194 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004195 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004196 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004197 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004198
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004199 // Argument types.
4200 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004201 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004202 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004203 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004204 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004205 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004206 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4207 // Use array's original type only if it has known number of
4208 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004209 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004210 PType = PVDecl->getType();
4211 } else if (PType->isFunctionType())
4212 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004213 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4214 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004215 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004216 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004217 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004218
4219 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004220}
4221
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004222/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004223/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004224/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4225/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004226/// Property attributes are stored as a comma-delimited C string. The simple
4227/// attributes readonly and bycopy are encoded as single characters. The
4228/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4229/// encoded as single characters, followed by an identifier. Property types
4230/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004231/// these attributes are defined by the following enumeration:
4232/// @code
4233/// enum PropertyAttributes {
4234/// kPropertyReadOnly = 'R', // property is read-only.
4235/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4236/// kPropertyByref = '&', // property is a reference to the value last assigned
4237/// kPropertyDynamic = 'D', // property is dynamic
4238/// kPropertyGetter = 'G', // followed by getter selector name
4239/// kPropertySetter = 'S', // followed by setter selector name
4240/// kPropertyInstanceVariable = 'V' // followed by instance variable name
4241/// kPropertyType = 't' // followed by old-style type encoding.
4242/// kPropertyWeak = 'W' // 'weak' property
4243/// kPropertyStrong = 'P' // property GC'able
4244/// kPropertyNonAtomic = 'N' // property non-atomic
4245/// };
4246/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004247void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004248 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004249 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004250 // Collect information from the property implementation decl(s).
4251 bool Dynamic = false;
4252 ObjCPropertyImplDecl *SynthesizePID = 0;
4253
4254 // FIXME: Duplicated code due to poor abstraction.
4255 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004256 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004257 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4258 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004259 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004260 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004261 ObjCPropertyImplDecl *PID = *i;
4262 if (PID->getPropertyDecl() == PD) {
4263 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4264 Dynamic = true;
4265 } else {
4266 SynthesizePID = PID;
4267 }
4268 }
4269 }
4270 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004271 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004272 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004273 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004274 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004275 ObjCPropertyImplDecl *PID = *i;
4276 if (PID->getPropertyDecl() == PD) {
4277 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4278 Dynamic = true;
4279 } else {
4280 SynthesizePID = PID;
4281 }
4282 }
Mike Stump1eb44332009-09-09 15:08:12 +00004283 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004284 }
4285 }
4286
4287 // FIXME: This is not very efficient.
4288 S = "T";
4289
4290 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004291 // GCC has some special rules regarding encoding of properties which
4292 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004293 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004294 true /* outermost type */,
4295 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004296
4297 if (PD->isReadOnly()) {
4298 S += ",R";
4299 } else {
4300 switch (PD->getSetterKind()) {
4301 case ObjCPropertyDecl::Assign: break;
4302 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004303 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004304 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004305 }
4306 }
4307
4308 // It really isn't clear at all what this means, since properties
4309 // are "dynamic by default".
4310 if (Dynamic)
4311 S += ",D";
4312
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004313 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4314 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004315
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004316 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4317 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004318 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004319 }
4320
4321 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4322 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004323 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004324 }
4325
4326 if (SynthesizePID) {
4327 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4328 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004329 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004330 }
4331
4332 // FIXME: OBJCGC: weak & strong
4333}
4334
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004335/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004336/// Another legacy compatibility encoding: 32-bit longs are encoded as
4337/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004338/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4339///
4340void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004341 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004342 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004343 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004344 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004345 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004346 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004347 PointeeTy = IntTy;
4348 }
4349 }
4350}
4351
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004352void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004353 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004354 // We follow the behavior of gcc, expanding structures which are
4355 // directly pointed to, and expanding embedded structures. Note that
4356 // these rules are sufficient to prevent recursive encoding of the
4357 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004358 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004359 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004360}
4361
David Chisnall64fd7e82010-06-04 01:10:52 +00004362static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4363 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004364 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnall64fd7e82010-06-04 01:10:52 +00004365 case BuiltinType::Void: return 'v';
4366 case BuiltinType::Bool: return 'B';
4367 case BuiltinType::Char_U:
4368 case BuiltinType::UChar: return 'C';
4369 case BuiltinType::UShort: return 'S';
4370 case BuiltinType::UInt: return 'I';
4371 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00004372 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004373 case BuiltinType::UInt128: return 'T';
4374 case BuiltinType::ULongLong: return 'Q';
4375 case BuiltinType::Char_S:
4376 case BuiltinType::SChar: return 'c';
4377 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004378 case BuiltinType::WChar_S:
4379 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004380 case BuiltinType::Int: return 'i';
4381 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00004382 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004383 case BuiltinType::LongLong: return 'q';
4384 case BuiltinType::Int128: return 't';
4385 case BuiltinType::Float: return 'f';
4386 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004387 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004388 }
4389}
4390
Douglas Gregor5471bc82011-09-08 17:18:35 +00004391static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4392 EnumDecl *Enum = ET->getDecl();
4393
4394 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4395 if (!Enum->isFixed())
4396 return 'i';
4397
4398 // The encoding of a fixed enum type matches its fixed underlying type.
4399 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4400}
4401
Jay Foad4ba2a172011-01-12 09:06:06 +00004402static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004403 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004404 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004405 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004406 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4407 // The GNU runtime requires more information; bitfields are encoded as b,
4408 // then the offset (in bits) of the first element, then the type of the
4409 // bitfield, then the size in bits. For example, in this structure:
4410 //
4411 // struct
4412 // {
4413 // int integer;
4414 // int flags:2;
4415 // };
4416 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4417 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4418 // information is not especially sensible, but we're stuck with it for
4419 // compatibility with GCC, although providing it breaks anything that
4420 // actually uses runtime introspection and wants to work on both runtimes...
4421 if (!Ctx->getLangOptions().NeXTRuntime) {
4422 const RecordDecl *RD = FD->getParent();
4423 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004424 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00004425 if (const EnumType *ET = T->getAs<EnumType>())
4426 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnallc7ff82c2010-12-26 20:12:30 +00004427 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004428 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004429 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004430 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004431}
4432
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004433// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004434void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4435 bool ExpandPointedToStructures,
4436 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004437 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004438 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004439 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004440 bool StructField,
4441 bool EncodeBlockParameters,
4442 bool EncodeClassNames) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004443 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004444 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004445 return EncodeBitField(this, S, T, FD);
4446 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004447 return;
4448 }
Mike Stump1eb44332009-09-09 15:08:12 +00004449
John McCall183700f2009-09-21 23:43:11 +00004450 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004451 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004452 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004453 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004454 return;
4455 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004456
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004457 // encoding for pointer or r3eference types.
4458 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004459 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004460 if (PT->isObjCSelType()) {
4461 S += ':';
4462 return;
4463 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004464 PointeeTy = PT->getPointeeType();
4465 }
4466 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4467 PointeeTy = RT->getPointeeType();
4468 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004469 bool isReadOnly = false;
4470 // For historical/compatibility reasons, the read-only qualifier of the
4471 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4472 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004473 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004474 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004475 if (OutermostType && T.isConstQualified()) {
4476 isReadOnly = true;
4477 S += 'r';
4478 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004479 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004480 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004481 while (P->getAs<PointerType>())
4482 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004483 if (P.isConstQualified()) {
4484 isReadOnly = true;
4485 S += 'r';
4486 }
4487 }
4488 if (isReadOnly) {
4489 // Another legacy compatibility encoding. Some ObjC qualifier and type
4490 // combinations need to be rearranged.
4491 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00004492 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00004493 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004494 }
Mike Stump1eb44332009-09-09 15:08:12 +00004495
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004496 if (PointeeTy->isCharType()) {
4497 // char pointer types should be encoded as '*' unless it is a
4498 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004499 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004500 S += '*';
4501 return;
4502 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004503 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004504 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4505 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4506 S += '#';
4507 return;
4508 }
4509 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4510 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4511 S += '@';
4512 return;
4513 }
4514 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004515 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004516 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004517 getLegacyIntegralTypeEncoding(PointeeTy);
4518
Mike Stump1eb44332009-09-09 15:08:12 +00004519 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004520 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004521 return;
4522 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004523
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004524 if (const ArrayType *AT =
4525 // Ignore type qualifiers etc.
4526 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004527 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004528 // Incomplete arrays are encoded as a pointer to the array element.
4529 S += '^';
4530
Mike Stump1eb44332009-09-09 15:08:12 +00004531 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004532 false, ExpandStructures, FD);
4533 } else {
4534 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004535
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004536 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4537 if (getTypeSize(CAT->getElementType()) == 0)
4538 S += '0';
4539 else
4540 S += llvm::utostr(CAT->getSize().getZExtValue());
4541 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00004542 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004543 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4544 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00004545 S += '0';
4546 }
Mike Stump1eb44332009-09-09 15:08:12 +00004547
4548 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004549 false, ExpandStructures, FD);
4550 S += ']';
4551 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004552 return;
4553 }
Mike Stump1eb44332009-09-09 15:08:12 +00004554
John McCall183700f2009-09-21 23:43:11 +00004555 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004556 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004557 return;
4558 }
Mike Stump1eb44332009-09-09 15:08:12 +00004559
Ted Kremenek6217b802009-07-29 21:53:49 +00004560 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004561 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004562 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004563 // Anonymous structures print as '?'
4564 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4565 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004566 if (ClassTemplateSpecializationDecl *Spec
4567 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4568 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4569 std::string TemplateArgsStr
4570 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004571 TemplateArgs.data(),
4572 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00004573 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004574
4575 S += TemplateArgsStr;
4576 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004577 } else {
4578 S += '?';
4579 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004580 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004581 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004582 if (!RDecl->isUnion()) {
4583 getObjCEncodingForStructureImpl(RDecl, S, FD);
4584 } else {
4585 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4586 FieldEnd = RDecl->field_end();
4587 Field != FieldEnd; ++Field) {
4588 if (FD) {
4589 S += '"';
4590 S += Field->getNameAsString();
4591 S += '"';
4592 }
Mike Stump1eb44332009-09-09 15:08:12 +00004593
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004594 // Special case bit-fields.
4595 if (Field->isBitField()) {
4596 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4597 (*Field));
4598 } else {
4599 QualType qt = Field->getType();
4600 getLegacyIntegralTypeEncoding(qt);
4601 getObjCEncodingForTypeImpl(qt, S, false, true,
4602 FD, /*OutermostType*/false,
4603 /*EncodingProperty*/false,
4604 /*StructField*/true);
4605 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004606 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004607 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004608 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004609 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004610 return;
4611 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004612
Douglas Gregor5471bc82011-09-08 17:18:35 +00004613 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004614 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004615 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004616 else
Douglas Gregor5471bc82011-09-08 17:18:35 +00004617 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004618 return;
4619 }
Mike Stump1eb44332009-09-09 15:08:12 +00004620
Bob Wilsondc8dab62011-11-30 01:57:58 +00004621 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004622 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00004623 if (EncodeBlockParameters) {
4624 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4625
4626 S += '<';
4627 // Block return type
4628 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4629 ExpandPointedToStructures, ExpandStructures,
4630 FD,
4631 false /* OutermostType */,
4632 EncodingProperty,
4633 false /* StructField */,
4634 EncodeBlockParameters,
4635 EncodeClassNames);
4636 // Block self
4637 S += "@?";
4638 // Block parameters
4639 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4640 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4641 E = FPT->arg_type_end(); I && (I != E); ++I) {
4642 getObjCEncodingForTypeImpl(*I, S,
4643 ExpandPointedToStructures,
4644 ExpandStructures,
4645 FD,
4646 false /* OutermostType */,
4647 EncodingProperty,
4648 false /* StructField */,
4649 EncodeBlockParameters,
4650 EncodeClassNames);
4651 }
4652 }
4653 S += '>';
4654 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004655 return;
4656 }
Mike Stump1eb44332009-09-09 15:08:12 +00004657
John McCallc12c5bb2010-05-15 11:32:37 +00004658 // Ignore protocol qualifiers when mangling at this level.
4659 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4660 T = OT->getBaseType();
4661
John McCall0953e762009-09-24 19:53:00 +00004662 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004663 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004664 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004665 S += '{';
4666 const IdentifierInfo *II = OI->getIdentifier();
4667 S += II->getName();
4668 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00004669 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004670 DeepCollectObjCIvars(OI, true, Ivars);
4671 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00004672 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004673 if (Field->isBitField())
4674 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004675 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004676 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004677 }
4678 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004679 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004680 }
Mike Stump1eb44332009-09-09 15:08:12 +00004681
John McCall183700f2009-09-21 23:43:11 +00004682 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004683 if (OPT->isObjCIdType()) {
4684 S += '@';
4685 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004686 }
Mike Stump1eb44332009-09-09 15:08:12 +00004687
Steve Naroff27d20a22009-10-28 22:03:49 +00004688 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4689 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4690 // Since this is a binary compatibility issue, need to consult with runtime
4691 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004692 S += '#';
4693 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004694 }
Mike Stump1eb44332009-09-09 15:08:12 +00004695
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004696 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004697 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004698 ExpandPointedToStructures,
4699 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00004700 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00004701 // Note that we do extended encoding of protocol qualifer list
4702 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004703 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004704 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4705 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004706 S += '<';
4707 S += (*I)->getNameAsString();
4708 S += '>';
4709 }
4710 S += '"';
4711 }
4712 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004713 }
Mike Stump1eb44332009-09-09 15:08:12 +00004714
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004715 QualType PointeeTy = OPT->getPointeeType();
4716 if (!EncodingProperty &&
4717 isa<TypedefType>(PointeeTy.getTypePtr())) {
4718 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004719 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004720 // {...};
4721 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004722 getObjCEncodingForTypeImpl(PointeeTy, S,
4723 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004724 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004725 return;
4726 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004727
4728 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00004729 if (OPT->getInterfaceDecl() &&
4730 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004731 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004732 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004733 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4734 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004735 S += '<';
4736 S += (*I)->getNameAsString();
4737 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004738 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004739 S += '"';
4740 }
4741 return;
4742 }
Mike Stump1eb44332009-09-09 15:08:12 +00004743
John McCall532ec7b2010-05-17 23:56:34 +00004744 // gcc just blithely ignores member pointers.
4745 // TODO: maybe there should be a mangling for these
4746 if (T->getAs<MemberPointerType>())
4747 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004748
4749 if (T->isVectorType()) {
4750 // This matches gcc's encoding, even though technically it is
4751 // insufficient.
4752 // FIXME. We should do a better job than gcc.
4753 return;
4754 }
4755
David Blaikieb219cfc2011-09-23 05:06:16 +00004756 llvm_unreachable("@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004757}
4758
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004759void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4760 std::string &S,
4761 const FieldDecl *FD,
4762 bool includeVBases) const {
4763 assert(RDecl && "Expected non-null RecordDecl");
4764 assert(!RDecl->isUnion() && "Should not be called for unions");
4765 if (!RDecl->getDefinition())
4766 return;
4767
4768 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4769 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4770 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4771
4772 if (CXXRec) {
4773 for (CXXRecordDecl::base_class_iterator
4774 BI = CXXRec->bases_begin(),
4775 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4776 if (!BI->isVirtual()) {
4777 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004778 if (base->isEmpty())
4779 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004780 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4781 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4782 std::make_pair(offs, base));
4783 }
4784 }
4785 }
4786
4787 unsigned i = 0;
4788 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4789 FieldEnd = RDecl->field_end();
4790 Field != FieldEnd; ++Field, ++i) {
4791 uint64_t offs = layout.getFieldOffset(i);
4792 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4793 std::make_pair(offs, *Field));
4794 }
4795
4796 if (CXXRec && includeVBases) {
4797 for (CXXRecordDecl::base_class_iterator
4798 BI = CXXRec->vbases_begin(),
4799 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4800 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004801 if (base->isEmpty())
4802 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004803 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00004804 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4805 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4806 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004807 }
4808 }
4809
4810 CharUnits size;
4811 if (CXXRec) {
4812 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4813 } else {
4814 size = layout.getSize();
4815 }
4816
4817 uint64_t CurOffs = 0;
4818 std::multimap<uint64_t, NamedDecl *>::iterator
4819 CurLayObj = FieldOrBaseOffsets.begin();
4820
Argyrios Kyrtzidiscb8061e2011-08-22 16:03:14 +00004821 if ((CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) ||
4822 (CurLayObj == FieldOrBaseOffsets.end() &&
4823 CXXRec && CXXRec->isDynamicClass())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004824 assert(CXXRec && CXXRec->isDynamicClass() &&
4825 "Offset 0 was empty but no VTable ?");
4826 if (FD) {
4827 S += "\"_vptr$";
4828 std::string recname = CXXRec->getNameAsString();
4829 if (recname.empty()) recname = "?";
4830 S += recname;
4831 S += '"';
4832 }
4833 S += "^^?";
4834 CurOffs += getTypeSize(VoidPtrTy);
4835 }
4836
4837 if (!RDecl->hasFlexibleArrayMember()) {
4838 // Mark the end of the structure.
4839 uint64_t offs = toBits(size);
4840 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4841 std::make_pair(offs, (NamedDecl*)0));
4842 }
4843
4844 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4845 assert(CurOffs <= CurLayObj->first);
4846
4847 if (CurOffs < CurLayObj->first) {
4848 uint64_t padding = CurLayObj->first - CurOffs;
4849 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4850 // packing/alignment of members is different that normal, in which case
4851 // the encoding will be out-of-sync with the real layout.
4852 // If the runtime switches to just consider the size of types without
4853 // taking into account alignment, we could make padding explicit in the
4854 // encoding (e.g. using arrays of chars). The encoding strings would be
4855 // longer then though.
4856 CurOffs += padding;
4857 }
4858
4859 NamedDecl *dcl = CurLayObj->second;
4860 if (dcl == 0)
4861 break; // reached end of structure.
4862
4863 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4864 // We expand the bases without their virtual bases since those are going
4865 // in the initial structure. Note that this differs from gcc which
4866 // expands virtual bases each time one is encountered in the hierarchy,
4867 // making the encoding type bigger than it really is.
4868 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004869 assert(!base->isEmpty());
4870 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004871 } else {
4872 FieldDecl *field = cast<FieldDecl>(dcl);
4873 if (FD) {
4874 S += '"';
4875 S += field->getNameAsString();
4876 S += '"';
4877 }
4878
4879 if (field->isBitField()) {
4880 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004881 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004882 } else {
4883 QualType qt = field->getType();
4884 getLegacyIntegralTypeEncoding(qt);
4885 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4886 /*OutermostType*/false,
4887 /*EncodingProperty*/false,
4888 /*StructField*/true);
4889 CurOffs += getTypeSize(field->getType());
4890 }
4891 }
4892 }
4893}
4894
Mike Stump1eb44332009-09-09 15:08:12 +00004895void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004896 std::string& S) const {
4897 if (QT & Decl::OBJC_TQ_In)
4898 S += 'n';
4899 if (QT & Decl::OBJC_TQ_Inout)
4900 S += 'N';
4901 if (QT & Decl::OBJC_TQ_Out)
4902 S += 'o';
4903 if (QT & Decl::OBJC_TQ_Bycopy)
4904 S += 'O';
4905 if (QT & Decl::OBJC_TQ_Byref)
4906 S += 'R';
4907 if (QT & Decl::OBJC_TQ_Oneway)
4908 S += 'V';
4909}
4910
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004911void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004912 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004913
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004914 BuiltinVaListType = T;
4915}
4916
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00004917TypedefDecl *ASTContext::getObjCIdDecl() const {
4918 if (!ObjCIdDecl) {
4919 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4920 T = getObjCObjectPointerType(T);
4921 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4922 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4923 getTranslationUnitDecl(),
4924 SourceLocation(), SourceLocation(),
4925 &Idents.get("id"), IdInfo);
4926 }
4927
4928 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00004929}
4930
Douglas Gregor7a27ea52011-08-12 06:17:30 +00004931TypedefDecl *ASTContext::getObjCSelDecl() const {
4932 if (!ObjCSelDecl) {
4933 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4934 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4935 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4936 getTranslationUnitDecl(),
4937 SourceLocation(), SourceLocation(),
4938 &Idents.get("SEL"), SelInfo);
4939 }
4940 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004941}
4942
Douglas Gregor79d67262011-08-12 05:59:41 +00004943TypedefDecl *ASTContext::getObjCClassDecl() const {
4944 if (!ObjCClassDecl) {
4945 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4946 T = getObjCObjectPointerType(T);
4947 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4948 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4949 getTranslationUnitDecl(),
4950 SourceLocation(), SourceLocation(),
4951 &Idents.get("Class"), ClassInfo);
4952 }
4953
4954 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004955}
4956
Douglas Gregora6ea10e2012-01-17 18:09:05 +00004957ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
4958 if (!ObjCProtocolClassDecl) {
4959 ObjCProtocolClassDecl
4960 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
4961 SourceLocation(),
4962 &Idents.get("Protocol"),
4963 /*PrevDecl=*/0,
4964 SourceLocation(), true);
4965 }
4966
4967 return ObjCProtocolClassDecl;
4968}
4969
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004970void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004971 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004972 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004973
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004974 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004975}
4976
John McCall0bd6feb2009-12-02 08:04:21 +00004977/// \brief Retrieve the template name that corresponds to a non-empty
4978/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00004979TemplateName
4980ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4981 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00004982 unsigned size = End - Begin;
4983 assert(size > 1 && "set is not overloaded!");
4984
4985 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4986 size * sizeof(FunctionTemplateDecl*));
4987 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4988
4989 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004990 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004991 NamedDecl *D = *I;
4992 assert(isa<FunctionTemplateDecl>(D) ||
4993 (isa<UsingShadowDecl>(D) &&
4994 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4995 *Storage++ = D;
4996 }
4997
4998 return TemplateName(OT);
4999}
5000
Douglas Gregor7532dc62009-03-30 22:58:21 +00005001/// \brief Retrieve the template name that represents a qualified
5002/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00005003TemplateName
5004ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5005 bool TemplateKeyword,
5006 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00005007 assert(NNS && "Missing nested-name-specifier in qualified template name");
5008
Douglas Gregor789b1f62010-02-04 18:10:26 +00005009 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00005010 llvm::FoldingSetNodeID ID;
5011 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5012
5013 void *InsertPos = 0;
5014 QualifiedTemplateName *QTN =
5015 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5016 if (!QTN) {
5017 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
5018 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5019 }
5020
5021 return TemplateName(QTN);
5022}
5023
5024/// \brief Retrieve the template name that represents a dependent
5025/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00005026TemplateName
5027ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5028 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00005029 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00005030 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00005031
5032 llvm::FoldingSetNodeID ID;
5033 DependentTemplateName::Profile(ID, NNS, Name);
5034
5035 void *InsertPos = 0;
5036 DependentTemplateName *QTN =
5037 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5038
5039 if (QTN)
5040 return TemplateName(QTN);
5041
5042 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5043 if (CanonNNS == NNS) {
5044 QTN = new (*this,4) DependentTemplateName(NNS, Name);
5045 } else {
5046 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5047 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005048 DependentTemplateName *CheckQTN =
5049 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5050 assert(!CheckQTN && "Dependent type name canonicalization broken");
5051 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00005052 }
5053
5054 DependentTemplateNames.InsertNode(QTN, InsertPos);
5055 return TemplateName(QTN);
5056}
5057
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005058/// \brief Retrieve the template name that represents a dependent
5059/// template name such as \c MetaFun::template operator+.
5060TemplateName
5061ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00005062 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005063 assert((!NNS || NNS->isDependent()) &&
5064 "Nested name specifier must be dependent");
5065
5066 llvm::FoldingSetNodeID ID;
5067 DependentTemplateName::Profile(ID, NNS, Operator);
5068
5069 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00005070 DependentTemplateName *QTN
5071 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005072
5073 if (QTN)
5074 return TemplateName(QTN);
5075
5076 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5077 if (CanonNNS == NNS) {
5078 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5079 } else {
5080 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5081 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005082
5083 DependentTemplateName *CheckQTN
5084 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5085 assert(!CheckQTN && "Dependent template name canonicalization broken");
5086 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005087 }
5088
5089 DependentTemplateNames.InsertNode(QTN, InsertPos);
5090 return TemplateName(QTN);
5091}
5092
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005093TemplateName
John McCall14606042011-06-30 08:33:18 +00005094ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5095 TemplateName replacement) const {
5096 llvm::FoldingSetNodeID ID;
5097 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5098
5099 void *insertPos = 0;
5100 SubstTemplateTemplateParmStorage *subst
5101 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5102
5103 if (!subst) {
5104 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5105 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5106 }
5107
5108 return TemplateName(subst);
5109}
5110
5111TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005112ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5113 const TemplateArgument &ArgPack) const {
5114 ASTContext &Self = const_cast<ASTContext &>(*this);
5115 llvm::FoldingSetNodeID ID;
5116 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5117
5118 void *InsertPos = 0;
5119 SubstTemplateTemplateParmPackStorage *Subst
5120 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5121
5122 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00005123 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005124 ArgPack.pack_size(),
5125 ArgPack.pack_begin());
5126 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5127 }
5128
5129 return TemplateName(Subst);
5130}
5131
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005132/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00005133/// TargetInfo, produce the corresponding type. The unsigned @p Type
5134/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00005135CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005136 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00005137 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005138 case TargetInfo::SignedShort: return ShortTy;
5139 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5140 case TargetInfo::SignedInt: return IntTy;
5141 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5142 case TargetInfo::SignedLong: return LongTy;
5143 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5144 case TargetInfo::SignedLongLong: return LongLongTy;
5145 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5146 }
5147
David Blaikieb219cfc2011-09-23 05:06:16 +00005148 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005149}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00005150
5151//===----------------------------------------------------------------------===//
5152// Type Predicates.
5153//===----------------------------------------------------------------------===//
5154
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005155/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5156/// garbage collection attribute.
5157///
John McCallae278a32011-01-12 00:34:59 +00005158Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
Douglas Gregore289d812011-09-13 17:21:33 +00005159 if (getLangOptions().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00005160 return Qualifiers::GCNone;
5161
5162 assert(getLangOptions().ObjC1);
5163 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5164
5165 // Default behaviour under objective-C's gc is for ObjC pointers
5166 // (or pointers to them) be treated as though they were declared
5167 // as __strong.
5168 if (GCAttrs == Qualifiers::GCNone) {
5169 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5170 return Qualifiers::Strong;
5171 else if (Ty->isPointerType())
5172 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5173 } else {
5174 // It's not valid to set GC attributes on anything that isn't a
5175 // pointer.
5176#ifndef NDEBUG
5177 QualType CT = Ty->getCanonicalTypeInternal();
5178 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5179 CT = AT->getElementType();
5180 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5181#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005182 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00005183 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005184}
5185
Chris Lattner6ac46a42008-04-07 06:51:04 +00005186//===----------------------------------------------------------------------===//
5187// Type Compatibility Testing
5188//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00005189
Mike Stump1eb44332009-09-09 15:08:12 +00005190/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005191/// compatible.
5192static bool areCompatVectorTypes(const VectorType *LHS,
5193 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00005194 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00005195 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00005196 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00005197}
5198
Douglas Gregor255210e2010-08-06 10:14:59 +00005199bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5200 QualType SecondVec) {
5201 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5202 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5203
5204 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5205 return true;
5206
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005207 // Treat Neon vector types and most AltiVec vector types as if they are the
5208 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00005209 const VectorType *First = FirstVec->getAs<VectorType>();
5210 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005211 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00005212 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005213 First->getVectorKind() != VectorType::AltiVecPixel &&
5214 First->getVectorKind() != VectorType::AltiVecBool &&
5215 Second->getVectorKind() != VectorType::AltiVecPixel &&
5216 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00005217 return true;
5218
5219 return false;
5220}
5221
Steve Naroff4084c302009-07-23 01:01:38 +00005222//===----------------------------------------------------------------------===//
5223// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5224//===----------------------------------------------------------------------===//
5225
5226/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5227/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00005228bool
5229ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5230 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005231 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00005232 return true;
5233 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5234 E = rProto->protocol_end(); PI != E; ++PI)
5235 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5236 return true;
5237 return false;
5238}
5239
Steve Naroff4084c302009-07-23 01:01:38 +00005240/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5241/// return true if lhs's protocols conform to rhs's protocol; false
5242/// otherwise.
5243bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5244 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5245 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5246 return false;
5247}
5248
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005249/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5250/// Class<p1, ...>.
5251bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5252 QualType rhs) {
5253 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5254 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5255 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5256
5257 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5258 E = lhsQID->qual_end(); I != E; ++I) {
5259 bool match = false;
5260 ObjCProtocolDecl *lhsProto = *I;
5261 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5262 E = rhsOPT->qual_end(); J != E; ++J) {
5263 ObjCProtocolDecl *rhsProto = *J;
5264 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5265 match = true;
5266 break;
5267 }
5268 }
5269 if (!match)
5270 return false;
5271 }
5272 return true;
5273}
5274
Steve Naroff4084c302009-07-23 01:01:38 +00005275/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5276/// ObjCQualifiedIDType.
5277bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5278 bool compare) {
5279 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00005280 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005281 lhs->isObjCIdType() || lhs->isObjCClassType())
5282 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005283 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005284 rhs->isObjCIdType() || rhs->isObjCClassType())
5285 return true;
5286
5287 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00005288 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005289
Steve Naroff4084c302009-07-23 01:01:38 +00005290 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005291
Steve Naroff4084c302009-07-23 01:01:38 +00005292 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005293 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00005294 // make sure we check the class hierarchy.
5295 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5296 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5297 E = lhsQID->qual_end(); I != E; ++I) {
5298 // when comparing an id<P> on lhs with a static type on rhs,
5299 // see if static class implements all of id's protocols, directly or
5300 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005301 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00005302 return false;
5303 }
5304 }
5305 // If there are no qualifiers and no interface, we have an 'id'.
5306 return true;
5307 }
Mike Stump1eb44332009-09-09 15:08:12 +00005308 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005309 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5310 E = lhsQID->qual_end(); I != E; ++I) {
5311 ObjCProtocolDecl *lhsProto = *I;
5312 bool match = false;
5313
5314 // when comparing an id<P> on lhs with a static type on rhs,
5315 // see if static class implements all of id's protocols, directly or
5316 // through its super class and categories.
5317 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5318 E = rhsOPT->qual_end(); J != E; ++J) {
5319 ObjCProtocolDecl *rhsProto = *J;
5320 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5321 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5322 match = true;
5323 break;
5324 }
5325 }
Mike Stump1eb44332009-09-09 15:08:12 +00005326 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00005327 // make sure we check the class hierarchy.
5328 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5329 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5330 E = lhsQID->qual_end(); I != E; ++I) {
5331 // when comparing an id<P> on lhs with a static type on rhs,
5332 // see if static class implements all of id's protocols, directly or
5333 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005334 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00005335 match = true;
5336 break;
5337 }
5338 }
5339 }
5340 if (!match)
5341 return false;
5342 }
Mike Stump1eb44332009-09-09 15:08:12 +00005343
Steve Naroff4084c302009-07-23 01:01:38 +00005344 return true;
5345 }
Mike Stump1eb44332009-09-09 15:08:12 +00005346
Steve Naroff4084c302009-07-23 01:01:38 +00005347 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5348 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5349
Mike Stump1eb44332009-09-09 15:08:12 +00005350 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00005351 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005352 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005353 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5354 E = lhsOPT->qual_end(); I != E; ++I) {
5355 ObjCProtocolDecl *lhsProto = *I;
5356 bool match = false;
5357
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005358 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00005359 // see if static class implements all of id's protocols, directly or
5360 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005361 // First, lhs protocols in the qualifier list must be found, direct
5362 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00005363 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5364 E = rhsQID->qual_end(); J != E; ++J) {
5365 ObjCProtocolDecl *rhsProto = *J;
5366 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5367 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5368 match = true;
5369 break;
5370 }
5371 }
5372 if (!match)
5373 return false;
5374 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005375
5376 // Static class's protocols, or its super class or category protocols
5377 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5378 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5379 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5380 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5381 // This is rather dubious but matches gcc's behavior. If lhs has
5382 // no type qualifier and its class has no static protocol(s)
5383 // assume that it is mismatch.
5384 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5385 return false;
5386 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5387 LHSInheritedProtocols.begin(),
5388 E = LHSInheritedProtocols.end(); I != E; ++I) {
5389 bool match = false;
5390 ObjCProtocolDecl *lhsProto = (*I);
5391 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5392 E = rhsQID->qual_end(); J != E; ++J) {
5393 ObjCProtocolDecl *rhsProto = *J;
5394 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5395 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5396 match = true;
5397 break;
5398 }
5399 }
5400 if (!match)
5401 return false;
5402 }
5403 }
Steve Naroff4084c302009-07-23 01:01:38 +00005404 return true;
5405 }
5406 return false;
5407}
5408
Eli Friedman3d815e72008-08-22 00:56:42 +00005409/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005410/// compatible for assignment from RHS to LHS. This handles validation of any
5411/// protocol qualifiers on the LHS or RHS.
5412///
Steve Naroff14108da2009-07-10 23:34:53 +00005413bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5414 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00005415 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5416 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5417
Steve Naroffde2e22d2009-07-15 18:40:39 +00005418 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00005419 if (LHS->isObjCUnqualifiedIdOrClass() ||
5420 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00005421 return true;
5422
John McCallc12c5bb2010-05-15 11:32:37 +00005423 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00005424 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5425 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00005426 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005427
5428 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5429 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5430 QualType(RHSOPT,0));
5431
John McCallc12c5bb2010-05-15 11:32:37 +00005432 // If we have 2 user-defined types, fall into that path.
5433 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00005434 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00005435
Steve Naroff4084c302009-07-23 01:01:38 +00005436 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005437}
5438
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005439/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00005440/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005441/// arguments in block literals. When passed as arguments, passing 'A*' where
5442/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5443/// not OK. For the return type, the opposite is not OK.
5444bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5445 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005446 const ObjCObjectPointerType *RHSOPT,
5447 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005448 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005449 return true;
5450
5451 if (LHSOPT->isObjCBuiltinType()) {
5452 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5453 }
5454
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005455 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005456 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5457 QualType(RHSOPT,0),
5458 false);
5459
5460 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5461 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5462 if (LHS && RHS) { // We have 2 user-defined types.
5463 if (LHS != RHS) {
5464 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005465 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005466 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005467 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005468 }
5469 else
5470 return true;
5471 }
5472 return false;
5473}
5474
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005475/// getIntersectionOfProtocols - This routine finds the intersection of set
5476/// of protocols inherited from two distinct objective-c pointer objects.
5477/// It is used to build composite qualifier list of the composite type of
5478/// the conditional expression involving two objective-c pointer objects.
5479static
5480void getIntersectionOfProtocols(ASTContext &Context,
5481 const ObjCObjectPointerType *LHSOPT,
5482 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005483 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005484
John McCallc12c5bb2010-05-15 11:32:37 +00005485 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5486 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5487 assert(LHS->getInterface() && "LHS must have an interface base");
5488 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005489
5490 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5491 unsigned LHSNumProtocols = LHS->getNumProtocols();
5492 if (LHSNumProtocols > 0)
5493 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5494 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005495 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005496 Context.CollectInheritedProtocols(LHS->getInterface(),
5497 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005498 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5499 LHSInheritedProtocols.end());
5500 }
5501
5502 unsigned RHSNumProtocols = RHS->getNumProtocols();
5503 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00005504 ObjCProtocolDecl **RHSProtocols =
5505 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005506 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5507 if (InheritedProtocolSet.count(RHSProtocols[i]))
5508 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00005509 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005510 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005511 Context.CollectInheritedProtocols(RHS->getInterface(),
5512 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005513 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5514 RHSInheritedProtocols.begin(),
5515 E = RHSInheritedProtocols.end(); I != E; ++I)
5516 if (InheritedProtocolSet.count((*I)))
5517 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005518 }
5519}
5520
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005521/// areCommonBaseCompatible - Returns common base class of the two classes if
5522/// one found. Note that this is O'2 algorithm. But it will be called as the
5523/// last type comparison in a ?-exp of ObjC pointer types before a
5524/// warning is issued. So, its invokation is extremely rare.
5525QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00005526 const ObjCObjectPointerType *Lptr,
5527 const ObjCObjectPointerType *Rptr) {
5528 const ObjCObjectType *LHS = Lptr->getObjectType();
5529 const ObjCObjectType *RHS = Rptr->getObjectType();
5530 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5531 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00005532 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005533 return QualType();
5534
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005535 do {
John McCallc12c5bb2010-05-15 11:32:37 +00005536 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005537 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005538 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005539 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5540
5541 QualType Result = QualType(LHS, 0);
5542 if (!Protocols.empty())
5543 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5544 Result = getObjCObjectPointerType(Result);
5545 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005546 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005547 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005548
5549 return QualType();
5550}
5551
John McCallc12c5bb2010-05-15 11:32:37 +00005552bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5553 const ObjCObjectType *RHS) {
5554 assert(LHS->getInterface() && "LHS is not an interface type");
5555 assert(RHS->getInterface() && "RHS is not an interface type");
5556
Chris Lattner6ac46a42008-04-07 06:51:04 +00005557 // Verify that the base decls are compatible: the RHS must be a subclass of
5558 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00005559 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00005560 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005561
Chris Lattner6ac46a42008-04-07 06:51:04 +00005562 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5563 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00005564 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00005565 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005566
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005567 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5568 // more detailed analysis is required.
5569 if (RHS->getNumProtocols() == 0) {
5570 // OK, if LHS is a superclass of RHS *and*
5571 // this superclass is assignment compatible with LHS.
5572 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005573 bool IsSuperClass =
5574 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5575 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005576 // OK if conversion of LHS to SuperClass results in narrowing of types
5577 // ; i.e., SuperClass may implement at least one of the protocols
5578 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5579 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5580 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005581 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005582 // If super class has no protocols, it is not a match.
5583 if (SuperClassInheritedProtocols.empty())
5584 return false;
5585
5586 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5587 LHSPE = LHS->qual_end();
5588 LHSPI != LHSPE; LHSPI++) {
5589 bool SuperImplementsProtocol = false;
5590 ObjCProtocolDecl *LHSProto = (*LHSPI);
5591
5592 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5593 SuperClassInheritedProtocols.begin(),
5594 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5595 ObjCProtocolDecl *SuperClassProto = (*I);
5596 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5597 SuperImplementsProtocol = true;
5598 break;
5599 }
5600 }
5601 if (!SuperImplementsProtocol)
5602 return false;
5603 }
5604 return true;
5605 }
5606 return false;
5607 }
Mike Stump1eb44332009-09-09 15:08:12 +00005608
John McCallc12c5bb2010-05-15 11:32:37 +00005609 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5610 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005611 LHSPI != LHSPE; LHSPI++) {
5612 bool RHSImplementsProtocol = false;
5613
5614 // If the RHS doesn't implement the protocol on the left, the types
5615 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00005616 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5617 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00005618 RHSPI != RHSPE; RHSPI++) {
5619 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005620 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00005621 break;
5622 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005623 }
5624 // FIXME: For better diagnostics, consider passing back the protocol name.
5625 if (!RHSImplementsProtocol)
5626 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005627 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005628 // The RHS implements all protocols listed on the LHS.
5629 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005630}
5631
Steve Naroff389bf462009-02-12 17:52:19 +00005632bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5633 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00005634 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5635 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005636
Steve Naroff14108da2009-07-10 23:34:53 +00005637 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00005638 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005639
5640 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5641 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00005642}
5643
Douglas Gregor569c3162010-08-07 11:51:51 +00005644bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5645 return canAssignObjCInterfaces(
5646 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5647 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5648}
5649
Mike Stump1eb44332009-09-09 15:08:12 +00005650/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00005651/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00005652/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00005653/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00005654bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5655 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005656 if (getLangOptions().CPlusPlus)
5657 return hasSameType(LHS, RHS);
5658
Douglas Gregor447234d2010-07-29 15:18:02 +00005659 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00005660}
5661
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005662bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00005663 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005664}
5665
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005666bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5667 return !mergeTypes(LHS, RHS, true).isNull();
5668}
5669
Peter Collingbourne48466752010-10-24 18:30:18 +00005670/// mergeTransparentUnionType - if T is a transparent union type and a member
5671/// of T is compatible with SubType, return the merged type, else return
5672/// QualType()
5673QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5674 bool OfBlockPointer,
5675 bool Unqualified) {
5676 if (const RecordType *UT = T->getAsUnionType()) {
5677 RecordDecl *UD = UT->getDecl();
5678 if (UD->hasAttr<TransparentUnionAttr>()) {
5679 for (RecordDecl::field_iterator it = UD->field_begin(),
5680 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00005681 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005682 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5683 if (!MT.isNull())
5684 return MT;
5685 }
5686 }
5687 }
5688
5689 return QualType();
5690}
5691
5692/// mergeFunctionArgumentTypes - merge two types which appear as function
5693/// argument types
5694QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5695 bool OfBlockPointer,
5696 bool Unqualified) {
5697 // GNU extension: two types are compatible if they appear as a function
5698 // argument, one of the types is a transparent union type and the other
5699 // type is compatible with a union member
5700 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5701 Unqualified);
5702 if (!lmerge.isNull())
5703 return lmerge;
5704
5705 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5706 Unqualified);
5707 if (!rmerge.isNull())
5708 return rmerge;
5709
5710 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5711}
5712
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005713QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00005714 bool OfBlockPointer,
5715 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00005716 const FunctionType *lbase = lhs->getAs<FunctionType>();
5717 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00005718 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5719 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00005720 bool allLTypes = true;
5721 bool allRTypes = true;
5722
5723 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005724 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005725 if (OfBlockPointer) {
5726 QualType RHS = rbase->getResultType();
5727 QualType LHS = lbase->getResultType();
5728 bool UnqualifiedResult = Unqualified;
5729 if (!UnqualifiedResult)
5730 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005731 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005732 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005733 else
John McCall8cc246c2010-12-15 01:06:38 +00005734 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5735 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005736 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005737
5738 if (Unqualified)
5739 retType = retType.getUnqualifiedType();
5740
5741 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5742 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5743 if (Unqualified) {
5744 LRetType = LRetType.getUnqualifiedType();
5745 RRetType = RRetType.getUnqualifiedType();
5746 }
5747
5748 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005749 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00005750 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005751 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005752
Daniel Dunbar6a15c852010-04-28 16:20:58 +00005753 // FIXME: double check this
5754 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5755 // rbase->getRegParmAttr() != 0 &&
5756 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00005757 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5758 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00005759
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005760 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00005761 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005762 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005763
John McCall8cc246c2010-12-15 01:06:38 +00005764 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00005765 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5766 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00005767 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5768 return QualType();
5769
John McCallf85e1932011-06-15 23:02:42 +00005770 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5771 return QualType();
5772
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005773 // functypes which return are preferred over those that do not.
5774 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5775 allLTypes = false;
5776 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5777 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005778 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5779 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00005780
John McCallf85e1932011-06-15 23:02:42 +00005781 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00005782
Eli Friedman3d815e72008-08-22 00:56:42 +00005783 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00005784 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5785 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005786 unsigned lproto_nargs = lproto->getNumArgs();
5787 unsigned rproto_nargs = rproto->getNumArgs();
5788
5789 // Compatible functions must have the same number of arguments
5790 if (lproto_nargs != rproto_nargs)
5791 return QualType();
5792
5793 // Variadic and non-variadic functions aren't compatible
5794 if (lproto->isVariadic() != rproto->isVariadic())
5795 return QualType();
5796
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00005797 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5798 return QualType();
5799
Fariborz Jahanian78213e42011-09-28 21:52:05 +00005800 if (LangOpts.ObjCAutoRefCount &&
5801 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5802 return QualType();
5803
Eli Friedman3d815e72008-08-22 00:56:42 +00005804 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00005805 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00005806 for (unsigned i = 0; i < lproto_nargs; i++) {
5807 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5808 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005809 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5810 OfBlockPointer,
5811 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005812 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005813
5814 if (Unqualified)
5815 argtype = argtype.getUnqualifiedType();
5816
Eli Friedman3d815e72008-08-22 00:56:42 +00005817 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00005818 if (Unqualified) {
5819 largtype = largtype.getUnqualifiedType();
5820 rargtype = rargtype.getUnqualifiedType();
5821 }
5822
Chris Lattner61710852008-10-05 17:34:18 +00005823 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5824 allLTypes = false;
5825 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5826 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00005827 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00005828
Eli Friedman3d815e72008-08-22 00:56:42 +00005829 if (allLTypes) return lhs;
5830 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005831
5832 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5833 EPI.ExtInfo = einfo;
5834 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005835 }
5836
5837 if (lproto) allRTypes = false;
5838 if (rproto) allLTypes = false;
5839
Douglas Gregor72564e72009-02-26 23:50:07 +00005840 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00005841 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00005842 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005843 if (proto->isVariadic()) return QualType();
5844 // Check that the types are compatible with the types that
5845 // would result from default argument promotions (C99 6.7.5.3p15).
5846 // The only types actually affected are promotable integer
5847 // types and floats, which would be passed as a different
5848 // type depending on whether the prototype is visible.
5849 unsigned proto_nargs = proto->getNumArgs();
5850 for (unsigned i = 0; i < proto_nargs; ++i) {
5851 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00005852
5853 // Look at the promotion type of enum types, since that is the type used
5854 // to pass enum values.
5855 if (const EnumType *Enum = argTy->getAs<EnumType>())
5856 argTy = Enum->getDecl()->getPromotionType();
5857
Eli Friedman3d815e72008-08-22 00:56:42 +00005858 if (argTy->isPromotableIntegerType() ||
5859 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5860 return QualType();
5861 }
5862
5863 if (allLTypes) return lhs;
5864 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005865
5866 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5867 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00005868 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005869 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005870 }
5871
5872 if (allLTypes) return lhs;
5873 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00005874 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00005875}
5876
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005877QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00005878 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005879 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00005880 // C++ [expr]: If an expression initially has the type "reference to T", the
5881 // type is adjusted to "T" prior to any further analysis, the expression
5882 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005883 // expression is an lvalue unless the reference is an rvalue reference and
5884 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005885 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5886 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00005887
5888 if (Unqualified) {
5889 LHS = LHS.getUnqualifiedType();
5890 RHS = RHS.getUnqualifiedType();
5891 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005892
Eli Friedman3d815e72008-08-22 00:56:42 +00005893 QualType LHSCan = getCanonicalType(LHS),
5894 RHSCan = getCanonicalType(RHS);
5895
5896 // If two types are identical, they are compatible.
5897 if (LHSCan == RHSCan)
5898 return LHS;
5899
John McCall0953e762009-09-24 19:53:00 +00005900 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005901 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5902 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00005903 if (LQuals != RQuals) {
5904 // If any of these qualifiers are different, we have a type
5905 // mismatch.
5906 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00005907 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5908 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00005909 return QualType();
5910
5911 // Exactly one GC qualifier difference is allowed: __strong is
5912 // okay if the other type has no GC qualifier but is an Objective
5913 // C object pointer (i.e. implicitly strong by default). We fix
5914 // this by pretending that the unqualified type was actually
5915 // qualified __strong.
5916 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5917 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5918 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5919
5920 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5921 return QualType();
5922
5923 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5924 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5925 }
5926 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5927 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5928 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005929 return QualType();
John McCall0953e762009-09-24 19:53:00 +00005930 }
5931
5932 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00005933
Eli Friedman852d63b2009-06-01 01:22:52 +00005934 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5935 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00005936
Chris Lattner1adb8832008-01-14 05:45:46 +00005937 // We want to consider the two function types to be the same for these
5938 // comparisons, just force one to the other.
5939 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5940 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00005941
5942 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00005943 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5944 LHSClass = Type::ConstantArray;
5945 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5946 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00005947
John McCallc12c5bb2010-05-15 11:32:37 +00005948 // ObjCInterfaces are just specialized ObjCObjects.
5949 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5950 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5951
Nate Begeman213541a2008-04-18 23:10:10 +00005952 // Canonicalize ExtVector -> Vector.
5953 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5954 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00005955
Chris Lattnera36a61f2008-04-07 05:43:21 +00005956 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005957 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00005958 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00005959 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00005960 // Compatibility is based on the underlying type, not the promotion
5961 // type.
John McCall183700f2009-09-21 23:43:11 +00005962 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005963 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5964 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005965 }
John McCall183700f2009-09-21 23:43:11 +00005966 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005967 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5968 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005969 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00005970 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00005971 if (OfBlockPointer && !BlockReturnType) {
5972 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
5973 return LHS;
5974 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
5975 return RHS;
5976 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00005977
Eli Friedman3d815e72008-08-22 00:56:42 +00005978 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005979 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005980
Steve Naroff4a746782008-01-09 22:43:08 +00005981 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005982 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00005983#define TYPE(Class, Base)
5984#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00005985#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00005986#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5987#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5988#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00005989 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00005990
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005991 case Type::LValueReference:
5992 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00005993 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00005994 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00005995
John McCallc12c5bb2010-05-15 11:32:37 +00005996 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00005997 case Type::IncompleteArray:
5998 case Type::VariableArray:
5999 case Type::FunctionProto:
6000 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00006001 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00006002
Chris Lattner1adb8832008-01-14 05:45:46 +00006003 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00006004 {
6005 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006006 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6007 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006008 if (Unqualified) {
6009 LHSPointee = LHSPointee.getUnqualifiedType();
6010 RHSPointee = RHSPointee.getUnqualifiedType();
6011 }
6012 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6013 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006014 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00006015 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00006016 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00006017 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00006018 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006019 return getPointerType(ResultType);
6020 }
Steve Naroffc0febd52008-12-10 17:49:55 +00006021 case Type::BlockPointer:
6022 {
6023 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006024 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6025 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006026 if (Unqualified) {
6027 LHSPointee = LHSPointee.getUnqualifiedType();
6028 RHSPointee = RHSPointee.getUnqualifiedType();
6029 }
6030 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6031 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00006032 if (ResultType.isNull()) return QualType();
6033 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6034 return LHS;
6035 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6036 return RHS;
6037 return getBlockPointerType(ResultType);
6038 }
Eli Friedmanb001de72011-10-06 23:00:33 +00006039 case Type::Atomic:
6040 {
6041 // Merge two pointer types, while trying to preserve typedef info
6042 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6043 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6044 if (Unqualified) {
6045 LHSValue = LHSValue.getUnqualifiedType();
6046 RHSValue = RHSValue.getUnqualifiedType();
6047 }
6048 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6049 Unqualified);
6050 if (ResultType.isNull()) return QualType();
6051 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6052 return LHS;
6053 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6054 return RHS;
6055 return getAtomicType(ResultType);
6056 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006057 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00006058 {
6059 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6060 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6061 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6062 return QualType();
6063
6064 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6065 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006066 if (Unqualified) {
6067 LHSElem = LHSElem.getUnqualifiedType();
6068 RHSElem = RHSElem.getUnqualifiedType();
6069 }
6070
6071 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006072 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00006073 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6074 return LHS;
6075 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6076 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00006077 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6078 ArrayType::ArraySizeModifier(), 0);
6079 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6080 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006081 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6082 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00006083 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6084 return LHS;
6085 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6086 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006087 if (LVAT) {
6088 // FIXME: This isn't correct! But tricky to implement because
6089 // the array's size has to be the size of LHS, but the type
6090 // has to be different.
6091 return LHS;
6092 }
6093 if (RVAT) {
6094 // FIXME: This isn't correct! But tricky to implement because
6095 // the array's size has to be the size of RHS, but the type
6096 // has to be different.
6097 return RHS;
6098 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00006099 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6100 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00006101 return getIncompleteArrayType(ResultType,
6102 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006103 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006104 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00006105 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00006106 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00006107 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00006108 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00006109 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006110 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00006111 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00006112 case Type::Complex:
6113 // Distinct complex types are incompatible.
6114 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006115 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006116 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00006117 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6118 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006119 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00006120 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00006121 case Type::ObjCObject: {
6122 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006123 // FIXME: This should be type compatibility, e.g. whether
6124 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00006125 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6126 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6127 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00006128 return LHS;
6129
Eli Friedman3d815e72008-08-22 00:56:42 +00006130 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00006131 }
Steve Naroff14108da2009-07-10 23:34:53 +00006132 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006133 if (OfBlockPointer) {
6134 if (canAssignObjCInterfacesInBlockPointer(
6135 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006136 RHS->getAs<ObjCObjectPointerType>(),
6137 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00006138 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006139 return QualType();
6140 }
John McCall183700f2009-09-21 23:43:11 +00006141 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6142 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00006143 return LHS;
6144
Steve Naroffbc76dd02008-12-10 22:14:21 +00006145 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00006146 }
Steve Naroffec0550f2007-10-15 20:41:53 +00006147 }
Douglas Gregor72564e72009-02-26 23:50:07 +00006148
David Blaikie7530c032012-01-17 06:56:22 +00006149 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00006150}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00006151
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006152bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6153 const FunctionProtoType *FromFunctionType,
6154 const FunctionProtoType *ToFunctionType) {
6155 if (FromFunctionType->hasAnyConsumedArgs() !=
6156 ToFunctionType->hasAnyConsumedArgs())
6157 return false;
6158 FunctionProtoType::ExtProtoInfo FromEPI =
6159 FromFunctionType->getExtProtoInfo();
6160 FunctionProtoType::ExtProtoInfo ToEPI =
6161 ToFunctionType->getExtProtoInfo();
6162 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6163 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6164 ArgIdx != NumArgs; ++ArgIdx) {
6165 if (FromEPI.ConsumedArguments[ArgIdx] !=
6166 ToEPI.ConsumedArguments[ArgIdx])
6167 return false;
6168 }
6169 return true;
6170}
6171
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006172/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6173/// 'RHS' attributes and returns the merged version; including for function
6174/// return types.
6175QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6176 QualType LHSCan = getCanonicalType(LHS),
6177 RHSCan = getCanonicalType(RHS);
6178 // If two types are identical, they are compatible.
6179 if (LHSCan == RHSCan)
6180 return LHS;
6181 if (RHSCan->isFunctionType()) {
6182 if (!LHSCan->isFunctionType())
6183 return QualType();
6184 QualType OldReturnType =
6185 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6186 QualType NewReturnType =
6187 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6188 QualType ResReturnType =
6189 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6190 if (ResReturnType.isNull())
6191 return QualType();
6192 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6193 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6194 // In either case, use OldReturnType to build the new function type.
6195 const FunctionType *F = LHS->getAs<FunctionType>();
6196 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00006197 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6198 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006199 QualType ResultType
6200 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006201 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006202 return ResultType;
6203 }
6204 }
6205 return QualType();
6206 }
6207
6208 // If the qualifiers are different, the types can still be merged.
6209 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6210 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6211 if (LQuals != RQuals) {
6212 // If any of these qualifiers are different, we have a type mismatch.
6213 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6214 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6215 return QualType();
6216
6217 // Exactly one GC qualifier difference is allowed: __strong is
6218 // okay if the other type has no GC qualifier but is an Objective
6219 // C object pointer (i.e. implicitly strong by default). We fix
6220 // this by pretending that the unqualified type was actually
6221 // qualified __strong.
6222 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6223 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6224 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6225
6226 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6227 return QualType();
6228
6229 if (GC_L == Qualifiers::Strong)
6230 return LHS;
6231 if (GC_R == Qualifiers::Strong)
6232 return RHS;
6233 return QualType();
6234 }
6235
6236 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6237 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6238 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6239 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6240 if (ResQT == LHSBaseQT)
6241 return LHS;
6242 if (ResQT == RHSBaseQT)
6243 return RHS;
6244 }
6245 return QualType();
6246}
6247
Chris Lattner5426bf62008-04-07 07:01:58 +00006248//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00006249// Integer Predicates
6250//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00006251
Jay Foad4ba2a172011-01-12 09:06:06 +00006252unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00006253 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00006254 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006255 if (T->isBooleanType())
6256 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00006257 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00006258 return (unsigned)getTypeSize(T);
6259}
6260
6261QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00006262 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00006263
6264 // Turn <4 x signed int> -> <4 x unsigned int>
6265 if (const VectorType *VTy = T->getAs<VectorType>())
6266 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00006267 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00006268
6269 // For enums, we return the unsigned version of the base type.
6270 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00006271 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00006272
6273 const BuiltinType *BTy = T->getAs<BuiltinType>();
6274 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006275 switch (BTy->getKind()) {
6276 case BuiltinType::Char_S:
6277 case BuiltinType::SChar:
6278 return UnsignedCharTy;
6279 case BuiltinType::Short:
6280 return UnsignedShortTy;
6281 case BuiltinType::Int:
6282 return UnsignedIntTy;
6283 case BuiltinType::Long:
6284 return UnsignedLongTy;
6285 case BuiltinType::LongLong:
6286 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00006287 case BuiltinType::Int128:
6288 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00006289 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00006290 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006291 }
6292}
6293
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00006294ASTMutationListener::~ASTMutationListener() { }
6295
Chris Lattner86df27b2009-06-14 00:45:47 +00006296
6297//===----------------------------------------------------------------------===//
6298// Builtin Type Computation
6299//===----------------------------------------------------------------------===//
6300
6301/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00006302/// pointer over the consumed characters. This returns the resultant type. If
6303/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6304/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6305/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00006306///
6307/// RequiresICE is filled in on return to indicate whether the value is required
6308/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00006309static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00006310 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00006311 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00006312 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00006313 // Modifiers.
6314 int HowLong = 0;
6315 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00006316 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006317
Chris Lattner33daae62010-10-01 22:42:38 +00006318 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00006319 bool Done = false;
6320 while (!Done) {
6321 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00006322 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006323 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00006324 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006325 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006326 case 'S':
6327 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6328 assert(!Signed && "Can't use 'S' modifier multiple times!");
6329 Signed = true;
6330 break;
6331 case 'U':
6332 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6333 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6334 Unsigned = true;
6335 break;
6336 case 'L':
6337 assert(HowLong <= 2 && "Can't have LLLL modifier");
6338 ++HowLong;
6339 break;
6340 }
6341 }
6342
6343 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00006344
Chris Lattner86df27b2009-06-14 00:45:47 +00006345 // Read the base type.
6346 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00006347 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00006348 case 'v':
6349 assert(HowLong == 0 && !Signed && !Unsigned &&
6350 "Bad modifiers used with 'v'!");
6351 Type = Context.VoidTy;
6352 break;
6353 case 'f':
6354 assert(HowLong == 0 && !Signed && !Unsigned &&
6355 "Bad modifiers used with 'f'!");
6356 Type = Context.FloatTy;
6357 break;
6358 case 'd':
6359 assert(HowLong < 2 && !Signed && !Unsigned &&
6360 "Bad modifiers used with 'd'!");
6361 if (HowLong)
6362 Type = Context.LongDoubleTy;
6363 else
6364 Type = Context.DoubleTy;
6365 break;
6366 case 's':
6367 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6368 if (Unsigned)
6369 Type = Context.UnsignedShortTy;
6370 else
6371 Type = Context.ShortTy;
6372 break;
6373 case 'i':
6374 if (HowLong == 3)
6375 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6376 else if (HowLong == 2)
6377 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6378 else if (HowLong == 1)
6379 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6380 else
6381 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6382 break;
6383 case 'c':
6384 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6385 if (Signed)
6386 Type = Context.SignedCharTy;
6387 else if (Unsigned)
6388 Type = Context.UnsignedCharTy;
6389 else
6390 Type = Context.CharTy;
6391 break;
6392 case 'b': // boolean
6393 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6394 Type = Context.BoolTy;
6395 break;
6396 case 'z': // size_t.
6397 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6398 Type = Context.getSizeType();
6399 break;
6400 case 'F':
6401 Type = Context.getCFConstantStringType();
6402 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00006403 case 'G':
6404 Type = Context.getObjCIdType();
6405 break;
6406 case 'H':
6407 Type = Context.getObjCSelType();
6408 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006409 case 'a':
6410 Type = Context.getBuiltinVaListType();
6411 assert(!Type.isNull() && "builtin va list type not initialized!");
6412 break;
6413 case 'A':
6414 // This is a "reference" to a va_list; however, what exactly
6415 // this means depends on how va_list is defined. There are two
6416 // different kinds of va_list: ones passed by value, and ones
6417 // passed by reference. An example of a by-value va_list is
6418 // x86, where va_list is a char*. An example of by-ref va_list
6419 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6420 // we want this argument to be a char*&; for x86-64, we want
6421 // it to be a __va_list_tag*.
6422 Type = Context.getBuiltinVaListType();
6423 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00006424 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00006425 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00006426 else
Chris Lattner86df27b2009-06-14 00:45:47 +00006427 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00006428 break;
6429 case 'V': {
6430 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00006431 unsigned NumElements = strtoul(Str, &End, 10);
6432 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00006433 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00006434
Chris Lattner14e0e742010-10-01 22:53:11 +00006435 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6436 RequiresICE, false);
6437 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00006438
6439 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00006440 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00006441 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00006442 break;
6443 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00006444 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00006445 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6446 false);
6447 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00006448 Type = Context.getComplexType(ElementType);
6449 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00006450 }
6451 case 'Y' : {
6452 Type = Context.getPointerDiffType();
6453 break;
6454 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006455 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00006456 Type = Context.getFILEType();
6457 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006458 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00006459 return QualType();
6460 }
Mike Stumpfd612db2009-07-28 23:47:15 +00006461 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006462 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00006463 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00006464 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00006465 else
6466 Type = Context.getjmp_bufType();
6467
Mike Stumpfd612db2009-07-28 23:47:15 +00006468 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006469 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00006470 return QualType();
6471 }
6472 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00006473 case 'K':
6474 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6475 Type = Context.getucontext_tType();
6476
6477 if (Type.isNull()) {
6478 Error = ASTContext::GE_Missing_ucontext;
6479 return QualType();
6480 }
6481 break;
Mike Stump782fa302009-07-28 02:25:19 +00006482 }
Mike Stump1eb44332009-09-09 15:08:12 +00006483
Chris Lattner33daae62010-10-01 22:42:38 +00006484 // If there are modifiers and if we're allowed to parse them, go for it.
6485 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00006486 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00006487 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00006488 default: Done = true; --Str; break;
6489 case '*':
6490 case '&': {
6491 // Both pointers and references can have their pointee types
6492 // qualified with an address space.
6493 char *End;
6494 unsigned AddrSpace = strtoul(Str, &End, 10);
6495 if (End != Str && AddrSpace != 0) {
6496 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6497 Str = End;
6498 }
6499 if (c == '*')
6500 Type = Context.getPointerType(Type);
6501 else
6502 Type = Context.getLValueReferenceType(Type);
6503 break;
6504 }
6505 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6506 case 'C':
6507 Type = Type.withConst();
6508 break;
6509 case 'D':
6510 Type = Context.getVolatileType(Type);
6511 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00006512 case 'R':
6513 Type = Type.withRestrict();
6514 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006515 }
6516 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00006517
Chris Lattner14e0e742010-10-01 22:53:11 +00006518 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00006519 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00006520
Chris Lattner86df27b2009-06-14 00:45:47 +00006521 return Type;
6522}
6523
6524/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00006525QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00006526 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00006527 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00006528 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00006529
Chris Lattner5f9e2722011-07-23 10:55:15 +00006530 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00006531
Chris Lattner14e0e742010-10-01 22:53:11 +00006532 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00006533 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00006534 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6535 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006536 if (Error != GE_None)
6537 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00006538
6539 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6540
Chris Lattner86df27b2009-06-14 00:45:47 +00006541 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00006542 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006543 if (Error != GE_None)
6544 return QualType();
6545
Chris Lattner14e0e742010-10-01 22:53:11 +00006546 // If this argument is required to be an IntegerConstantExpression and the
6547 // caller cares, fill in the bitmask we return.
6548 if (RequiresICE && IntegerConstantArgs)
6549 *IntegerConstantArgs |= 1 << ArgTypes.size();
6550
Chris Lattner86df27b2009-06-14 00:45:47 +00006551 // Do array -> pointer decay. The builtin should use the decayed type.
6552 if (Ty->isArrayType())
6553 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00006554
Chris Lattner86df27b2009-06-14 00:45:47 +00006555 ArgTypes.push_back(Ty);
6556 }
6557
6558 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6559 "'.' should only occur at end of builtin type list!");
6560
John McCall00ccbef2010-12-21 00:44:39 +00006561 FunctionType::ExtInfo EI;
6562 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6563
6564 bool Variadic = (TypeStr[0] == '.');
6565
6566 // We really shouldn't be making a no-proto type here, especially in C++.
6567 if (ArgTypes.empty() && Variadic)
6568 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00006569
John McCalle23cf432010-12-14 08:05:40 +00006570 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00006571 EPI.ExtInfo = EI;
6572 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00006573
6574 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00006575}
Eli Friedmana95d7572009-08-19 07:44:53 +00006576
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006577GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6578 GVALinkage External = GVA_StrongExternal;
6579
6580 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006581 switch (L) {
6582 case NoLinkage:
6583 case InternalLinkage:
6584 case UniqueExternalLinkage:
6585 return GVA_Internal;
6586
6587 case ExternalLinkage:
6588 switch (FD->getTemplateSpecializationKind()) {
6589 case TSK_Undeclared:
6590 case TSK_ExplicitSpecialization:
6591 External = GVA_StrongExternal;
6592 break;
6593
6594 case TSK_ExplicitInstantiationDefinition:
6595 return GVA_ExplicitTemplateInstantiation;
6596
6597 case TSK_ExplicitInstantiationDeclaration:
6598 case TSK_ImplicitInstantiation:
6599 External = GVA_TemplateInstantiation;
6600 break;
6601 }
6602 }
6603
6604 if (!FD->isInlined())
6605 return External;
6606
6607 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6608 // GNU or C99 inline semantics. Determine whether this symbol should be
6609 // externally visible.
6610 if (FD->isInlineDefinitionExternallyVisible())
6611 return External;
6612
6613 // C99 inline semantics, where the symbol is not externally visible.
6614 return GVA_C99Inline;
6615 }
6616
6617 // C++0x [temp.explicit]p9:
6618 // [ Note: The intent is that an inline function that is the subject of
6619 // an explicit instantiation declaration will still be implicitly
6620 // instantiated when used so that the body can be considered for
6621 // inlining, but that no out-of-line copy of the inline function would be
6622 // generated in the translation unit. -- end note ]
6623 if (FD->getTemplateSpecializationKind()
6624 == TSK_ExplicitInstantiationDeclaration)
6625 return GVA_C99Inline;
6626
6627 return GVA_CXXInline;
6628}
6629
6630GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6631 // If this is a static data member, compute the kind of template
6632 // specialization. Otherwise, this variable is not part of a
6633 // template.
6634 TemplateSpecializationKind TSK = TSK_Undeclared;
6635 if (VD->isStaticDataMember())
6636 TSK = VD->getTemplateSpecializationKind();
6637
6638 Linkage L = VD->getLinkage();
6639 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6640 VD->getType()->getLinkage() == UniqueExternalLinkage)
6641 L = UniqueExternalLinkage;
6642
6643 switch (L) {
6644 case NoLinkage:
6645 case InternalLinkage:
6646 case UniqueExternalLinkage:
6647 return GVA_Internal;
6648
6649 case ExternalLinkage:
6650 switch (TSK) {
6651 case TSK_Undeclared:
6652 case TSK_ExplicitSpecialization:
6653 return GVA_StrongExternal;
6654
6655 case TSK_ExplicitInstantiationDeclaration:
6656 llvm_unreachable("Variable should not be instantiated");
6657 // Fall through to treat this like any other instantiation.
6658
6659 case TSK_ExplicitInstantiationDefinition:
6660 return GVA_ExplicitTemplateInstantiation;
6661
6662 case TSK_ImplicitInstantiation:
6663 return GVA_TemplateInstantiation;
6664 }
6665 }
6666
David Blaikie7530c032012-01-17 06:56:22 +00006667 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006668}
6669
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00006670bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006671 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6672 if (!VD->isFileVarDecl())
6673 return false;
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00006674 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006675 return false;
6676
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006677 // Weak references don't produce any output by themselves.
6678 if (D->hasAttr<WeakRefAttr>())
6679 return false;
6680
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006681 // Aliases and used decls are required.
6682 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6683 return true;
6684
6685 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6686 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00006687 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00006688 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006689
6690 // Constructors and destructors are required.
6691 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6692 return true;
6693
6694 // The key function for a class is required.
6695 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6696 const CXXRecordDecl *RD = MD->getParent();
6697 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6698 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6699 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6700 return true;
6701 }
6702 }
6703
6704 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6705
6706 // static, static inline, always_inline, and extern inline functions can
6707 // always be deferred. Normal inline functions can be deferred in C99/C++.
6708 // Implicit template instantiations can also be deferred in C++.
6709 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00006710 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006711 return false;
6712 return true;
6713 }
Douglas Gregor94da1582011-09-10 00:22:34 +00006714
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006715 const VarDecl *VD = cast<VarDecl>(D);
6716 assert(VD->isFileVarDecl() && "Expected file scoped var");
6717
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006718 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6719 return false;
6720
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006721 // Structs that have non-trivial constructors or destructors are required.
6722
6723 // FIXME: Handle references.
Sean Hunt023df372011-05-09 18:22:59 +00006724 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006725 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6726 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Sean Hunt023df372011-05-09 18:22:59 +00006727 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6728 RD->hasTrivialCopyConstructor() &&
6729 RD->hasTrivialMoveConstructor() &&
6730 RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006731 return true;
6732 }
6733 }
6734
6735 GVALinkage L = GetGVALinkageForVariable(VD);
6736 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6737 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6738 return false;
6739 }
6740
6741 return true;
6742}
Charles Davis071cc7d2010-08-16 03:33:14 +00006743
Charles Davisee743f92010-11-09 18:04:24 +00006744CallingConv ASTContext::getDefaultMethodCallConv() {
6745 // Pass through to the C++ ABI object
6746 return ABI->getDefaultMethodCallConv();
6747}
6748
Jay Foad4ba2a172011-01-12 09:06:06 +00006749bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00006750 // Pass through to the C++ ABI object
6751 return ABI->isNearlyEmpty(RD);
6752}
6753
Peter Collingbourne14110472011-01-13 18:57:25 +00006754MangleContext *ASTContext::createMangleContext() {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00006755 switch (Target->getCXXABI()) {
Peter Collingbourne14110472011-01-13 18:57:25 +00006756 case CXXABI_ARM:
6757 case CXXABI_Itanium:
6758 return createItaniumMangleContext(*this, getDiagnostics());
6759 case CXXABI_Microsoft:
6760 return createMicrosoftMangleContext(*this, getDiagnostics());
6761 }
David Blaikieb219cfc2011-09-23 05:06:16 +00006762 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00006763}
6764
Charles Davis071cc7d2010-08-16 03:33:14 +00006765CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00006766
6767size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00006768 return ASTRecordLayouts.getMemorySize()
6769 + llvm::capacity_in_bytes(ObjCLayouts)
6770 + llvm::capacity_in_bytes(KeyFunctions)
6771 + llvm::capacity_in_bytes(ObjCImpls)
6772 + llvm::capacity_in_bytes(BlockVarCopyInits)
6773 + llvm::capacity_in_bytes(DeclAttrs)
6774 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6775 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6776 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6777 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6778 + llvm::capacity_in_bytes(OverriddenMethods)
6779 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00006780 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00006781 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00006782}
Ted Kremenekd211cb72011-10-06 05:00:56 +00006783
6784void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6785 ParamIndices[D] = index;
6786}
6787
6788unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6789 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6790 assert(I != ParamIndices.end() &&
6791 "ParmIndices lacks entry set by ParmVarDecl");
6792 return I->second;
6793}